Swift:添加可选的Ints [英] Swift: adding optionals Ints
问题描述
我声明以下内容:
var x:Int?
var y:Int?
,我想要第三个变量z
,它包含x
和y
的总和.大概是x
& y
是可选的,z
也必须是可选的:
and I'd like a third variable z
that contains the sum of x
and y
. Presumably, as x
& y
are optionals, z
must also be an optional:
var z:Int? = x + y
但这会产生一个编译器错误可选类型'Int?'的值没有解包;您的意思是使用'!'或'?'"
but this gives a complier error "value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'"
如果我打开x
& y
:
If I unwrap x
& y
:
var z:Int? = x! + y!
我收到一个运行时错误x
& y
为nil,所以不能解包.
I get a run-time error as x
& y
are nil, so can't be unwrapped.
我可以达到预期的结果,
I can achieve the desired result as follows:
var z:Int?
if let x1 = x {
if let y1 = y {
z = x1+y1
}
}
但是将2个整数加在一起似乎有点冗长!有没有更好的方法来实现这一目标?
but this seems a bit verbose for adding together 2 integers! Is there a better way of achieving this?
推荐答案
这是我的看法,我认为它更干净:
Here is my take, I think it's cleaner:
let none:Int? = nil
let some:Int? = 2
func + (left: Int?, right:Int?) -> Int? {
return left != nil ? right != nil ? left! + right! : left : right
}
println(none + none)
println(none + some)
println(some + none)
println(some + some)
println(2 + 2)
结果如下:
nil
Optional(2)
Optional(2)
Optional(4)
4
这篇关于Swift:添加可选的Ints的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!