HIT해

[Swift 기초문법 - 38] 콜렉션 합치기 본문

Swift/기초문법

[Swift 기초문법 - 38] 콜렉션 합치기

힛해 2024. 8. 16. 08:42
728x90
  • List
  • Set
  • Dictionary

이 세가지를 활용한 콜렉션 합치기를 알아보자!

 

1. List 합치기

let myFriends = ["철수", "짱구"]

let otherFriends = ["멩구", "유리"]

let totalFriends = myFriends + otherFriends

// myFriends.append(contentsOf: otherFriends)
// 보통 이방식으로 많이 합치는데 단점이 두가지 있다.
// 1. let으로 선언되어있기에 append를 사용할 수 없다.
// 2. 기존의 한 배열에 추가하는 형태이기에 초기값의 변경이 일어난다 (알고리즘 풀이할때 곤욕!)

 

이때 List와 Set을 합칠 수도 있다.

let myFriends = ["철수", "짱구"]

let otherFriends : Set<String> = ["멩구", "유리"]

let totalFriends = myFriends + otherFriends

 

[String]의 형태로 만들어진다.