Reputation: 295
I sometimes see a function which accepts an object as a parameter which has '!' as suffix. I know it means the parameter is an implicitly unwrapped optional. But I don't know what is the difference between the two case. i.e. defining a parameter with '!' and without '!'.
class Cat {
var name: String
init(name: String) {
self.name = name
}
}
func tame(cat: Cat) {
print("Hi, \(cat.name)")
}
func tame2(cat: Cat!) {
print("Hi, \(cat.name)")
}
let cat = Cat(name: "Jack")
tame(cat: cat)
tame2(cat: cat)
As a result there is no difference between the function tame and tame2. If the parameter has a possibility of being nil, I should define the parameter as an optional right?
func tame3(cat: Cat?) {
if let cat = cat {
print("Hi, \(cat.name)")
}
}
In which case should I define a function's parameter as implicitly unwrapped optional like tame2?
Upvotes: 1
Views: 55
Reputation: 285290
In which case should I define a function's parameter as implicitly unwrapped optional like
tame2
?
Short answer: Never.
If the parameter has a possibility of being
nil
, I should define the parameter as an optional right?
Right.
Implicit unwrapped optionals are useful for properties which could not be initialized in an init
method but are supposed to have always a value and for compatibility to bridge Objective-C API to Swift, nothing else.
Upvotes: 3