如何向Array添加数字?迅速

时间:2016-01-24 12:18:34

标签: swift

例如:

onCreateView

2 个答案:

答案 0 :(得分:2)

如果您在myArray按住Option键并单击,您会看到它的类型为[String]String数组)。您只能将String添加到myArray

如果您希望能够将Int添加到阵列,则需要更具包容性的类型。如果您创建数组[Any],则可以在其中添加任何内容。

var myArray:[Any] = ["first string","second string"]
myArray.append(35)   // This now works

如果您只想存储IntString,则可以创建自己的自定义协议:

protocol StringsAndInts {
}

extension String: StringsAndInts {
}

extension Int: StringsAndInts {
}

var myArray:[StringsAndInts] = ["first string","second string"]

myArray.append(35)

print(myArray)  // ["first string", "second string", 35]

myArray.append(3.14)  // error: argument type 'Double' does not conform to expected type 'StringsAndInts'

答案 1 :(得分:1)

如果你写

var myArray = ["first string","second string"]
print(myArray.dynamicType)

您会看到myArray的类型为Array<String>[String]。您无法在{。}}附加Int

您需要做的是自己指定myArray的类型:

var myArray : [AnyObject] = ["first string","second string"]

print(myArray.dynamicType) // now prints Array<AnyObject> which you can add Int to

myArray.append(35)