그래오늘은이거야

Swift Set 사용법 (사용해야 하는 이유) 본문

세상 개발/IOS(Swift)

Swift Set 사용법 (사용해야 하는 이유)

jinhongstar 2020. 6. 10. 11:17
728x90
반응형

Swift Collection Types 은 3가지가 있다.

 

Array, Set, Dictionaries

 

objective c 를 하다보면 Array 와 Dicttionaries 는 익숙하다

 

Swift 를 하면서 Set 에 대하여 집합에 대하여 공부하였다

 

데이터를 다루면서 집합을 정교하게 다룰 수 있다.

합집합,교집합 알고리즘 공부하다보면 중요하단 사실을 알게된다.

 

Set생성

var letters = Set<Character>()

print("letters is of type Set<Character> with \(letters.count) items.")

// letters is of type Set<Character> with 0 items.

 

letters.insert("a")

letters = []

 

Set 초기화

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

 

 

Swift 모든 문법은 isEmpty 공백 Java와 같이 비교 할 수있다.

 

추가

favoriteGenres.insert("Jazz")

 

삭제

if let removedGenre = favoriteGenres.remove("Rock") {

print("\(removedGenre)? I'm over it.")

} else {

print("I never much cared for that.")

}

// Rock? I'm over it.

 

이게 제일 중요하다.

 

이걸 objective c 할때는 내가 직접 다 하나하나 코드로 짜서 비교하고 별짓을 다했는데

이걸 swift 는 라이브러리를 제공한다.

 

 

let oddDigits: Set = [1, 3, 5, 7, 9]

let evenDigits: Set = [0, 2, 4, 6, 8]

let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

 

oddDigits.union(evenDigits).sorted()

// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

oddDigits.intersection(evenDigits).sorted()

// []

oddDigits.subtracting(singleDigitPrimeNumbers).sorted()

// [1, 9]

oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()

// [1, 2, 9]

 

Set 비교연산

 

 

let houseAnimals: Set = ["🐶", "🐱"]

let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]

let cityAnimals: Set = ["🐦", "🐭"]

 

houseAnimals.isSubset(of: farmAnimals)

// 참

farmAnimals.isSuperset(of: houseAnimals)

// 참

farmAnimals.isDisjoint(with: cityAnimals)

// 참

 

 

참고 사이트

https://jusung.gitbook.io/the-swift-language-guide/language-guide/04-collection-types

 

콜렉션 타입 (Collection Types)

 

jusung.gitbook.io

 

반응형
Comments