当我在swift中使用单一类型数组时,我可以使用不同类型的操作(追加,+ =等)将项添加到我的数组中,例如此代码可以工作:
var arr = [1, 2, 3, 4, 5]
arr[0...2] = [-1, -2, -3]
arr += 6
arr.append(-3)
arr += [8, -3, 1, 2]
//arr is now [-1, -2, -3, 4, 5, 6, -3, 8, -3, 1, 2]
但是当我使用多类型项目初始化我的数组时,它们都不起作用:
var arr = ["Hello", -3, 4.5, "Hi"]
var arr2:AnyObject = ["hi", -3.4, 2]
arr[0...2] = [-1, -6.7, "hello"] // Cannot assign to the result of this expression
arr.append(1.2) // 'NSArray' does not have a member named 'append'
arr += [1, "Error", -3.2] // Could not find an overload for '+=' that accepts the supplied arguments
arr2.append("hello") // 'AnyObject' does not have a member named 'append'
arr.arrayByAddingObject("This works!")
arr2.arrayByAddingObject("This works too!")
我意识到当我使用AnyObject时,我的数组变成NSArray(实际上是NSMutableArray)如何使用AnyObject类型创建一个普通的swift数组,这样我就可以使用像' + ='这样的有用操作。或者附加功能。
答案 0 :(得分:2)
因此,您可以通过将数组声明为:
来解决前4个错误var arr:Array<Any> = ["Hello", -3, 4.5, "Hi"]
var arr2:Array<Any> = ["hi", -3.4, 2]
arr[0...2] = [-1, -6.7, "hello"]
arr.append(1.2)
arr += [1, "Error", -3.2]
arr2.append("hello")
现在他们是Swift Arrays
而不是NSArrays
,您无法在其上调用arrayByAddingObject
。
似乎NSArray
的转换会起作用,但这会导致编译器失败(在操场上)。
答案 1 :(得分:2)
您必须将数组声明为AnyObject[]
var arr: AnyObject[] = ["Hello", -3, 4.5, "Hi"]
var arr2: AnyObject[] = ["hi", -3.4, 2]
arr[0...2] = [-1, -6.7, "hello"]
arr += "hello"
arr.append([1, "Error", -3.2])
arr2 += ["hi", "hiya"]
arr2.append("hello")
当您尝试添加具有负浮点值
的数组时,似乎存在错误arr += [1, "No Error", 3, -3]
arr += [-1, "No Error", 3, 3]
arr += -3.2 // no error
arr += [1, "Error", -3.2]