[Swift] Dictionary / Set

Dzeko·2021년 8월 1일

Swift 기본

목록 보기
16/20
post-thumbnail

Dictionary

순서가 없고 key - value로 이루어짐
값을 의미단위로 찾을 때 용이

var scoreDic1: [String: Int] = ["Gerrard": 95, "Lampard":90, "Scholes": 80]
var scoreDic2: Dictionary<String, Int> = ["Son": 85, "Salah": 95, "Dzeko":70]

scoreDic2["Son"]
scoreDic2["Salah"]
scoreDic2["Gerrard"]

scoreDic1.isEmpty
scoreDic1.count

// 변경
scoreDic1["Scholes"] = 75

// 추가
scoreDic1["Ballack"] = 80

// 삭제
scoreDic1["Scholes"] = nil

for (key, value) in scoreDic1 {
    print("\(key) and \(value)")
}

도전과제

1. 이름, 직업, 도시에 대한 본인의 딕셔너리

var myDictionary: [String: String] = ["이름":"김제코","직업":"축구선수","도시":"보스니아"]

2. 도시를 부산으로 업데이트하기

myDictionary["도시"] = "부산"
myDictionary

3. 딕셔너리를 받아서 이름과 도시를 프린트하는 함수 만들기

func printNameAndCity(){
    print("나는 \(myDictionary["도시"]!)의 \(myDictionary["이름"]!)이다!")
}

func printNameNCity(dic: [String:String]) {
    if let name = dic["이름"], let city = dic["도시"] {
        print("나는 \(city)의 \(name)이다!")
    } else {
        print("정보가 없습니다")
    }
}
printNameNCity(dic: myDictionary)

Set

순서, 중복이 없는 유일한 item을 가지는...집합과 같은 느낌

var someSet : Set<Int> = [1, 2, 3, 4, 1, 3, 4]

비었는지 / elements

someSet.isEmpty
someSet.count

포함하는지

someSet.contains(1)
someSet.contains(5)

넣기

someSet.insert(43)
someSet

빼기

someSet.remove(1)
someSet

0개의 댓글