Toy Project/Swift Language Syntax

5. Swift Collection(Dicionary, Set)

개발자킹콩 2021. 1. 21. 16:36

// Dictionary
// 순서가 없이 key와 value로 구성된다.
// 커피에 이름을 적는 것과 비슷한 구조이다.
// Key는 Unique해야한다.

var scoreDic: [String: Int] = ["Jason": 80, "Jay": 95, "Jake": 90]
var scoreDic1: Dictionary<String, Int> = ["Jason": 80, "Jay": 95, "Jake": 90]
print(scoreDic)
print(scoreDic["Jay"]) // Optional type이다. 없을 수 있기때문
print(scoreDic["duddn"]) // nil 값이 나온다.

if let score = scoreDic["Jay"] {
  print(score)
}

// isEmpty, count
print(scoreDic.isEmpty)
print(scoreDic.count)

// update
scoreDic["Jason"] = 99
print(scoreDic)

// 사용자 추가, 제거
scoreDic["Jack"] = 100
print(scoreDic)
scoreDic["Jack"] = nil
print(scoreDic)

// for loop
for (name, score) in scoreDic {
  print(name, score)
}

for key in scoreDic.keys  {
  print(key)
}
for value in scoreDic.values {
  print(value)
}


// 도전과제!!
// 1 이름, 직업 ,도시에 대해서 본인의 딕셔너리 만들기
// 2 여기서 도시를 부산으로 업데이트하기
// 3 딕셔너리를 받아서 이름과 도시 프린트하는 함수 만들기

var myInfo: [String: String] = ["name": "whduddn", "job": "student", "city": "Daegu"]
var myInfo1: Dictionary<String,String> = ["name": "whduddn", "job": "student", "city": "Daegu"]

 

myInfo["city"] = "Busan"

func printCity(info: Dictionary<String, String>) {
  if let name = info["name"], let city = info["city"] {
    print(name, city)
  } else {
    print("-->Cannot find")
  }
}

printCity(info: myInfo)
print()


// Set
// 순서가 없고 유일한 아이템만 취급하는 집합이다.
var someSet: Set<Int> = [1,2,1,4,3,1]
print(someSet)

print(someSet.isEmpty)

print(someSet.count)

print(someSet.contains(4))

 

someSet.insert(7)

print(someSet)

someSet.remove(1)

print(someSet)

 

 

'Toy Project > Swift Language Syntax' 카테고리의 다른 글

7. Swift Closure 조금더  (0) 2021.01.21
6. Swift Closure basic  (0) 2021.01.21
4. Swift Collection (Array)  (0) 2021.01.21
3. Swift Optional  (0) 2021.01.21
2. Swift Function  (0) 2021.01.21