HIT해

[Swift 기초문법 - 56] Set 내장함수 본문

Swift/Swift 기초문법

[Swift 기초문법 - 56] Set 내장함수

힛해 2024. 8. 19. 22:47
728x90

Set의 다양한 내장함수를 알아보자!

  1. union ( 합집합 )
  2. intersection ( 교집합 )
  3. symmetricDifference ( 차집합 )

 

사용예시

1. union

중복을 제외하고 합친다

import UIKit

let myFriends = ["철수", "영희", "수잔", "제시카"]
let yourFriends = ["철수", "영희", "제니퍼", "존시나"]


let myFriendsSet = Set(myFriends)
let yourFriendsSet = Set(yourFriends)

let totalFriends = myFriendsSet.union(yourFriends)

 

실행결과

 

2. intersection

중복만을 가져온다

import UIKit

let myFriends = ["철수", "영희", "수잔", "제시카"]
let yourFriends = ["철수", "영희", "제니퍼", "존시나"]


let myFriendsSet = Set(myFriends)
let yourFriendsSet = Set(yourFriends)

let sharedFriends = myFriendsSet.intersection(yourFriends)

 

실행결과

 

 

3. symmetricDifference

중복되는 요소들을 전부 제거한다!

import UIKit

let myFriends = ["철수", "영희", "수잔", "제시카"]
let yourFriends = ["철수", "영희", "제니퍼", "존시나"]


let myFriendsSet = Set(myFriends)
let yourFriendsSet = Set(yourFriends)

let totalFriends = myFriendsSet.symmetricDifference(yourFriends)

 

실행결과

 

중복 요소였던 철수와 영희를 제외하고 Set이 만들어진 것을 볼 수 있다.