The real benefits of using implicitly deployed options (declared with!) Are related to class initialization, when two classes point to each other, and you need to avoid a strong reference loop. For example:
Class A ↔ Class B
A procedure of class A init should create (and its own) class B, and B needs a weak appeal to A:
class A { let instanceOfB: B! init() { self.instanceOfB = B(instanceOfA: self) } } class B { unowned let instanceOfA: A init(instanceOfA: A) { self.instanceOfA = instanceOfA } }
Now,
- Class B requires a reference to class A, which must be initialized.
- Class A can only pass
self to the initializer of class B after full initialization. - In order for class A to be considered initialized before class B is created, the
instanceOfB property must be optional.
However, once A was created, it would be very annoying to have access to instanceOfB using instanceOfB! since we know what should be B
To avoid this, instanceOfB is declared as an optional (optional) instance (instanceOfB!), And we can access it using only instanceOfB. (In addition, I suspect that the compiler can also optimize access in different ways).
An example of this is shown on pages 464 through 466 of the book.
Summary:
- Use? if the value can become zero in the future, so you check it out.
- Use! if it really does not become zero in the future, but first it should be zero.
tarmes Jun 06 '14 at 2:47 a.m. 2014-06-06 14:47
source share