递增一个隐式展开的可选

编程入门 行业动态 更新时间:2024-10-28 05:14:08
本文介绍了递增一个隐式展开的可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 }

更多推荐

递增一个隐式展开的可选

本文发布于:2023-11-26 12:22:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633917.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!