There are a few different ways of how to create an Array with default values in Swift. Below are a few Swift code examples of creating an Array. Each example creates an array with some initial values.
Create an Array of Strings
var appleProgrammingLanguages: [String] = ["Swift", "Objective-C"]
Thanks to Swift’s type inference, you don’t have to write the type of the array if you’re initializing it with an array literal containing values of the same type.
var otherProgrammingLanguages = ["Javascript", "PHP"]
Create an Array of Int
var randomNumbers: [Int] = [0, 5, 15, 43]
or
var randomNumbers = [0, 5, 15, 43]
Create an Array of Int with Default Values
var arrayOfThreeElements = [Int](repeating: 1, count: 3)
or
var arrayOfThreeElements = (repeating: 1, count: 3)
Dictionary with Default Values
let skills = [ "Sergey": "Java", "Sandip": "Swift" ]
Create a New Array by Adding Two Arrays Together
var myProgrammingLanguages = appleProgrammingLanguages + otherProgrammingLanguages print(myProgrammingLanguages)
For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.