Created
December 19, 2019 12:22
-
-
Save tombaranowicz/303e47f157694800c6ac33768358293b to your computer and use it in GitHub Desktop.
Swift Collections - Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
//CREATE | |
//declaration using type annotation syntax (arrays are strongly typed) | |
let stringArray : Array<String> | |
//initialiser syntax uses type inference mechanism | |
var intArray = Array<Int>() | |
let shorterIntArray = [Int]() | |
//array literals syntax - usually used to initialise with predefined list of values | |
let literalIntArray: [Int] = [] | |
//immutable version of array | |
let immutableIPhones = ["11", "11 Pro", "11 Pro Max"] | |
//mutable array | |
var iPhones = ["11", "11 Pro", "11 Pro Max"] | |
//check elements | |
iPhones.count | |
iPhones.isEmpty | |
//MODIFY | |
//add elements | |
iPhones.append("XR") | |
iPhones.append(contentsOf: ["8", "8 Plus"]) | |
//print(iPhones) | |
iPhones.insert("7", at: 0) | |
//print(iPhones) | |
//remove elements | |
//iPhones.removeFirst() //LIFO | |
//iPhones.removeLast() //FIFO | |
//iPhones.remove(at: 0) | |
//print(iPhones) | |
//UPDATE | |
//iPhones[0] = "5s" | |
//print(iPhones) | |
//SORT | |
//let sortedIPhones = iPhones.sorted() //elements that conform to the Comparable protocol | |
//print(sortedIPhones) | |
//COPY | |
//like all collection types in the standard library, arrays have value semantics - when you assign an existing array to another variable, the array content is copied. | |
var iPhonesCopy = iPhones | |
iPhonesCopy.removeLast() | |
print(iPhonesCopy) | |
print(iPhones) | |
//ACCESS ELEMENTS | |
//let firstIPhone = iPhones[0] | |
let firstIPhone = iPhones.first | |
let lastIPhone = iPhones.last | |
//ITERATE | |
//iterate over all elements | |
for iPhone in iPhones { | |
// print(iPhone) | |
} | |
//iterate over all elements and skip first | |
for iPhone in iPhones.dropFirst() { | |
// print(iPhone) | |
} | |
//iterate over all elements and skip last | |
for iPhone in iPhones.dropLast() { | |
// print(iPhone) | |
} | |
//iterate over all elements and get index of element | |
for (index, iPhone) in iPhones.enumerated() { | |
// print("\(index). \(iPhone)") | |
} | |
//FIND ELEMENT | |
//let firstNotNewIPhone = iPhones.firstIndex { (iPhone) -> Bool in | |
// return !iPhone.contains("11") | |
//} | |
//print(firstNotNewIPhone) | |
//TRANSFORM | |
let uppercasedIPhones = iPhones.map({ $0.uppercased() }) | |
print(uppercasedIPhones) | |
let onlyNewIphones = iPhones.filter { (iPhone) -> Bool in | |
return iPhone.contains("11") | |
} | |
print(onlyNewIphones) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment