When to use expanded options as part of a type definition

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

      

I see that the main difference between these two properties is that there is no need to initialize the unwrapped property and that you can do a comparison like:

if c.unwrapped == nil{
   // Do whatever
}

      

and the optional property does not allow comparisons with nil.

The point is that it seems to me that creating an expanded property is unsafe, because most likely the code throws more exceptions at runtime when it tries to access expandable properties with null values. However, the optional values ​​will force the developer to take care of the code and initialize the properties to avoid such situations.

So can someone tell me what scripts would be correct for creating expandable properties?

+3


source to share


2 answers


There are some cases where it is not possible to set variables when the object is initialized, but you are more or less guaranteed to set properties before using them. One example of this is IBOutlet

s. They are set after the view controller is created, but before that, for example, they are called viewDidLoad

. This is why they are marked as optional.

Another case is when you want to pass some data to an object. Say that you have a view controller that represents the information passed by the view controller. A view controller can have a property var information: MyCustomObject!

because you know that in order for the view controller to display information on the screen, that property must be set; however, the property cannot be set before the view controller is created. Typically, you instantiate the view controller with segue and then in prepareForSegue:

you must set the property.



Of course it is possible to use options for the examples above, but if you know that an option is optional, you can save a lot if let ...

in the same way as non-options are used (in theory everything could be declared as optional, but why do you all check that the property is set ?).

+3


source


Your approach is correct, creating an unbound property is unsafe because if your expanded value is zero your application will crash. To avoid this, you should use if let

check instead == nil

. For example,

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 is a great conversation aboutoptionals

+2


source







All Articles