递增一个隐式展开的可选 [英] Incrementing an implicitly unwrapped optional

查看:88
本文介绍了递增一个隐式展开的可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我声明一个隐式展开的可选内容为:

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
}

这篇关于递增一个隐式展开的可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