[iOS] Swift Collection type - Array, Dictionary, Set 사용하기

김말이·2023년 7월 23일
0

Array

순서가 있는 리스트 컬렉션

var integers: Array<Int> = Array<Int>()
var integers: Array<Int> = [Int]()
var integers: [Int] = []
// 불변 Array
let immutableArray = [1, 2, 3] 

integers.append(1)
integers.append(0.1) // Error

integers.remove(at:0) // 인덱스 번호
integers.removeLast()
integers.removeAll()

integers.contains(1) // true/false
integers.count

Dictionary

키와 값의 쌍으로 이루어진 컬렉션

var dict: Dictionary<String, Any> = [String: Any]()
var emptyDict: [String: String] = [:]
// 불변 Dictionary
let initDict: [String: String] = ["name": "shine", "id": "kijrary"] 

dict["firstKey"] = "value"
dict["secondKey"] = 100

dict["firstKey"] = "dictionary" // 값 수정

dict.removeVaue(forKey: "secondKey")

let someValue: String = initDict["name"] // Error - (1)

(1) - Optional로 인한 오류

Optional 타입 사용

Swift의 Dictionary에서 키를 사용하여 값을 찾을 때, 해당 키에 매핑된 값이 항상 존재한다고 보장할 수 없으므로 Optional 타입으로 반환된다. 따라서 initDict["name"]의 결과는 String? (Optional String) 타입이 된다.

Optional 해제

Optional type은 값을 포함하거나, 아무 값도 포함하지 않는 두 가지 상태를 나타낸다. 값을 사용하기 위해서는 Optional을 해제해야 한다.

따라서, initDict["name"]의 결과가 String?이기 때문에 값을 사용하려면 Optional을 해제해야 한다.

Optional 강제 해제 (Forced Unwrapping):

let someValue: String = initDict["name"]! // Optional 강제 해제

이 방법은 값이 nil일 경우 런타임 오류가 발생할 수 있기 때문에 권장되지 않는다.

Optional Binding:

if let nameValue = initDict["name"] {
    // 값이 존재하면 옵셔널이 해제되고, nameValue에 할당
    let someValue: String = nameValue
    // 이곳에서 nameValue를 사용할 수 있음
    print(someValue) // "shine"
} else {
    // 값이 없는 경우 처리
    print("No value found for 'name' key.")
}

Optional Binding을 사용하면 값이 존재할 경우에만 해당 값을 변수에 할당하고, 값이 없는 경우에는 처리할 수 있다. 이 방법은 안전하게 Optional을 해제하는 방법이다.

Set

순서가 없고, 멤버가 유일한 컬렉션

var exampleSet: Set<Int> = Set<Int>()
var secondSet: Set<Int> = [1, 2, 3, 4]

exampleSet.insert(1)
exampleSet.removeFirst()
exampleSet.remove(1)

exampleSet.contains(1) // true/false
exampleSet.count

let union: Set<Int> = exampleSet.union(secondSet)
let sortUnion: [Int] = union.sorted() // 배열로 저장해야 정렬결과가 표현됨
// 교집합
let intersection: Set<Int> = exampleSet.intersection(secondSet)
// 차집합(exampleSet-secondSet)
let subtracting: Set<Int> = exampleSet.subtracting(secondSet)
profile
공부해서 남주자

1개의 댓글

comment-user-thumbnail
2023년 7월 23일

정보 감사합니다.

답글 달기