Assign nil to multiple UIlabels and Uiimageviews at the same time - swift

Cant seem to find an answer to this question.
I want to assign the below "UIlabel" and "UIimageview" nil, how would i do this in the same line?
productimage.image = nil
producttext.text = nil
I've tried the following which doesn't seem to work:
productimage.image = producttext.text = nil // this doesnt work
productimage.image = nil, producttext.text = nil // this doesnt work either
Appreciate any help.

You can use semicolon.
productimage.image = nil; producttext.text = nil

Related

Swift 3 NSArray compare to nil

I'm trying to migrate an objc project to swift3. I'm not sure how can I compare an array to nil. I have found this topic, but that was 2 years ago and the swift's syntax has changed a lot.
If I have a code like this in swift:
let variable = something as? NSArray
if variable == nil {
// do something
}
It won't let me to compare this variable with nil, causing an error "comparing this variable, always returns false". I have tried comparing variable.description with " ", but does it do the same thing?
By "something" i meant:
var variable = dict.object(forKey: someString) as! NSArray
The main thing I wanted to do with this was:
var variable = dict.object(forKey: someString) as! NSArray
if variable == nil {
//create
}
else {
// append
}
That's what the optional unwrapping syntax is for. You can combine the unwrapping and cast into one if statement:
if let variable = something as? NSArray {
// variable is not nil and is an NSArray
// Now you can do something with it.
} else {
// Either something is nil or it is not able to be cast as an NSArray
// Handle this case.
}
I should also mention that if you don't need to use something in Objective-C, then you should use the Swift-native array type. This can be declared like this:
let someArray = ["string1", "string2"]
This line indicates that variable is and must be an NSArray. If dict.object(forKey: someString) is not an NSArray, this will cause a crash
var variable = dict.object(forKey: someString) as! NSArray
// ^
// This exclamation mark means you are certain this is an NSArray
// Also, because there is no question mark after NSArray, this variable
// is not optional. It cannot be nil
However, you then use
if variable == nil {
And this is where the warning comes from. The variable can never be nil, because the variable is not optional
What you probably want is:
if let variable = dict.object(forKey:someString) as? NSArray
This will return false if:
dict.object(forKey:someString) returns a nil object
the object returned is not an NSArray
After this variable is now a non-optional NSArray. It is guaranteed to be an NSArray and is guaranteed to not be nil. You can use it without unwrapping it. e.g.
if let variable = dict.object(forKey:someString) as? NSArray {
for element in variable {
}
}
else {
//The dict doesn't contain the object yet. `variable` is nil
//Create a new array and add it to dict
let newArray = ["First Value"]
dict[someString] = newArray
}
let variable = something as? NSArray
With this declaration, variable will be an optional type (NSArray?) and never nil. This is because casting with as? returns an optional value that either contains the successfully casted object or nothing. You can see this by alt-clicking the variable name in Xcode.
If you want to know whether it contains a value, you need to use the if let syntax:
if let variable = variable {
// variable is guaranteed to be an NSArray here.
}
You can also use this format with guard-else:
guard let variable = something as? NSArray else {
// your variable is nil. Do something if needed
}
// your variable is available in this scope. Do something when variable contains Array

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")
}

CoreData unexpectedly found nil while unwrapping an Optional value

Having an app where I type username, pick a picture from imagePickerController and all that data is saved to core data and retrieved to tableview cell and is working fine, however if I don't choose picture app is crashing with log "unexpectedly found nil while unwrapping an Optional value", I forgot how to do that, can't remember in what project I solved that.
let imageData = NSData(data: UIImageJPEGRepresentation(photoImageView.image!, 1.0)!)
newUser.setValue(imageData, forKey: "image")
Something like if image data != nil {
} ??
Try if let image = photoImageView.image {//use the image}. This will unwrap the optional in a safe way.
Be careful when you use the ! operator, you are basically guaranteeing the thing will never be nil. Use the if let statement or ? operator unless there is absolutely no way that the variable in question could be nil.
solved with this
if photoImageView == nil {
let imageData = NSData(data: UIImageJPEGRepresentation(photoImageView.image!, 1.0)!)
newUser.setValue(imageData, forKey: "image")
}

how to give nil parameter in if condition in 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.

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.