티스토리 뷰

Swift 3.0.1 가이드에 대응하는 정리글을 작성하였습니다!!!

Array 정리 최신버전 링크 > http://wlaxhrl.tistory.com/36



Apple 제공 Swift 프로그래밍 가이드(2.1)의 Collection Types 중 Set 부분을 공부하며 정리한 글입니다. 개인적인 생각도 조금 들어가있습니다.


들어가며

Set은 같은 타입의 값을 중복되지 않게 순서없이 저장하는 콜렉션 타입이다. 저장한 순서가 중요하지 않고, 똑같은 값이 두 번 나오지 않는 것을 기대할 때 Set을 사용하면 유용하다.


Hash Values for Set Types

Set에 저장될 type은 반드시 hashable 해야한다. hashable이란 hashValue (int value)를 스스로 가져야 하며 a= b 일때 a.hashValue == b.hashValue 를 만족해야 한다.

Swift의 모든 기본 타입(String, Int, Double, Bool 등)은 hashable 하다. 또한 Enumeration case value 역시 기본적으로 hashable 하다. 즉 이런 타입들은 Set에 저장될 수 있고 Dictionary의 key 값이 될 수도 있다. Int나 Bool 타입이 Dictionary Key값이 된다니... Objective-C와 비교가 된다.

자신이 만든 Custom Type을 Set에 저장하거나 Dictionary의 Key 타입으로 사용하고 싶다면 Hashable protocol 을 따라야 한다.


Set Type Syntax

Set<Element>으로 만든다. Element는 Set에 저장할 값의 타입이다.


Creating and Initializing an Set

 // 1. 빈 Set 생성
var letters = Set<character>()
print("letters is of type Set<character> with \(letters.count) items.")
// prints "letters is of type Set<character> with 0 items.”

letters.insert("a")
// letters now contains 1 value of type Character
letters = []
// letters is now an empty set, but is still of type Set<Character>

// 2.Array Literal 을 이용하여 Set 생성
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items
// var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"] 만 써도 String타입이 저장될 Set을 유추해준다.
// 그러나 Set을 명시하지 않으면 favoriteGenres는 array가 된다.


Accessing and Modifying a Set

 // 1. Set 안에 몇 개의 Item이 있는지
print("I have \(favoriteGenres.count) favorite music genres.")
// prints "I have 3 favorite music genres.”


// 2. Set 안이 비어있는지 체크
if favoriteGenres.isEmpty
{
    print("As far as music goes, I'm not picky.")
}
else
{
    print("I have particular music preferences.")
}
// prints "I have particular music preferences.”


// 3. Set 에 Item 추가
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items


// 4. Set의 Item 제거
// remove(Item) 메서드는 Item이 Set에 있었다면 지우고 그 Item을 반환하고
// Item이 Set에 없었다면 nil을 반환한다
if let removedGenre = favoriteGenres.remove("Rock")
{
    print("\(removedGenre)? I'm over it.")
}
else
{
    print("I never much cared for that.")
}
// prints "Rock? I'm over it.”


// 5. 특정 Item이 Set 안에 들어있는지 체크
if favoriteGenres.contains("Funk")
{
    print("I get up on the good foot.")
}
else
{
    print("It's too funky in here.")
}
// prints "It's too funky in here.”


Iterating Over a Set

for genre in favoriteGenres
{
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop

// Set 안의 Item을 특정 순서로 순회하고 싶다면 sort() 메서드를 사용
// Item을 < 연산자로 sorting 한 array가 반환됨
for genre in favoriteGenres.sort()
{
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz


Performing Set Operations

<Fundamental Set Operations>

각 메서드는 초록색 부분에 해당하는 Item들로 구성된 새로운 Set을 생성하여 반환한다.

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).sort()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersect(evenDigits).sort()
// []
oddDigits.subtract(singleDigitPrimeNumbers).sort()
// [1, 9]
oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort()
// [1, 2, 9]


<Set Membership and Equality>

a는 b의 superset, b는 a의 subset, b와 c는 서로에게 disjoint.

  • “is equal” operator (==) : 두 Set의 내용이 동일(Item)

  • isSubsetOf(_:) : subset인지를 판별

  • isSupersetOf(_:) : superset인지를 판별

  • isStrictSubsetOf(_:) : subset이면서, subset!=superset

  • isStrictSupersetOf(_:) : superset이면서, subset!=superset

  • isDisjointWith(_:) : 두 Set 간의 교집합이 없음

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

houseAnimals.isSubsetOf(farmAnimals)
// true
farmAnimals.isSupersetOf(houseAnimals)
// true
farmAnimals.isDisjointWith(cityAnimals)
// true

let myAnimals: Set = ["🐔", "🐑"]
let myFriendAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let myWifeAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱", "🐭"]

myAnimals.isStrictSubsetOf(farmAnimals)
// true
myFriendAnimals.isStrictSubsetOf(farmAnimals)
// false
myWifeAnimals.isStrictSubsetOf(farmAnimals)
// false



'Swift 공식 가이드 > Swift 2' 카테고리의 다른 글

Control Flow  (0) 2016.03.03
Collection Types - Dictionary  (0) 2016.03.01
Collection Types - Array  (0) 2016.02.28
Strings and Characters  (0) 2016.02.28
Basic Operators  (1) 2016.02.28
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   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
글 보관함