let emptyArray = [String]()
let emptyDouble: [Double] = []
let preLoadArray = Array(repeating: 0, count: 10) // initializes array with 10 default values of the number 0
let arrayMix = [1, "two", 3] as [Any]
var arrayNum = [1, 2, 3]
var array = ["1", "two", "3"]
array[1] = "2"
array.append("4")
array += ["5", "6"]
array.insert("0", at: 0)
array[0] = "Zero"
array.insert(contentsOf: ["-3", "-2", "-1"], at: 0)
array.remove(at: 0)
array.removeLast()
array = ["Replaces all indexes with this"]
array.removeAll()
for item in arrayMix {
print(item)
}
for (index, element) in array.enumerated() {
print(index)
print(element)
}
for (index, _) in arrayNum.enumerated().reversed() {
arrayNum.remove(at: index)
}
let words = "these words will be objects in an array".components(separatedBy: " ")
print(words[1])
var names = ["Jemima", "Peter", "David", "Kelly", "Isabella", "Adam"]
names.sort() // sorts names in alphabetical order
let nums = [1, 1234, 12, 123, 0, 999]
print(nums.sorted()) // sorts numbers from lowest to highest
var myArray: Array<String> = Array()
var myArray = [String]()
var myArray: [String] = []
var myArray = Array<String>()
var myArray:Array<String> = []
任何类型的数组:-
var myArray: Array<AnyObject> = Array()
var myArray = [AnyObject]()
var myArray: [AnyObject] = []
var myArray = Array<AnyObject>()
var myArray:Array<AnyObject> = []
Integer 类型的数组:-
var myArray: Array<Int> = Array()
var myArray = [Int]()
var myArray: [Int] = []
var myArray = Array<Int>()
var myArray:Array<Int> = []
// Create an empty array
var emptyArray = [String]()
// Add values to array by appending (Adds values as the last element)
emptyArray.append("Apple")
emptyArray.append("Oppo")
// Add values to array by inserting (Adds to a specified position of the list)
emptyArray.insert("Samsung", at: 0)
// Remove elements from an array by index number
emptyArray.remove(at: 2)
// Remove elements by specifying the element
if let removeElement = emptyArray.firstIndex(of: "Samsung") {
emptyArray.remove(at: removeElement)
}
一个类似的答案也给出了,但是对于最新版本的 Swift (Swift 5)并不适用,所以这里是更新后的答案。希望能有帮助!:)
// An array of 'Int' elements
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
// An array of 'String' elements
let streets = ["Albemarle", "Brandywine", "Chesapeake"]
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()