Appearance
Create and Initilize an Array in Swift
Create an Empty Array
swift
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
Create an Array with some Initial Values
swift
// 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"]
// 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"]
Create an Array with repeated values
swift
var threeDoubles = Array(repeating: 0.0, count: 3)
var threeDoubles = [Double](repeating: 0.0, count: 3)
var threeDoubles = Array(repeating: 0.0, count: 3)
var threeDoubles = [Double](repeating: 0.0, count: 3)
Create an Array by subscript of another Array using Range
swift
let words = ["Hey", "Hello", "Bonjour", "Welcome", "Hi", "Hola"]
let wordsSlice = words[2...4] // ArraySlice<String>
let selectedWords = Array(wordsSlice) // ["Bonjour", "Welcome", "Hi"]
let words = ["Hey", "Hello", "Bonjour", "Welcome", "Hi", "Hola"]
let wordsSlice = words[2...4] // ArraySlice<String>
let selectedWords = Array(wordsSlice) // ["Bonjour", "Welcome", "Hi"]