DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 3/100)

Swift

  • Array
  • Dictionary
  • Set
  • Enum
import Cocoa // ## Arrays var beatles = ["John", "Paul", "George"] print(beatles) beatles.append("Ringo") print(beatles) let numbers = [4, 8, 15, 16, 23, 42] // numbers.append(43) // -> this is not allowed since numbers is constant print(numbers) // var temperatures = [25.3, 28.2, 26.4, "hello"] // can't save both decimals and strings, an array can only have one type of data // define an empty array var names1 = Array<String>() var names2 = [String]() names2.append("John") print(names2) var names3: [String] = [] // use type hint names3.append("Doe") print(names3) // array method var numbers2 = [13,102,4,1,24] print(numbers2.count) let num = numbers2.remove(at: 0) // 13 will be removed, num is 13 print(num) // 13 print(numbers2) print(numbers2.sorted()) // [1, 4, 24, 102], this will not change numbers2 print(numbers2.reversed()) // ReversedCollection, lazy operation print(Array(numbers2.reversed())) // [24, 1, 4, 102] // ## Dictionary let employee2 = [ "name": "Taylor Swift", "job": "Singer", "location": "Nashville" ] print(employee2["name"]) // Optional("Taylor Swift"), the key may not exist print(employee2["name"]!) // this will unwrap the optional to the actual value print(employee2["height", default: "Unknown"]) // set the default value // define an empty dictionary var heights = [String: Int]() heights["John"] = 6 print(heights) var heights2: [String: Int] = [:] heights2["John"] = 6 print(heights2) // get count print(heights2.count) // 1 // ## Set var numbers4 = Set([1,2,3]) print(numbers4.count) // 3 numbers4.insert(3) // inserted: false print(numbers4.count) // 3 print(numbers4.contains(2)) // true // define an empty set var numbers5 = Set<Int>() numbers5.insert(1) numbers5.insert(1) numbers5.insert(5) numbers5.insert(3) print(numbers5.count) // 3 print(numbers5) // [5,3,1] let numbers6 = numbers5.sorted() print(numbers6) // numbers6 type is Array, not a Set, b/c set doesn't have order // Enums enum Weekday { case monday case tuesday case wednesday case thursday case friday } var day = Weekday.monday day = .tuesday day = .friday print(day) // friday /* Swift knows that .tuesday must refer to Weekday.tuesday because day must always be some kind of Weekday. */ 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)