250x250
반응형
05-20 20:28
Today
Total
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Notice
Recent Posts
Recent Comments
Link
Archives
관리 메뉴

Bill Kim's Life...

[Swift] Collection Types : Array, Dictionary, Set 본문

CS(컴퓨터 과학)/Swift

[Swift] Collection Types : Array, Dictionary, Set

billnjoyce 2020. 6. 11. 15:23
728x90
반응형
Swift5의 클래스와 구조체의 공통점과 차이점에 대해서 살펴봅니다.

 

 

#. 개발 환경

  • Xcode 11.x 이상
  • Swift 5

 

 


 

 

Collection Types

 

Swift에서는 콜렉션(리스트) 타입으로 아래의 세가지 형태의 타입을 지원합니다.

 

 

 

그렇다면 위의 세가지 형태의 콜렉션 타입에 대해서 하나하나 살펴보겠습니다.

 

 

 

 


 

 

Array(배열)

 

배열과 비슷한 형태의 컬렉션으로서 순서(인데스)가 있는 리스트 형태의 컬렉션 타입입니다.

 

// 빈 Int Array 생성
var integers: Array<Int> = Array<Int>()

// 다른 생성 방법
// var integers: Array<Int> = [Int]()
// var integers: Array<Int> = []
// var integers: [Int] = Array<Int>()
// var integers: [Int] = [Int]()
// var integers: [Int] = []
// var integers = [Int]()

// 추가
integers.append(1)
integers.append(100)
        
print(integers) // [1, 100]

// 비었는지 확인
if integers.isEmpty {
   print("It's empty.")
} else {
   print("It's not empty.")
}

// 수정
integers[0] = 99
integers[1] = 10
        
// 삭제
integers.remove(at: 0)
integers.removeLast()
integers.removeAll()
        
// 멤버 갯수 확인
print(integers.count)

// 배열 순회
for item in integers {
    print(item)
}

 

 

 


 

 

 

Dictionary

 

키와 값의 쌍으로 이루어진 컬렉션 타입입니다.

 

// 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] = Dictionary<String, Any>()
// var anyDictionary: [String: Any] = [String: Any]()
// var anyDictionary: [String: Any] = [:]
// var anyDictionary = [String: Any]()
        
// 추가
anyDictionary["someKey"] = "value"
anyDictionary["anotherKey"] = 100
        
print(anyDictionary) // ["someKey": "value", "anotherKey": 100]

// 비었는지 확인
if anyDictionary.isEmpty {
   print("It's empty.")
} else {
   print("It's not empty.")
}

// 수정
anyDictionary["someKey"] = "dictionary"
print(anyDictionary) // ["someKey": "dictionary", "anotherKey": 100]
        
// 삭제
anyDictionary.removeValue(forKey: "anotherKey")
anyDictionary["someKey"] = nil
print(anyDictionary) // [:]
        
// 멤버 갯수 확인
print(anyDictionary.count) // 0

 

 

 

 


 

 

 

Set

 

마지막으로 Set으로서 순서가 없고 멤버 값에 대해서 유일한 것을 보장(중복값 허용 안함)하는 컬렉션입니다.

 

// 빈 Int Set 생성
var integerSet: Set<Int> = Set<Int>()
        
// 추가
integerSet.insert(1)
integerSet.insert(100)
integerSet.insert(99)
integerSet.insert(99) // 99가 이미 있기 때문에 추가 안됨
integerSet.insert(99) // 99가 이미 있기 때문에 추가 안됨
        
print(integerSet) // [100, 99, 1]
print(integerSet.contains(1)) // true
print(integerSet.contains(2)) // false
        
// 비었는지 확인
if anyDictionary.isEmpty {
    print("It's empty.")
} else {
    print("It's not empty.")
}

// 삭제
integerSet.remove(100)
integerSet.removeFirst()

// 멤버 갯수 확인
print(integerSet.count) // 1

// Set 멤버 순회
for item in integerSet {
    print("\(item)")
}

 

Swift에서의 Set에서는 아래와 같은 특별한 기능의 함수도 제공합니다.

 

 

  • Intersection : 교집합
  • SymmetricDifference : 대칭차
  • Union : 합집합
  • Subtracting : 차집합

 

 

그림으로 살펴보면 아래와 같습니다.

 

 

 

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

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

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

// 차집합
let subtracting: Set<Int> = setA.subtracting(setB)
print(subtracting) // [2, 1]

// 대칭차
let symDiffSet: Set<Int> = setA.symmetricDifference(setB)
print(symDiffSet) // [6, 2, 7, 1]

 

 

 

 


 

 

 

또한 아래와 같은 관계도 살펴볼 수 있습니다.

 

 

 

 

  • a는 b의 Superset
  • b는 a의 Subset
  • b와 c는 서로 Disjoint 관계
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

// isSubset(of:) : A.isSubset(of:B) : A가 B의 부분집합이면 true 아니면 false 반환
// isSuperset(of:) : B.isSuperset(of:A) : B가 A의 상위 집합이면 true 아니면 false 반환
// isStrictSubset(of:) : subset이면서 subset != superset이면 true 아니면 false 반환
// isStrictSuperset(of:) : superset이면서 subset != superset이면 true 아니면 false 반환
// isDisjoint(with:) : 두 집합 사이에 어떤 공통 값이 없을 때 true, 하나라도 있으면 false 반환
        
print(houseAnimals.isSubset(of: farmAnimals)) // 참(true)
print(farmAnimals.isSuperset(of: houseAnimals)) // 참(true)
print(houseAnimals.isStrictSubset(of: farmAnimals)) // 참(true)
print(farmAnimals.isStrictSuperset(of: houseAnimals)) // 참(true)
print(farmAnimals.isDisjoint(with: cityAnimals)) // 참(true)

 

 


 

 

 

이상으로 Swift에서의 콜렉션 타입에 대해서 살펴보았습니다.

그럼 저희 블로그를 찾아주셔서 감사드리오며 행복한 하루 되시길 바랍니다.

 

 

 

 

감사합니다.

 

 

 

 

 

 

www.slideshare.net/BillKim8/collection-types

 

[Swift] Collection types

[Swift] Collection types 에 관한 강의 자료입니다.

www.slideshare.net

 

 

 

 


[참고 자료(References)]

 

[1] 콜렉션 타입 (Collection Types) : https://jusung.gitbook.io/the-swift-language-guide/language-guide/04-collection-types

[2] 컬렉션 타입 : https://yagom.github.io/swift_basic/contents/03_collection_types/

[3] [Swift]Collection Types 정리 : http://minsone.github.io/mac/ios/swift-collection-types-summary

[4] [Swift 공부] 컬렉션 타입이란 ? : https://noahlogs.tistory.com/14

[5] Swift – 함수, 콜렉션 타입 : https://blog.yagom.net/528/

[6] Swift - 컬렉션 타입(Collection Types) : http://seorenn.blogspot.com/2014/06/swift-collection-types.html

[7] [Swift 3] 컬렉션 타입 (Collection Types_Array, Set, Dictionary) : https://beankhan.tistory.com/155

[8] 컬렉션 타입(Collection Types) : https://kka7.tistory.com/141

[9] 3 swift 컬렉션 : https://www.slideshare.net/donggyupark2/3-swift-56764853

[10] [Swift] 016 Working with Collection (컬렉션 사용하기) for beginners : https://creativeworks.tistory.com/entry/Swift-016-Working-with-Collection-컬렉션-사용하기-for-beginners

 

728x90
반응형
Comments