importCocoa// ## Arraysvarbeatles=["John","Paul","George"]print(beatles)beatles.append("Ringo")print(beatles)letnumbers=[4,8,15,16,23,42]// numbers.append(43) // -> this is not allowed since numbers is constantprint(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 arrayvarnames1=Array<String>()varnames2=[String]()names2.append("John")print(names2)varnames3:[String]=[]// use type hintnames3.append("Doe")print(names3)// array methodvarnumbers2=[13,102,4,1,24]print(numbers2.count)letnum=numbers2.remove(at:0)// 13 will be removed, num is 13print(num)// 13print(numbers2)print(numbers2.sorted())// [1, 4, 24, 102], this will not change numbers2print(numbers2.reversed())// ReversedCollection, lazy operationprint(Array(numbers2.reversed()))// [24, 1, 4, 102]// ## Dictionaryletemployee2=["name":"Taylor Swift","job":"Singer","location":"Nashville"]print(employee2["name"])// Optional("Taylor Swift"), the key may not existprint(employee2["name"]!)// this will unwrap the optional to the actual valueprint(employee2["height",default:"Unknown"])// set the default value// define an empty dictionaryvarheights=[String:Int]()heights["John"]=6print(heights)varheights2:[String:Int]=[:]heights2["John"]=6print(heights2)// get countprint(heights2.count)// 1// ## Setvarnumbers4=Set([1,2,3])print(numbers4.count)// 3numbers4.insert(3)// inserted: falseprint(numbers4.count)// 3print(numbers4.contains(2))// true// define an empty setvarnumbers5=Set<Int>()numbers5.insert(1)numbers5.insert(1)numbers5.insert(5)numbers5.insert(3)print(numbers5.count)// 3print(numbers5)// [5,3,1]letnumbers6=numbers5.sorted()print(numbers6)// numbers6 type is Array, not a Set, b/c set doesn't have order// EnumsenumWeekday{casemondaycasetuesdaycasewednesdaycasethursdaycasefriday}varday=Weekday.mondayday=.tuesdayday=.fridayprint(day)// friday/*
Swift knows that .tuesday must refer to Weekday.tuesday
because day must always be some kind of Weekday.
*/
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)