타입 설명
Array : 순서가 있는 리스트 컬렉션
Dictionary : 키와 값의 쌍으로 이루어진 컬렉션
Set : 순서가 없고, 멤버가 유일한 컬렉션
Array
var integers: Array<Int> = Array<Int>() // 같은 표현 var integers: Array<Int> = [Int]() var integers: Array<Int> = [] var integers: [Int] = Array<Int>() var integers: [Int] = [Int]() var integers: [Int] = [] var integers = [Int]() // 추가 integers.append(1) // 존재 확인 print(integers.contains(1)) // true // 교체 integers[0] = 100 // 삭제 integers.remove(at: 0) integers.removeLast() integers.removeAll() // 멤버 수 확인 print(integers.count) //let을 사용하여 선언하면 불변 배열
Dictionary
var anyDictionary: Dictionary <String, Any> = Dictionary <String, Any>() var anyDictionary: Dictionary <String, Any> = Dictionary [:] var anyDictionary: [String : Any] = Dictionary <String, Any>() var anyDictionary: [String : Any] = [String : Any]() var anyDictionary: [String : Any] = [:] var anyDictionary = [String : Any]() anyDictionary["someKey"] = "value" anyDictionary["anotherKey"] = 100 print(anyDictionary) // ["someKey": "value", "anotherKey": 100] // 키에 해당하는 값 변경 anyDictionary["someKey"] = "dictionary" print(anyDictionary) // ["someKey": "dictionary", "anotherKey": 100] // 키에 해당하는 값 제거 anyDictionary.removeValue(forKey: "anotherKey") anyDictionary["someKey"] = nil print(anyDictionary) //let을 사용하여 Dictionary를 선언하면 불변 Dictionary가 된다 let emptyDictionary: [String: String] = [:] let initalizedDictionary: [String: String] = ["name": "jahlee", "gender": "male"] // 불변 Dictionary이므로 값 변경 불가 //emptyDictionary["key"] = "value" // "name"이라는 키에 해당하는 값이 없을 수 있으므로 // String 타입의 값이 나올 것이라는 보장이 없다. // 컴파일 오류가 발생합니다 // let someValue: String = initalizedDictionary["name"]
Set
var intergerSet: Set<Int> = Set<Int>() intergerset.insert(1) intergerset.insert(2) intergerset.insert(3) print(intergerset.contains(1))// true intergerset.remove(1) intergerset.removeFirst() print(intergerset.count(1)) let setA: Set<Int> = [1, 2, 3, 4, 5] let setB: Set<Int> = [3, 4, 5 ,6 ,7] // 합집합 let union Set<Int> = setA.union(setB) // 정렬 let sortedUnion: Set<Int> = union.sorted() // 교집합 let intersection: Set<Int> = setA.intersection(setB) // 차집합 let subtraction: Set<Int> = setA.subtraction(setB)