[swift] Collection
2023. 2. 17. 13:42ㆍ👩🏻💻 ios 앱개발 ( swift )
728x90
🦴 Collection의 type 3가지
- Array
- Dictionary
- Set
🦴 Array
//두 가지 형태로 array를 만들 수 있다.
let evenNumbers: [Int] = [2, 4, 6, 8]
let evenNumbers2: Array<Int> = [2, 4, 6, 8]
배열이 비어있을수도(nil) 있기 때문에 optional형태로 출력된다.
부드럽게 박스 열기 방법으로 열어줌.
🦴 Dictionary
//Dictonary
var scoreDic = ["Jason":80, "Jay":95, "Jake":90]
//var scoreDic: [String: Int] = ["Jason":80, "Jay":95, "Jake":90]
//var scoreDic: Dictionary<String, Int> = ["Jason":80, "Jay":95, "Jake":90]
//var scoreDic:
print("\n",scoreDic)
scoreDic["Jake"]
scoreDic["Jerry"]
scoreDic.isEmpty
scoreDic.count
scoreDic["Jason"] = 99
scoreDic
scoreDic["Jack"] = 100
scoreDic
scoreDic["Jack"] = nil //dictnary에서 데이터 삭제하는 방법
scoreDic
print()
for (name, score) in scoreDic{
print("\(name) : \(score)")
}
print("\n---> 키만 가져와서 볼 때")
for key in scoreDic.keys {
print("key: \(key)")
}
//1. 이름, 직업, 도시에 대해서 본인의 딕셔너리를 만들어보기
//2. 여기서 도시를 부산으로 업데이트
//3. 딕셔너리를 받아서 이름과 도시 출력하는 함수 만들기
var infoDic = ["name": "김감자", "job": "학생", "city": "양재"]
infoDic["city"] = "부산"
func printInfo(dic : [String: String]){
//optional binding 이용
if let myname = dic["name"], let mycity = dic["city"] {
print("이름: \(myname), 도시: \(mycity)")
}
else{
print("cannot find")
}
}
print("\n---> 딕셔너리를 받아서 이름과 도시 출력하는 함수")
printInfo(dic: infoDic)
🦴 Set
'👩🏻💻 ios 앱개발 ( swift )' 카테고리의 다른 글
[swift] Closure & Collection **연습하기(reduce, filter, map) (3) | 2023.02.24 |
---|---|
[swift] Closure (0) | 2023.02.22 |
[swift] optional (0) | 2023.02.16 |
[ swift ] Function (0) | 2023.02.14 |
[swift] switch문 (0) | 2023.02.13 |