dimanche 28 juin 2015

When to use ?, !, None, or Lazy?

I just started learning Swift and recently found out about

1) "Normal" variables (for lack of a better name):

ex: var test1: String

2) "Optional" variables

ex: var test2: String?

3) "Implicitly Unwrapped Optionals"

ex: var test3: String!

4) Lazy variables

ex: lazy var test4: String

My understanding is this:

1) Use "Optional" variables (?) when the variable may or may not be initialized at points in the future starting from initialization

2) Use "Implicitly Unwrapped Optionals" (!) when the variable is guaranteed to be initialized

3) Optionals can be converted to Implicitly Unwrapped Optionals via "Forced Unwrapping"

ex: let possibleString: String? = "Hello" println(possibleString!)

4) Use Lazy variables when there is no need for something to be set until initialization (it seems these can be used with (?) or (!))

Therefore, my questions are:

1) When do I use option 1 - a variable without ? and without !

2) When do I use "lazy"

2.1) I read "lazy" is often used for singletons (http://ift.tt/1GINd7P) - why?

I have the most experience in Java and C++ terms, if that helps with my background for answering.

Aucun commentaire:

Enregistrer un commentaire