在 Swift 中向可选数组添加元素 [英] Adding elements to optional arrays in Swift
问题描述
在可选数组的末尾附加元素的正确方法是什么?假设我有一个可选数组 myArray,我想在末尾附加99".Append() 不适用于 nil 数组,因此我能找到的唯一解决方案如下,但它似乎不太优雅:
What is the proper way to append an element on the end of an optional array? Let's say I have an optional array, myArray, and I want to append '99' on the end. Append() does not work on a nil array, so the only solution I can find is the following, but it doesn't seem very elegant:
var myArray = [Int]?()
if myArray?.count > 0 {
myArray?.append(99)
} else {
myArray = [99]
}
推荐答案
你可以使用这样一个事实,即通过可选链调用的方法总是返回一个可选值,如果它是,它就是 nil
不可能调用方法:
You can use the fact that methods called via optional chaining always return an optional value, which is nil
if it was not possible to
call the method:
if (myArray?.append(99)) == nil {
myArray = [99]
}
如果 myArray != nil
然后 myArray?.append(99)
追加新元素并返回Void
,这样if-block就不会被执行.
If myArray != nil
then myArray?.append(99)
appends the new element
and returns Void
, so that the if-block is not executed.
如果 myArray == nil
那么 myArray?.append(99)
什么都不做并返回nil
,以便执行 if-block 并分配一个数组值.
If myArray == nil
then myArray?.append(99)
does nothing and returns
nil
, so that the if-block is executed and assigns an array value.
这篇关于在 Swift 中向可选数组添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!