티스토리 뷰


집단 자료형 - 집합

(Collection Type - Set)




1) 이론적 정의

 


1. Swift 에서 사용되는 집단 자료형으로는 배열(Array) , 집합(Set) , 딕셔너리(Dictionnary) 가 있다. 여기서는 집합에 대해 알아보자.




2) 집합(Set)


 

 1.  순서가 없는 Collection (Unordered)


 2.  고유한 값 (Unique Value) = 중복된 값을 가지지 않는다.




* Example 1-1. 집합의 선언과 초기화 방법들



배열과 마찬가지로 집합도 다양하게 선언과 초기화를 할 수 있다.


let fruitsSet: Set<String> = ["Apple", "Orange", "Melon"]   

let numbers: Set = [1, 2, 3, 3, 3]

let emptySet = Set<String>()




* Example 1-2. 집합의 특징 



배열은 중복된 값을 가지지 않는다.


var number: Set = [1,2,3]

number.insert(1)                      <-- 1을 넣어주었으나,

number                                    <-- 결과는 [2, 3, 1] 로 동일하다. 


Q. 결과가 [1, 2, 3] 이 아니고 왜 [2, 3, 1] 인가요?

A. 집합은 스위프트에서 원래 순서가 음슴다..




* Example 2. 집합 내 요소들의 개수 (Number of elements)



