Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift if value is nil set default value instead

Tags:

swift

I have this code part:

let strValue = String()
textfield.stringValue = strValue!

The problem is that strValue can be nil.

For this I check it like this:

if strValues.isEmpty() {
   textfield.stringValue = ""
} else {
   textfield.stringValue = strValue!
}

But I there an quicker and easier way to do this?

I read something like ?? to solve it. But I don't know how to use it?

UPDATE thanks a lot for the many feedbacks. now i unterstand the ?? operator, but how i realize it in this situation?

let person = PeoplePicker.selectedRecords as! [ABPerson]
let address = person[0].value(forProperty: kABAddressProperty) as?
        ABMultiValue
txtStreet.stringValue = (((address?.value(at: 0) as! NSMutableDictionary).value(forKey: kABAddressStreetKey) as! String))

how can i usee the ?? operator in the last line of my code?

UPDATE 2 Okay i got it!

txtStreet.stringValue = (((adresse?.value(at: 0) as? NSMutableDictionary)?.value(forKey: kABAddressStreetKey) as? String)) ?? ""
like image 580
Ghost108 Avatar asked Jul 01 '17 17:07

Ghost108


People also ask

Is nil a value in Swift?

In Swift, nil means the absence of a value. Sending a message to nil results in a fatal error. An optional encapsulates this concept. An optional either has a value or it doesn't.

What should you use to provide a default value for a variable in Swift?

You can give your own parameters a default value just by writing an = after its type followed by the default you want to give it.

Does null exist in Swift?

NULL has no equivalent in Swift. nil is also called nil in Swift. Nil has no equivalent in Swift. [NSNull null] can be accessed in Swift as NSNull()

How do you check if a variable is null in Swift?

Swift – Check if Variable is not nil If optional variable is assigned with nil , then this says that there is no value in this variable. To check if this variable is not nil, we can use Swift Inequality Operator != .


1 Answers

you can do like this but your strValue should be optional type

let strValue:String?
textfield.stringValue = strValue ?? "your default value here"
like image 177
Irshad Ahmad Avatar answered Sep 28 '22 02:09

Irshad Ahmad