// Array 선언 및 생성
var integers: Array<Int> = Array<Int>()
/* 위와 동일한 표현
var integers: Array<Int> = [] //빈 Array 생성
var integers: [Int] = Array<Int>() //Array<Int> 축약
var integers: [Int] = [Int]()
var integers: [Int] = []
var integers = [Int]()
*/
// 타입 추론으로 생성
var array1 = [1, 2, 3]
var array2 = [] //에러. 타입 추론으로는 빈 배열 생성 불가
// 값 추가
integers.append(20)
integers.append(contentsOf: [7,8,9]) //여러 값 추가
// 값 삽입
integers.insert(99, at: 3) // 해석 : index 위치 3에 값 99 삽입
// 포함 여부 확인
print(integers.contains(20)) //true
print(integers.contains(1)) //false
// 삭제
integers.remove(at: 0) //해당 index 삭제
integers.removeLast()
integers.removeAll()
// 멤버 수 확인
print(integers.count)
// 불변 Array
let immutableArray = [1, 2, 3]
// Key가 String, Value가 Any인 빈 Dictionary 생성
var anyDictionary: Dictionary<String, Any> = [String: Any]()
/* 위와 동일한 표현
var anyDictionary: Dictionary<String, Any> = Dictionary[String: Any]()
var anyDictionary: Dictionary<String, Any> = [:]
var anyDictionary: [String: Any] = [String: Any]()
var anyDictionary: [String: Any] = [:]
var anyDictionary = [String: Any]()
*/
// 값 할당
anyDictionary["first"] = 1
anyDictionary["second"] = 2
// 값 제거
anyDictionary.removeValue(forKey: "first")
anyDictionary["second"] = nil
// 불변 Dictionary 생성
let emptyDictionary:[String: String] = [:]
let initializedDictionary:[String: String] = ["name":"bear", "gender": "male"]
//let someValue: String = initializedDictionary["name"] //에러. 키"name"의 값의 존재가 불확실하기 때문
if let someValue = initializedDictionary["name"] {
print(someValue) // bear
}
// 유용한 기능
print(initializedDictionary.count) // 결과 : 3
print(initializedDictionary.isEmpty) // 결과 : false
print(initializedDictionary.keys) // 결과 : ["name", "age", "gender"]
print(initializedDictionary.values) // 결과 : ["bear", "30", "male"]
// 빈 Set 생성 및 선언
var integerSet: Set<Int> = Set<Int>()
var emptySet = Set<String>()
// 타입 추론을 이용한 선언
var fruits: Set = ["Apple", "Banana", "Cherry"]
// 새로운 멤버 입력
integerSet.insert(1)
integerSet.insert(2)
integerSet.insert(3)
integerSet.insert(4)
integerSet.insert(1) // 여러번 insert해도 동일한 값은 한 번만 저장됨
// 멤버 포함여부 확인
print(integerSet.contains(1)) //true
print(integerSet.contains(6)) //false
// 멤버 삭제
integerSet.remove(4)
integerSet.removeFirst() //3이 삭제됨. 1이 재입력되어 마지막 위치이기 때문
integerSet.removeAll()
// 멤버 개수
integerSet.count
// Set 활용
// 유일성 보장으로 집합 현산에 유용
let setA: Set<Int> = [1, 2, 3, 4, 5]
let setB: Set<Int> = [3, 4, 5, 6, 7]
let union: Set<Int> = setA.union(setB) //[1, 2, 4, 5, 6, 3, 7] 정렬되지 않음. index 없음.
let sortedUnion: [Int] = union.sorted() // Set값을 Array에 오름차순 정렬
// 교집합
let intersection: Set<Int> = setA.intersection(setB) //[4, 5, 3]
// 차집합
let subtracting: Set<Int> = setA.subtracting(setB) //[2, 1]
💡 Array와 Set은 서로 타입캐스팅이 가능
var array = [1, 2, 3]
var set: Set<Int> = Set<Int>()
//Array to Set
set = Set(array)
//Set to Array
array = Array(set)