Array : 순서가 있는 리스트 컬렉션
Dictionary : '키'와 '값'의 쌍으로 이루어진 컬렉션
Set : 순서가 없고, 멤버가 유일한 컬렉션
1. Array
멤버가 순서(index로 표현)를 가진 리스트 형태의 컬렉션 타입으로, 여러가지 리터럴 문법을 활용할 수 있어 표현 방법이 다양하다
Array의 선언 및 생성
var integers: Array<Int> = Array<Int> ()
→ integers라는 이름의 Int 타입의, 빈 Array 생성
여러가지 방법으로 이와 동일한 코드를 작성할 수 있다
var integers: Array<Int> = [Int]()
var integers: Array<Int> = []
var integers: [Int] = Array<Int>()
var integers: [Int] = [Int]()
var integers: [Int] = []
var integers = [Int]()
Array 활용
append 함수를 활용해 멤버를 추가할 수 있다
integers.append(1)
integers.append(100)
그러나 Int 타입이 아닌 원소는 Int 형식의 Array에 추가할 수 없다
integers.append(101.1) // 오류 발생
확인해보면
print(integers)
[1, 100]
contains 함수를 활용해 멤버가 포함되었는지의 여부를 확인해보면
print(integers.contains(100))
print(integers.contains(99))
true
false
멤버를 교체하려 할 때는 index로 접근한다
integers[0] = 99
remove 함수를 활용해 index에 위치한 멤버를 삭제할 수 있다
integers.remove(at: 0)
integers.removeLast()
integers.removeAll()
count 함수를 활용해 멤버 수를 확인할 수 있다
print(integers.count)
0
만약 index를 벗어나 접근하려면 익셉션 런타입 오류 발생
integers[0] // 오류 발생
불변 Array
let을 사용해 Array 선언을 하게 된다면 수정이 불가능한 Array가 된다
let immutableArray = [1, 2, 3]
따라서 멤버를 추가하거나 삭제할 수 없다
immutableArray.append(4) // 오류 발생
immutableArray.removeAll() // 오류 발생
2. Dictionary
'키'와 '값'의 쌍으로 이루어진 컬렉션 타입으로, Array와 비슷하게 여러가지 리터럴 문법을 활용할 수 있다
Dictionary의 선언과 생성
var anyDictionary: Dictionary<String, Any> = [String: Any]()
→ Key가 String 타입이고 Value가 Any인 빈 Dictionary를 생성
여러가지 방법으로 이와 동일한 코드를 작성할 수 있다
var anyDictionary: Dictionary <String, Any> = Dictionary<String, Any>()
var anyDictionary: Dictionary <String, Any> = [:]
var anyDictionary: [String: Any] = Dictionary<String, Any>()
var anyDictionary: [String: Any] = [String: Any]()
var anyDictionary: [String: Any] = [:]
var anyDictionary: [String: Any]()
Dictionary 활용
키를 활용해서 해당하는 값을 할당할 수 있다
anyDictionary["someKey"] = "value"
anyDictionary["anotherKey"] = 100
print(anyDictionary)
["someKey": "value", "anotherKey": 100]
키에 해당하는 값을 변경할 수 있다
anyDictionary["someKey"] = "dictionary"
print(anyDictionary)
["someKey": "dictionary", "anotherKey": 100]
키에 해당하는 값을 제거할 수 있다
anyDictionary.removeValue(forKey: "anotherKey")
anyDictionary["someKey"] = nil
print(anyDictionary)
[:]
불변 Dictionary
let을 사용해 Dictionary 선언
let emptyDictionary: [String: String] = [:]
let initalizedDictionary: [String: String] = ["name": "yagom", "gender": "male"]
불변 Dictionary이므로 값을 변경할 수 없다
emptyDictionary["key"] = "value"
이런 경우에는 어떨까?
let someValue: String = initalizedDictionary["name"] // 컴파일 오류 발생
var someValue: String = initalizedDictionary["name"] // var이어도 결과는 마찬가지다
→ "name"이라는 키에 해당하는 값이 없을 수 있으므로 String 타입의 값이 나올 것이라는 보장이 없다!
3. Set
중복되지 않는 멤버가 순서없이 존재하는 컬렉션으로, Array, Dictionary와 다르게 축약형이 존재하지 않는다
Set 생성 및 선언
var integerSet: Set<Int> = Set<Int>()
insert 함수를 사용해 새로운 멤버를 추가할 수 있다
integerSet.insert(1)
integerSet.insert(99)
integerSet.insert(99)
integerSet.insert(99)
integerSet.insert(100)
print(integerSet)
[1, 99, 100]
→ 동일한 값은 여러번 insert 해도 한번만 저장된다는 걸 알 수 있다!
contains 함수를 사용해 멤버 포함 여부를 확인할 수 있다
print(integerSet.contains(1))
print(integerSet.contains(2))
true
false
remove 함수를 사용해 멤버를 삭제할 수 있다
integerSet.remove(99)
integerSet.removeFirst()
[100, 1][1]
count 함수를 사용하면 멤버의 개수를 알 수 있다
integerSet.count
1
Set의 활용
멤버의 유일성이 보장되기 때문에 집합 연산에 활용하기에 유용하다
let setA: Set<Int> = [1, 2, 3, 4, 5]
let setB: Set<Int> = [3, 4, 5, 6, 7]
union 함수를 활용해 합집합으로 만들 수도 있다
let union: Set<Int> = setA.union(setB)
print(union)
[2, 4, 5, 6, 7, 3, 1]
sorted 함수를 활용해 오름차순으로 정렬할 수 있다
let sortedUnion: [Int] = union.sorted()
print(sortedUnion)
[1, 2, 3, 4, 5, 6, 7]
intersection 함수를 활용해 교집합으로 만들 수도 있다
let intersection: Set<Int> = setA.intersection(setB)
print(intersection)
[5, 3, 4]
subtracting 함수를 활용해 차집합으로 만들 수도 있다
let subtracting: Set<Int> = setA.subtracting(setB)
print(subtracting)
[2, 1]
정리
1. Array
: 멤버가 순서를 가진 리스트 형태의 컬렉션 타입으로, index로 표현할 수 있으며 여러가지 리터럴 문법을 활용할 수 있다
var 이름:Array<타입> = Array<타입>()
(array는 Array의 임시적인 이름)
array.append(멤버) : 멤버 추가
array.contains(멤버) : 멤버 포함 여부 확인, bool 타입 반환
array[index] = 멤버 : 멤버 교체
array.remove(at: index) : 멤버 삭제
array.removeLast() : 가장 마지막 멤버 삭제
array.removeAll() : 모든 멤버 삭제
array.count : 멤버 수 확인
<주의>
Array가 갖고있는 index를 벗어나 접근하면 익셉션 런타임 오류 발생
let을 사용해 Array를 선언하면 불변 Array가 되기 때문에 멤버를 추가하거나 삭제할 수 없다
2. Dictionary
: '키'와 '값'의 쌍으로 이루어진 컬렉션 타입으로, 여러가지 리터럴 문법을 활용할 수 있다
var 이름: Dictionary<키 타입, 값 타입> = [키 타입: 값 타입]()
(dictionary는 Dictionary의 임시적인 이름)
dictionary["키"] = "값" : 키에 해당하는 값을 할당, 해당 형식으로 다른 값으로 변경도 가능
dictionary.removeValue(forKey: "키") : 키에 해당하는 값을 제거
dictionary["키"] = nil : 키에 해당하는 값을 제거, nil로 채움
<주의>
let을 사용해 Dictionary를 선언하면 불변 Dictionary가 되기 때문에 키 값을 변경할 수 없다
키에 해당하는 값을 다른 변수나 상수에 할당하고자 할 때는 일반적으로 대입하는 방법으로 할 수 없다 (컴파일 오류 발생)
3. Set
: 중복되지 않는 멤버가 순서없이 존재하는 컬렉션으로, Array, Dictionary와 다르게 축약형이 존재하지 않는다
var 이름: Set<Int> = Set<Int>()
(set은 Set의 임시적인 이름)
set.insert(값) : 새로운 멤버 추가
set.contains(값) : 멤버 포함 여부 확인, bool 타입으로 반환
set.remove(값) : 해당하는 멤버 삭제
set.removeFirst() : 가장 처음 멤버 삭제
set.count : 멤버 개수 반환
setA.union(setB) : setA와 setB의 합집합
setA.intersection(setB) : setA와 setB의 교집합
setA.subtracting(setB) : setA와 setB의 차집합
set.sorted() : 오름차순 정렬
<주의>
동일한 값은 여러번 insert 해도 한번만 저장된다
2022.02.23 - [Study/Swift_BoostCourse_Basic] - iOS 프로그래밍을 위한 스위프트 기초
'[Non-Updated] iOS > Swift_BoostCourse_Basic' 카테고리의 다른 글
[Swift_BoostCourse_Basic] CH 1_08. 함수 고급 (0) | 2022.02.25 |
---|---|
[Swift_BoostCourse_Basic] CH 1_07. 함수 기본 (0) | 2022.02.24 |
[Swift_BoostCourse_Basic] CH 1_05. Any, AnyObject, nil (0) | 2022.02.23 |
[Swift_BoostCourse_Basic] CH 1_04. 기본 데이터 타입 (0) | 2022.02.23 |
[Swift_BoostCourse_Basic] CH 1_03. 상수와 변수 (0) | 2022.02.23 |