Incrementing an implicitly unwrapped optional

早过忘川 提交于 2019-12-31 03:26:10

问题


I declare an implicitly unwrapped optional as:

var numberOfRows: Int!

and initialize it in init:

numberOfRows = 25

Later I need to decrement it by one so I write:

numberOfRows--

but this doesn't compile. The error message says the decrement operator can't be applied to an implicitly unwrapped optional. With a little experimentation I find that the following compiles without error:

numberOfRows!--

I would like to understand this. What is the explanation for what seems like the extra '!'?


回答1:


Implicitly unwrapped optional is a type on its own, and is different from the type it that wraps. Some operators on optionals and implicitly unwrapped optionals are pre-defined for you out of the box by the language, but for the rest you have to define them yourself.

In this particular case an operator postfix func --(inout value: Int!) -> Int! is just not defined. If you want to use postfix -- operator on Int! just the same way you use it on Int then you will have to define one.

E.g. something like:

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

    value = _value - 1
    return _value
}



回答2:


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

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

And it can be Some Type like Int for example or None and in this case it's have nil value.

When you make this:

var numberOfRows: Int!

you directly is indicated by the ! that this is not Int type but this is the enum Optional<Int> type. At moment of creation it's will be Some<Int> if equal it value but with this ! you have that it is enum Optional<Int> and in some next moment it will be the None. That's why you have to use ! second time when make this:

numberOfRows!--

Your nomberOfRows value is Optional<Int> type and it may be Int or nil and you have to directly indicate that this is Int type to make -- action.



来源:https://stackoverflow.com/questions/33504945/incrementing-an-implicitly-unwrapped-optional

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!