我声明一个隐式展开的可选内容为:
I declare an implicitly unwrapped optional as:
var numberOfRows: Int!并在init中初始化它:
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 '!'?
推荐答案隐式展开的可选是一种单独的类型,与包装的类型不同.某些 optionals 和隐式解开的optionals 上的运算符是根据语言预先为您预定义的,但是对于其余操作符,您必须自己定义它们.
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.
在这种特殊情况下,只是未定义运算符postfix func --(inout value: Int!) -> Int!.如果要在Int!上使用后缀--运算符,就像在Int上使用后缀--运算符一样,则必须定义一个.
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.
例如像这样:
postfix func --<T: SignedIntegerType>(inout value: T!) -> T! { guard let _value = value else { return nil } value = _value - 1 return _value }更多推荐
递增一个隐式展开的可选
发布评论