Increase Implicitly Expanded Optional

I declare implicitly deployed as optional as:

var numberOfRows: Int! 

and initialize it in init:

 numberOfRows = 25 

Later I need to reduce it by one, so I write:

 numberOfRows-- 

but it does not compile. The error message says that the decrement operator cannot be applied to an implicitly expanded optional. With a little experiment, I found that the following compilation without errors:

 numberOfRows!-- 

I would like to understand that. What is the explanation for what seems like an extra “!”?

+2
source share
2 answers

An optional type is implicitly expanded at its discretion and differs from the type that it wraps. Some operators on options and implicitly expandable options are predefined for you out of the box by the language, but for the rest you must define them yourself.

In this particular case, the postfix func --(inout value: Int!) -> Int! operator postfix func --(inout value: Int!) -> Int! just not defined. If you want to use the postfix operator -- on Int! just like you use it on Int , you will need to define it.

eg. sort of:

 postfix func --<T: SignedIntegerType>(inout value: T!) -> T! { guard let _value = value else { return nil } value = _value - 1 return _value } 
+3
source

If we look at what type optional , we will see that it is enum like:

 enum Optional<T> { case Some(T) case None } 

And it can be Some Type like Int for example or None , in which case it has the value nil .

When you do this:

 var numberOfRows: Int! 

you indicate directly ! that it is not an Int type, but it is an enum Optional<Int> . At the time of creation there will be Some<Int> if it is equal, but with this ! you have it enum Optional<Int> , and the next next moment it will be None . That is why you should use ! the second time you do this:

 numberOfRows!-- 

Your nomberOfRows value is of type Optional<Int> and can be Int or nil , and you need to directly indicate that it is an Int type, to do this -- action.

0
source

Source: https://habr.com/ru/post/1237314/


All Articles