Learn basic Swift syntax for basic types, strings, arrays and dictionaries.
Declare an Integer
let myInt : Int
// or
let anotherInt = 4Declare a String
let firstName : String
firstName = "John"
// or
let lastName = "Doe"Declare a Double with type inference
let myDouble = 4.5Declare an empty String
let emptyString = ""
// or
let anotherEmptyString = String()Iterate through the characters of a String
for character in myString.characters {
print(character)
}Count the numbers of characters of a String
let myString = "Hello"print(myString.characters.count)
Get the first character of a String
var myString = "Hello"
myString[myString.startIndex] // is H
// but returns an error for an empty StringGet the n-th character of a String
let myString = "Hello"
myString.startIndex.advancedBy(4) // is "o"Replace a substring of a String by another String
let myString = "Hello"
let stringToFind = "l"
let stringToReplace = "LL"
myString.stringByReplacingOccurrencesOfString(stringToFind
, withString : stringToReplace) // is "HeLLLLo"Test the beginning of a String and the end of a String
"Hello".hasPrefix("He") // returns true
"Hello".hasPrefix("el") // returns false
"Hello".hasSuffix("lo") // returns trueDeclare an empty Array of Integers.
Add one item.
var myInts = [Int]()
myInts.append(18)Create an Array of String with elements
var shoppingList = ["eggs", "milk", "bread"]Count the number of elements of an Array
myArray.countTest if an Array is empty
myArray.isEmptyGet the element of an Array at a given index
let myArray = [ 2, 4, 5]
myArray[0] // returns 2
myArray[2] // return 5
myArray[3] // returns an Error at runtimeChange the value of an Array at a given index
let myArray = [ 4, 5 , 6]
myArray[1] = 7
// myArray is now : [4 , 7 , 6]Test if an Array includes a given value.
let myArray = ["John", "Paul", "Gringo"]
myArray.contains("Paul") // returns 1
myArray.contains("Toto") // returns nilGet subarray from an Array with a range
ley myArray = ["apples", "bananas", "pears", "tomatoes"]
myArray[1...2] // is ["bananas", "pears"]Create an empty Dictionary where the Key is a String, the value an Int.
Add one element.
var ages = [String : Int]()
ages["John"] = 18Test if a Dictionary is empty.
Count the elements of a Dictionary.
myDictionary.isEmpty
myDictionary.countGet the value at a given Key in a Dictionary
ley myDict = ["John" : 14, "Paul" : 12]
myDict["John"] // returns 14
myDict["Bill"] // returns nilIterate over the keys and values of a Dictionary
for (key, value) in myDictionary {
// do something with key and value
}Iterate over the keys of a Dictionary
for key in myDictionary.keys {
// do something with key
}
Iterate over the values of a Dictionary
for value in myDictionary.values {
// do something with value
}
Create a Dictionary where keys and values are Int
let myDict = [ 1 : 18, 2 : 56]