Link
Notice
HIT해
[Swift 기초문법 - 56] Set 내장함수 본문
728x90
Set의 다양한 내장함수를 알아보자!
- union ( 합집합 )
- intersection ( 교집합 )
- 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이 만들어진 것을 볼 수 있다.
'Swift > 기초문법' 카테고리의 다른 글
[Swift 기초문법 - 59] 패턴 매칭 연산자 ~= (0) | 2024.08.19 |
---|---|
[Swift 기초문법 - 58] Any, AnyObject, some (0) | 2024.08.19 |
[Swift 기초문법 - 55] Dictionary 반복 (0) | 2024.08.19 |
[Swift 기초문법 - 54] stride (0) | 2024.08.19 |
[Swift 기초문법 - 53] Subset Superset (0) | 2024.08.19 |