let fruitsSet: Set<String> = ["Apple""Orange""Melon"


fruitsSet.count                                                <-- 3


if !fruitsSet.isEmpty {                                      <-- fruitsSet이 비어있지 않으면 True, 비어있으면 False

    print("\(fruitsSet.count) element(s)")           <-- 집합의 개수가 3으로, 비어있지 않으므로 여기가 출력 되겠습니다.

} else {

    print("empty set")

}




* Example 3. Searching



집합 내의 원하는 요소를 찾고자 할 때 사용한다.


if fruitsSet.contains("Apple") {

    < 집합 fruitsSet에 "Apple"이 포함되어 있으면 실행되는 부분을 정의한다 >

}


let productSet: Set = ["iPhone", "iPad", "Mac Pro", "iPad Pro", "Macbook Pro"]

let filteredSet = productSet.filter { (element) -> Bool in

    return element.hasPrefix("i")                                                    <-- Closure 를 배우지 않아서 아직 어렵지만 i 로 시작하는 요소들만 걸러낸다고 생각하자.

}


filteredSet                                                                                     <-- 결과 : ["iPad", "iPad Pro", "iPhone"]




* Example 4. 새로운 요소 추가(Add a new element)



집합 내의 원하는 요소를 추가하고자 할 때 사용한다.


var set: Set<String> = [ ]          <-- 비어있는 문자열 타입 집합의 선언과 초기화

set.insert("Apple")                   <-- 내부에 "Apple" 요소를 추가

set                                           <-- 결과 : ["Apple"]




* Example 5. 요소 제거(Remove an element)



집합 내의 원하는 요소를 제거하고자 할 때 사용한다.  :  .remove


set = ["Apple", "Orange", "Melon"]                     


if let removed = set.remove("Apple") {

    print("\(removed) has been removed!")

}


set                                                                       <-- ["Orange", "Melon"]




* Example 6. 두 집합 비교(Compare two sets) 



var favoriteFruits = Set(["Apple", "Orange", "Melon"])

//var tropicalFruits = Set(["Banana", "Papaya", "Kiwi", "Pineapple"])

var tropicalFruits = Set(["Orange", "Melon", "Apple"])


if favoriteFruits == tropicalFruits {

    print("favoriteFruits == tropicalFruits")                            <-- 각 배열의 요소들은 동일하게 가지고 있기 때문에 True.

} else {

    print("favoriteFruits != tropicalFruits")

}


if favoriteFruits.elementsEqual(tropicalFruits) {                 <-- .elementsEqual 은 비교 대상끼리의 '==' 비교에다가 내부 요소의 순서까지 같아야 한다고 보면 된다.

    print("favoriteFruits == tropicalFruits")

} else {

    print("favoriteFruits != tropicalFruits")                            <-- 요소의 순서가 같지 않으므로 이 부분 실행.

}




* Example 6. Subset & Superset



 isSubset(of: ) 은 한 집합의 요소(값) 전체가 어떠한 특정 집합에 포함되는지(Sub)를 판단하여 True, False 를 반환한다.

 isSuperset(of: ) 은 isSubset(of: ) 과 반대로 한 집합이 어떠한 특정 집합의 모든 값을 포함하는지(Super)를 판단하여 True, False 를 반환한다.


 isStrictSubset(of: ) & isStrictSuperset 은 Strict = 엄격한 이라는 뜻 그대로 포함여부를 정확하게 판단하여 True or False 를 반환한다. 

 예를 들면 두 집합이 요소가 같을 경우에는 서로가 Subset 이자 Superset 이 될 수 있기 때문에(서로 포함되기도 하고 모든 값을 포함하기도 하니까)

 이러한 부분에도 걸리지 않을 경우에만 분명하게 True 를 반환한다고 보면 된다.

 

isDisjoint(of: ) 은 두 집합 사이의 교집합을 확인하여 아무런 공통값이 없을 때(Disjoint) True 를 반환하고 하나라도 있으면 False  를 반환한다. (example 7. 참고)


tropicalFruits = Set(["Banana", "Papaya", "Kiwi", "Pineapple"])

let yellowFruits = Set(["Banana"])



if yellowFruits.isSubset(of: tropicalFruits) {            <-- 집합 yellowFruits 의 요소 전체가 집합 tropicalFruits 에 포함되나요?

    print("yellowFruits ⊂ tropicalFruits")                   <-- 집합 yellowFruits 의 요소 "Banana" 가 집합 tropicalFruits 에 포함되므로 True.

} else {

    print("yellowFruits ⊄ tropicalFruits")

}


if yellowFruits.isStrictSubset(of: tropicalFruits) {    <-- 집합 yellowFruits 의 요소 전체가 엄격하게 보았을 때, 집합 tropicalFruits 에 포함되나요?

    print("yellowFruits ⊂ tropicalFruits")                   <-- 집합 yellowFruits 의 요소 "Banana" 가 집합 tropicalFruits 에 포함되므로 True. 두 집합이 같을 가능성 없음.

} else {

    print("yellowFruits ⊄ tropicalFruits")

}


if tropicalFruits.isSuperset(of: yellowFruits) {         <-- 집합 tropicalFruits 의 요소 전체가, 집합 yellowFruits 의 모든 값을 포함하나요?

    print("tropicalFruits ⊃ yellowFruits")                   <-- 포함하고 있으므로 True. 

} else {

    print("tropicalFruits ⊅ yellowFruits")

}


if tropicalFruits.isStrictSuperset(of: yellowFruits) { <-- 집합 yellowFruits 의 요소 전체가 엄격하게 보았을 때, 집합 tropicalFruits 에 포함되나요?

    print("tropicalFruits ⊃ yellowFruits")                   <-- 포함하고 있고, 두 집합이 같아서 문제를 일으킬 일도 없으므로 True.

} else {

    print("tropicalFruits ⊅ yellowFruits")

}





* Example 7. 기본적인 집합 연산(Fundamental Set Operations)



  Intersection : 두 집합 A, B의 값을 비교하여 공통되는 값을 도출해낸다 = 교집합

  

favoriteFruits = Set(["Apple", "Orange", "Melon", "Kiwi"])

tropicalFruits = Set(["Banana", "Papaya", "Kiwi", "Pineapple"])


if favoriteFruits.isDisjoint(with: tropicalFruits) {

    print("favoriteFruits ∩ tropicalFruits = ∅")

} else {

    print("favoriteFruits ∩ tropicalFruits")                                    <-- "Kiwi" 가 공통된 교집합이므로 False 가 되어 이 부분 출력.

}


let commonSet = favoriteFruits.intersection(tropicalFruits)      <-- "Kiwi" 가 공통된 교집합. 

commonSet                                                                              <-- "Kiwi"


  union : 두 집합 A, B의 값을 비교하여 중복을 제거하고 모든 두 집합의 값을 도출해낸다 = 합집합


var unionSet = favoriteFruits.union(tropicalFruits)                   <-- 공통된 것의 중복을 제거하고(하나는 남겨두고) 모든 요소를 도출

unionSet                                                                                   <-- ["Apple", "Orange", "Melon", "Kiwi", " Banana", "Papaya", "Pineapple"]


  subtract : 두 집합 A, B의 값을 비교하여 A.subtract(B) 일 때에는, 두 집합에서 서로 교집합인 부분과 B가 가지고 있는 값들을 제외한 A의 값을 도출해낸다 = 차집합


let uncommonSet = favoriteFruits.subtract(tropicalFruits)       <-- favoriteeFruits 값을 그대로 두지만, tropicalFruits 와 공통되는 요소만 제거

uncommonSet                                    <-- ["Apple", "Orange", "Melon"] 


  symmetricDifference : 두 집합 A, B의 값을 비교하여 두 집합에서 서로 교집합인 부분을 제외하고 나머지 A,B의 모든 값들을 도출해낸다.


let exclusiveSet = favoriteFruits.symmetricDifference(tropicalFruits) <- 두 집합에서 교집합인 부분을 완전히 빼고 나머지들로 이루어진 집합을 도출

exclusiveSet                                                                                       <- ["Apple", "Orange", "Melon", " Banana", "Papaya", "Pineapple"]





지금까지 집합에 대해서 알아보았습니다. 틀린 부분이 있으면 댓글로 지적해주시면 감사드리겠습니다.


Made by Inswag's Swift in FastCampus 7th iOS Development School




댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함