Ankish Jain
Ankish Jain

Reputation: 11361

Swift Optionals : What if i need to change an non - optional type to optional

I had designed an custom object which was sure to return a value. Now the whole app is build around that custom object. Now conditions have appeared which can cause the custom object to be nil.

What do I do . Change the type to optional ? and change code everywhere to unwrap. Any other better solutions ?

Upvotes: 4

Views: 5506

Answers (2)

Narendra G
Narendra G

Reputation: 559

Change the type to Optional then that should allows nil values too.Check this below example will help you:

var specialValue :String? = "Some Value"

if let value = specialValue {
     // do some stuff.
}else {
    // Here specialValue is nil value.
}

(or) In Swift 2.0 , we are allowed to use guard.

guard let value = specialValue { return }
print(value)

Upvotes: 0

Tamás Zahola
Tamás Zahola

Reputation: 9311

Change the type to implicitly unwrapped optional. This way you can use it like a regular non-optional value everywhere you know for sure it wouldn't be nil (or where nil would mean an unrecoverable error), and check for nil where it can be nil.

Example:

let stringOrNil:String! = "foo"

if let string = stringOrNil { // used like an optional type
    println(string)
}

println(stringOrNil.isEmpty) // used like a non-optional type, will crash is stringOrNil is nil

Generally you would want to avoid implicitly unwrapped optionals, except for cases where you cannot initialise objects too early for technical reasons, e.g. in the case of interface builder outlets or asynchronously initialised objects, etc.

Upvotes: 4

Related Questions