how to give nil parameter in if condition in swift? - swift

In Objective-C:
if (!myImageView) {
NSLog(#"hdhd");
}
else {
//DO SOMETHING
}
But in Swift:
if (!myImageView) {
println("somethin")
}
else {
println("somethin")
}
This code is giving me the error:
Could not find an overload for '!' that accepts the supplied arguments'
myImageView is class variable UIImageView.
What should I do?

Usually, the best way to deal with checking variables for nil in Swift is going to be with the if let or if var syntax.
if let imageView = self.imageView {
// self.imageView is not nil
// we can access it through imageView
} else {
// self.imageView is nil
}
But for this to work (or for comparison against nil with either == nil or != nil), self.imageView must be an optional (implicitly unwrapped or otherwise).
Non-optionals can not be nil, and therefore the compiler will not let you compare them against nil. They'll never be nil.
So if if let imageView = self.imageView or self.imageView != nil or self.imageView == nil are giving you errors, it's almost certainly because self.imageView is not an optional.

If your variable is of type UIImageView then it cannot ever be nil.
However if you want your code to be equivalent to your Objective-C code, change the variable type to UIImageView? (an optional type) and replace:
if (!myImageView) {
with:
if (myImageView == nil) {

Test for myImageView != nil or myImageView.image != nil.

Related

Check if NSSize is nil - Comparing non-optional value of type 'NSSize'?

I have a NSSize variable
var originalselectedimagesize:NSSize
if(originalselectedimagesize == nil)
{
}
I'm trying to check if NSSize is set ? But i keep getting the following warning.How can i check if the value of NSSize is changed?
h(aka 'CGSize') to 'nil' always returns false
Because from the declaration, NSSize is not an optional. So checking a non-optional value for nil always return false.
In case if you have the following, then you won't get the warning.
var originalselectedimagesize:NSSize?
if(originalselectedimagesize == nil)
{
}
You can declare originalselectedimagesize as NSSize? (Optional type of NSSize), and set it to nil. Then, you can check if it has value like this:
var originalselectedimagesize: NSSize? = nil
// what ever...
// check for value
if let size = originalselectedimagesize {
}

Delete picture from UIImageView

I have a core data app with some items and imageviews. Now i would like to delete a picked photo from my imageview1 field.
imageView1.image = nil
and it works and my imageview1 ist empty, but when i save the record my app is crashing with the error:
fatal error: unexpectedly found nil while unwrapping an Optional value.
Whats the problem? Is it possible to "reset" the imageview1.image?
The error itself tells that while unwrapping an optional value, value found was nil. You need to first check if optional value is nil using if let or guard and unwrap(!) only when they are not nil.
If let image = imageView.image {
Item!.image =UIImagePNGRepresentation(imageView1.image!)"
} else {
Item.image = image(named: "placeholderimage")
}

Swift - how to make inner property optional

My question is in regards to optionals in swift. Let say i have the following defined already:
if let myCell = cell as? AECell {
if !myCell.someView.hidden{
//how do i use optional on someView, perhaps someView will not exists
}
}
as you can see, what if someView is nil , how do i use an optional here to only execute the if statement if someView is not nil ..i tried the question mark:
if !myCell.someView?.hidden but its syntax is not correct
if let myCell = cell as? AECell, let someView = myCell.someView {
// someView is unwrapped now
}
This should do it:
if let myCell = cell as? AECell, let myView = myCell.someView where !myView.hidden {
// This gets executed only if:
// - cell is downcast-able to AECell (-> myCell)
// - myCell.myView != nil (-> unwrapped)
// - myView.hidden == false
}
You could use optional chaining
if let myView = (cell as? AECell).someView {
if !myView.hidden{
// do something
}
}
To answer the question directly, yes you can use optionals this way. The someView property of your cell must be defined as optional.
class MyCell: UICollectionViewCell {
var someView: AECell?
}
Then you can use the following syntax:
myCell.someView?.hidden = true
The behavior you're talking about is very much akin to Objective-C's nil messaging behavior. In Swift,you want to lean more towards confirming the existence of an object before manipulating it.
guard let myView = myCell.someView as? AECell else {
// View is nil, deal with it however you need to.
return
}
myView.hidden = false

Swift Optional Binding with a negative result

How can I do an optional binding in Swift and check for a negative result? Say for example I have an optional view controller that I'd like to lazy load. When it's time to use it, I'd like to check if it's nil, and initialize it if it hasn't been done yet.
I can do something like this:
if let vc = viewController? {
// do something with it
} else {
// initialize it
// do something with it
}
But this is kludgey and inefficient, and requires me to put the "do something with it" code in there twice or bury it in a closure. The obvious way to improve on this from objC experience would be something like this:
if !(let vc = viewController?) {
// initialize it
}
if let vc = viewController? {
// do something with it
}
But this nets you a "Pattern variable binding cannot appear in an expression" error, which is telling me not to put the binding inside the parenthesis and try to evaluate it as an expression, which of course is exactly what I'm trying to do...
Or another way to write that out that actually works is:
if let vc = viewController? {
} else {
// initialize it
}
if let vc = viewController? {
// do something with it
}
But this is... silly... for lack of a better word. There must be a better way!
How can I do an optional binding and check for a negative result as the default? Surely this is a common use case?
you can implicitly cast Optional to boolean value
if !viewController {
viewController = // something
}
let vc = viewController! // you know it must be non-nil
vc.doSomething()
Update: In Xcode6-beta5, Optional no longer conform to LogicValue/BooleanType, you have to check it with nil using == or !=
if viewController == nil {
viewController = // something
}
Would this work for you?
if viewController == nil {
// initialize it
}
// do something with it
One way might be to create a defer statement that handles the actions. We can ensure those actions occur after the creation of our object by checking for nil. If we run into nil, instantiate the object and return. Before returning our deference will occur within the scope of some function.
func recreateAndUse() {
defer {
viewController?.view.addSubview(UIView())
viewController!.beginAppearanceTransition(true, animated: true)
}
guard viewController != nil else {
viewController = UIViewController()
return
}
}

Swift bad execution when checking length

I am trying to evaluate the contents of a form field that, when empty is throwing an error.
Here is the outlet code
#IBOutlet var txtUsername : UITextField!
Here is the println for the target field.
println("\(txtUsername)")
<UITextField: 0x10e8280a0; frame = (20 40; 280 30); text = ''; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x10e828b20>; layer = <CALayer: 0x10e828300>>
So, looking at this I would assume that txtUsername.text is empty or == "". But everything I try to do to evaluate this throws an error.
if countElements(txtUsername.text as String) != 0 {
... code here
}
if txtUsername.text.bridgeToObjectiveC().length != 0 {
... code here
}
if txtUsername.text.utf16count != 0 {
... code here
}
if txtUsername.text != "" {
... code here
}
All bring back "EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Also, evaluating whether it is nil doesn't seem to work. The below scripts show that there is something to be evaluated, even though it is blank. The problem is telling whether or not it is blank.
If the field was nil, I would expect it to return false and trigger the else statement.
if let evalText = txtUsername.text{
println("There is something here : \(evalText)")
} else {
println("text is nil")
}
// This returns "There is something here:"
if txtUsername.text{
println("There is something here")
} else {
println("text is nil")
}
// This returns "There is something here"
I have even tried to set the value in a variable, only to have it kick out the error after hitting the "if" statement.
Thanks,
EXC_BAD_INSTRUCTION implies an assertion failure. This is most common when something is nil but you are still trying to operate on it.
The text property of UITextField is an Implicitly Unwrapped Optional (String!). You must first check if it is nil. Your app is crashing because it is nil.
txtUsername.text is an optional in Swift. Even your label is an optional so it's not really safe to use ! when declaring it. But anyway, try using this:
if let currentText = txtUsername.text {
// ... Do something with currentText ...
}
else {
NSLog("Text is nil")
}
To be extra sure you can even check if txtUsername is set in the same way. So in the end you will have this:
if let currentTxtUsername = txtUsername{
if let currentText = currentTxtUsername.text {
// ... Do something with currentText ...
}
else {
NSLog("Text is nil")
}
}
else {
NSLog("Text label is nil")
}
Don't forget to remove the ! in the declaration part though.
Turned out to be an error ghosting issue.
The actual problem was that it would get further down in the code and run into a situation where I was inadvertently trying to put nil data from a core data object back into the text string. Setting a text field to nil doesn't work, but rather than error where the problem was, it erred at the "if" statement 20 lines above it.
Below is the full code, and some description of the issue.
#IBAction func btnLoad(sender : AnyObject) {
var appDel = (UIApplication.sharedApplication().delegate as AppDelegate)
var context = appDel.managedObjectContext
var request = NSFetchRequest(entityName: "Users")
request.returnsObjectsAsFaults = false
// Here is the place where it throws the error.
if txtUsername.text == "" {
request.predicate = NSPredicate(format: "username = %#", "\(txtUsername.text)")
}
var results = context.executeFetchRequest(request, error: nil)
println(results)
if(results.count > 0){
var res = results[0] as NSManagedObject
println("\(res)")
//*** The database had nil values for the result selected. And nil doesn't go into a text field.
txtUsername.text = res.valueForKey("username") as String
txtPassword.text = res.valueForKey("password") as String
responseLabel("User Found")
} else {
responseLabel("No Users Found")
}
}
Thanks everyone for replying.