Array
最后更新于
// 创建空的Array, 类型推断
let array1 = [Int]()
var array2 = Array<Int>()
// 创建空的Array, 指定类型
var array3 : [Int] = []
// 通过列表初始化
var array4 = [1,2,3,4,5]
// 调用init方法初始化
var array5 = Array(repeating:0, count:3)
array1.append(11)
array1 += [13,12]
array1.insert(13,at:0)
//
array1.remove(at:5)
// Can't remove last element from an empty collection:
array1.removeLast()array1[0]
array1[1] = 12
// 下标法可以使用区间运算符
array1[1...3] = [2,3,4]for value in array1 {
print("\(value)")
}
for (index, value) in shoppingList.enumerated() {
print("Item \(String(index + 1)): \(value)")
}
var numbers = [1, 2, 3, 4, 5]
var numbersCopy = numbers
numbers[0] = 100
print(numbers)
// Prints "[100, 2, 3, 4, 5]"
print(numbersCopy)
// Prints "[1, 2, 3, 4, 5]"// An integer type with reference semantics
class IntegerReference {
var value = 10
}
var firstIntegers = [IntegerReference(), IntegerReference()]
var secondIntegers = firstIntegers
// Modifications to an instance are visible from either array
firstIntegers[0].value = 100
print(secondIntegers[0].value)
// Prints "100"
// Replacements, additions, and removals are still visible
// only in the modified array
firstIntegers[0] = IntegerReference()
print(firstIntegers[0].value)
// Prints "10"
print(secondIntegers[0].value)
// Prints "100"var numbers = [1, 2, 3, 4, 5]
var firstCopy = numbers
var secondCopy = numbers
// The storage for 'numbers' is copied here
numbers[0] = 100
numbers[1] = 200
numbers[2] = 300
// 'numbers' is [100, 200, 300, 4, 5]
// 'firstCopy' and 'secondCopy' are [1, 2, 3, 4, 5]
let colors = ["periwinkle", "rose", "moss"]
let moreColors: [String?] = ["ochre", "pine"]
let url = URL(fileURLWithPath: "names.plist")
(colors as NSArray).write(to: url, atomically: true)
// true
(moreColors as NSArray).write(to: url, atomically: true)
// error: cannot convert value of type '[String?]' to type 'NSArray'