Reputation: 2854
Let's say, we define a class
class C{
var unwrapped : String!
var nonOptional : String
init(nonOptional:String){
self.nonOptional = nonOptional
}
}
And we create an instance of C:
var c = C(nonOptional: "hola")
What I see is that the main difference between the two properties are that it is not necessary to initialize an unwrapped property and that you can do a comparison like:
if c.unwrapped == nil{
// Do whatever
}
while a non-optional property don't let you compare against nil.
The point is that it seems to me that creating unwrapped property is unsafe because likely the code generates more runtime exceptions when you try to access unwrapped properties with nil values. However non-optional values will make the developer to take care of the code and initialize properties to avoid this kind of situations.
So could anyone tell me what scenarios would be proper to create unwrapped properties?
Upvotes: 3
Views: 62
Reputation: 1044
There are some cases where it is not possible to set the variables when the object is initialised, but you are more or less guaranteed to have the properties set before they are used. One example of this is IBOutlet
s. They are set after the view controller is created, but before for instance viewDidLoad
is called. This is why they are marked as an unwrapped optional.
Another case is when you wish to pass some data to an object. Say that you have a view controller that is presenting information passed by the presenting view controller. The view controller may have a property var information: MyCustomObject!
because you know that in order for the view controller to display the information on screen, this property must be set; however, the property cannot be set before/while the view controller is created. You would typically instantiate the view controller from a segue, then in prepareForSegue:
you would set the property.
It is of course possible to use optionals for the above examples, but if you know that the optional is set, you can save lots of if let ...
the same way that non-optionals are used (in theory, everything could be declared as an optional, but why do all the checks of you know that the property is set?).
Upvotes: 3
Reputation: 7013
Your approach is right, creating unwrapped property is unsafe because if your unwrapped value is nil, your app will crash. To avoid that you should use
if let
closure instead of checking == nil
. For instance
class C{
var unwrapped : String?
var nonOptional : String
init(nonOptional:String){
self.nonOptional = nonOptional
}
}
var c = C(nonOptional: "hola")
if let value = c.unwrapped {
/// value is not nil here
}
HERE a great talk about optionals
Upvotes: 2