본문 바로가기
Swift

[Swift] 5. 컬렉션 타입

by CodingKwon 2021. 10. 5.

1. Array

var a1: Array<Int> = Array<Int>()

// 같은 표현
// var a1: Array<Int> = [Int]()
// var a1: Array<Int> = []
// var a1: [Int] = Array<Int>()
// var a1: [Int] = [Int]()
// var a1: [Int] = []
// var a1 = [Int]()

// 멤버 추가
a1.append(1)
a1.append(10)

print(a1)	// [1, 10]

// 멤버 포함 여부 확인
print(a1.contains(1)) // true
print(a1.contains(2)) // false

// 멤버 교체
integers[0] = 10

// 멤버 삭제
integers.remove(at: 0)
integers.removeLast()
integers.removeAll()

// 멤버 수 확인
print(a1.count)
  • 멤버가 순서(인덱스)를 가지는 리스트 형태의 컬렉션

 

2. Dictionary

// Key가 String 타입이고 Value가 Any인 빈 Dictionary 생성
var b1: Dictionary<String, Any> = [String: Any]()

// 같은 표현
// var b1: Dictionary <String, Any> = Dictionary<String, Any>()
// var b1: Dictionary <String, Any> = [:]
// var b1: [String: Any] = Dictionary<String, Any>()
// var b1: [String: Any] = [String: Any]()
// var b1: [String: Any] = [:]
// var b1 = [String: Any]()


// 키에 해당하는 값 할당
b1["someKey"] = "value"
b1["anotherKey"] = 100

print(b1) // ["someKey": "value", "anotherKey": 100]

// 키에 해당하는 값 변경
b1["someKey"] = "dictionary"
print(b1) // ["someKey": "dictionary", "anotherKey": 100]

// 키에 해당하는 값 제거
b1.removeValue(forKey: "anotherKey")
b1["someKey"] = nil
print(b1)
  • 키와 값의 쌍으로 이루어진 컬렉션 타입

3. Set

// 빈 Int Set 생성
var c1: Set<Int> = Set<Int>()
c1.insert(1)
c1.insert(3)
c1.insert(2)
c1.insert(2)
c1.insert(2)

print(c1) // [3, 2, 1]
print(c1.contains(1)) // true
print(c1.contains(10)) // false

c1.remove(3)
c1.removeFirst()

print(c1.count) // 1


// 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)
print(union) // [2, 4, 5, 6, 7, 3, 1]

// 합집합 오름차순 정렬
let sortedUnion: [Int] = union.sorted()
print(sortedUnion) // [1, 2, 3, 4, 5, 6, 7]

// 교집합
let intersection: Set<Int> = setA.intersection(setB)
print(intersection) // [5, 3, 4]

// 차집합
let subtracting: Set<Int> = setA.subtracting(setB)
print(subtracting) // [2, 1]
  • 순서가 없고, 멤버가 유일한 것을 보장하는 컬렉션 타입

 

'Swift' 카테고리의 다른 글

[Swift] 7. 조건문  (0) 2021.10.05
[Swift] 6. 함수  (0) 2021.10.05
[Swift] 4. Any, AnyObject, nil  (0) 2021.10.04
[Swift] 3. 데이터 타입  (0) 2021.10.04
[Swift] 2. 상수와 변수  (0) 2021.10.04

댓글