Dictionary
key 와 value의 쌍. generic structure
@frozen struct Dictionary<Key, Value> where Key : Hashable
where문은 부가적인 조건을 추가하거나 타입에 대한 제약을 추가할때 사용
has function
을 이용하여 kim(데이터)이라는 사람이 01(인덱스/key/버킷)이라는 key값을 가질때 123-1234(해시값/value/엔트리)라는 전화번호를 저장한다.
Hashable 프로토콜은 정수 해시값을 갖는다. -> 대부분의 기본 자료형이 가능하다.
Dictionary의 제약조건
데이터를 key-value 쌍의 형태로 저장하고 관리
배열과 비슷한 목적의 작업을 하지만 순서가 없다
dictionary에 저장된 각 항목은 값을 참조하고 접근하는데 사용되는 유일한 key와 연결되어 있다
dictionary의 키는 hash가능한 타입이어야 한다
기본타입(String, Int, Double, Bool 등) 은 hash 가능하여 key값으로 사용 가능하다
optional, Array, Set도 key로 가능하다
Dictionary는 generic 구조체
var x = [Int:String]() //빈 dictionary
var y : Dictionary<String,String> = [:] //빈 dictionary
var a1 : [Int:String] = [1:"one", 2:"two", 3:"three"]
var a2 : Dictionary<Int,String> = [1:"one", 2:"two", 3:"three"]
var a3 = [1:"one", 2:"two", 3:"three"] //Dictionary<Int,String>
var b1 : [String:Double] = ["김보통":60.5,"이갈비":42.7,"엄청군":123.4]
var b2 : Dictionary<String,Double> = ["김보통":60.5,"이갈비":42.7,"엄청군":123.4]
var b3 = ["김보통":60.5,"이갈비":42.7,"엄청군":123.4] //Dictionary<String,Double>
let colors = ["빨강":"red","초록":"green","파랑":"blue"]
var c1 : [String:String] = ["빨강":"red","초록":"green","파랑":"blue"]
var c2 : Dictionary<String,String> = ["빨강":"red","초록":"green","파랑":"blue"]
//Dictionary<String,String>
Dictionary 항목 접근/변경/삭제
var number : [Int:String] = [1:"one", 2:"two", 3:"three"]
print(number)
print(number.count)
//key가 Int타입 일때는 Array 일수도 Dictionary일수도 잇다.
print(number[1],number[2],number[3]) // optional("one") optional("two") optional("three")
//key값이 없을 수 있어서 옵셔널로 값이 추출된다.
print(number[1]!,number[2]!,number[3]!) //one two three
print(number[0]) //nil
number[0] = "zero" //0 : zero 의 키-값 을 dictionary에 집어 넣는다
print(number)
number[4] = "four" //dictionary는 순서가 없어 항상 랜덤의 순서로 출력된다
print(number)
number.updateValue("둘", forKey: 2) // key값 2의 value를 "둘"로 바꿈
print(number)
number[2] = nil // 2라는 key 의 value 를 nil 로 만듬 -> 값을 삭제
print(number) //[1:"one", 3:"three"]
number.removeValue(forKey: 1) //key 1 의 value 삭제
print(number) //[3:"three"
var w : [String:Double] = ["김보통":60.5,"이갈비":42.7,"엄청군":123.4]
w["홍길동"] = 57.7 // 새로운 key-value 가 추가 된다.
w["이갈비"] = 40 // 이갈비(key) 의 value 를 40 으로 바꾼다
w.updateValue(62.5, forKey: :"김보통") //김보통(key)의 value를 62.5로 뱌꾼다
w["홍길동"] = nil // 홍길동(key)의 값(vaule)를 nil로 바꾼다 -> 삭제한다
Dictionary key 로 value 얻기 주의사항
var number : [Int:String] = [1:"one", 2:"two", 3:"three"]
if let num = number[1] {
print(num)
} //Dictionary 값은 옵셔널이기 때문에 강제 언래핑 보다는 옵셔널 바인딩으로 value를 추출한다
for - in 으로 dictionary 항목 접근
let colors = ["빨강":"red","초록":"green","파랑":"blue"]
for color in colors {
print(color)
} // (key: "빨강", value: "red")
// (key: "초록", value: "green")
// (key: "파랑", value: "blue")
for (k,e) in colors { // 튜플을 활용
print(k,e)
} //초록 green
//빨강 red
//파랑 blue
for cKey in colors.keys { //반드시 key 뒤에 s 붙여야 한다
print(cKey)
} //초록
//빨강
//파랑
for cValue in colors.values { //반드시 value 뒤에 s 붙여야 한다
print(cValue)
} //green
//blue
//red
Dictionary 정렬
let colors = ["빨강":"red","초록":"green","파랑":"blue"]
var order = colors.keys.sorted() //key 오름차순 정렬
print(order) //["빨강", "초록", "파랑"]
order = colors.keys.sorted(by: >) //key 내림차순 정렬
print(order) //["파랑", "초록", "빨강"]
order = colors.values.sorted() //value 오름차순 정렬
print(order) //["blue", "green", "red"]
order = colors.values.sorted(by: >) //value 내림차순 정렬
print(order) //["red", "green", "blue"]
var oColor = colors.sorted(by: <) //dictionary 자체를 오름차순 정렬
print(oColor) //key를 기준으로 정렬됨
//[(key: "빨강", value: "red"), (key: "초록", value: "green"), (key: "파랑", value: "blue")]
oColor = colors.sorted(by: >) //dictionary 자체를 내림차순 정렬
print(oColor) //key를 기준으로 정렬됨
//[(key: "파랑", value: "blue"), (key: "초록", value: "green"), (key: "빨강", value: "red")]
key 나 value 로 Array 만들기
let colors = ["빨강":"red","초록":"green","파랑":"blue"]
var kColor = colors.keys
print(kColor) //["파랑", "초록", "빨강"]
print(type(of: kColor)) //Keys
var kColor1 = [String](colors.keys)
print(kColor1) //["파랑", "초록", "빨강"]
print(type(of: kColor1)) //Array<String>
var eColor = colors.values
print(eColor) //["blue", "green", "red"]
print(type(of: eColor)) //Values
var eColor1 = [String](colors.values)
print(eColor1) //["blue", "green", "red"]
print(type(of: eColor1)) //Array<String>
Dictionary count / isEmpty
let colors = ["빨강":"red","초록":"green","파랑":"blue"]
var y : Dictionary<String,String> = [:] // 빈배열은 항상 자료형을 써줘야 한다!
if colors.isEmpty {
print("비어있습니다")
} else {
print(colors.count)
}
if y.isEmpty {
print("비어있습니다")
} else {
print(y.count)
}
참고자료 : https://developer.apple.com/documentation/swift/dictionary
Set
var x = Set<Int>() //빈 set
var y = Set<String>()
var z = Set<Character>()
z.insert("A") //set 항목 추가
z.insert("B")
z.insert("A") //중복된 항목은 추가 되지 않는다.
z.remove("B") //항목 삭제
print(z.contains("A")) // "A" 가 있으면 true 없으면 false
z.removeAll() // 전부 삭제
z = [] // 다시 빈set 만들기
print(z) // []
print(type(of: z)) // Set<Character>
var number3 : Set = [3, 6, 9, 12]
print(type(of: number3)) // 타입 추론
var fruit : Set<String> = ["apple", "orange", "banana"]
var z = Set<Character>()
if fruit.isEmpty {
print("비어있습니다")
} else {
print(fruit.count)
}
if z.isEmpty {
print("z는 비어있습니다")
} else {
print(z)
}
for ~ in 으로 set 항목 접근
var fruit : Set<String> = ["apple", "orange", "banana"]
for f in fruit { // 랜덤 출력
print(f)
}
for f in fruit.sorted() { // 오름차순 정렬
print(f)
}
for f in fruit.sorted(by: >) { // 내림차순 정렬
print(f)
}
Set 연산(집합연산)
let odd: Set = [1, 3, 5, 7, 9]
let even: Set = [0, 2, 4, 6, 8]
let prime: Set = [2, 3, 5, 7]
print(odd.union(even)) //합집합
print(odd.union(even).sorted()) //[0,1,2,3,4,5,6,7,8,9]
print(odd.intersection(even))//교집합
print(odd.intersection(even).sorted())//[]
print(odd.subtracting(prime))//차집합
print(odd.subtracting(prime).sorted())//[1,9]
print(odd.intersection(prime).sorted())//교집합 [3,5,7]
print(odd.symmetricDifference(prime).sorted())//여집합 [1,2,9]
let houseAnimals: Set = ["개", "고양이"]
let houseAnimals1: Set = ["고양이", "개"]
let farmAnimals: Set = ["소", "닭", "양", "개", "고양이"]
let cityAnimals: Set = ["새", "쥐"]
print(houseAnimals==houseAnimals1)
print(houseAnimals==farmAnimals)
print(houseAnimals.isSubset(of: farmAnimals)) //부분집합(a집합의 모든 원소가 b의 원소일때)
print(farmAnimals.isSuperset(of: houseAnimals)) //초집합(상위집합)
print(farmAnimals.isDisjoint(with: cityAnimals)) //서로소 집합 (공통집합이 없음)
Set : UITouch
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first!
// 터지가 발생한 뷰 기준 좌표
let point = touch.location(in: touch.view)
}
참고자료 : https://developer.apple.com/documentation/swift/set
출처 : https://www.youtube.com/channel/UCM8wseo6DkA-D7yGlCrcrwA/playlists