Collection

kmjmarine·2023년 4월 20일
0

1. Array

  • 순서(sequence)가 있는 element의 모음
  • sequence : 한번에 한단계 씩 진행할 수 있는 값의 목록
  • 기본 시간복잡도는 O(n)
- finding elements methods
  contains, allSatisfy, first, min(), max()
- selecting elements methods
  prefix(Int), suffix(Int)
- excluding elements methods
  dropFirst, drop, filter
- sorting elements methods
  sorted(), reversed()
- transforming a Sequence
  map, compactMap, flatMap, reduce, lazy
  • 공식문서에 swapAt(), insert, remove 등 빠진게 있는데 추후 다시 확인해보기

let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
print(bugs.contains("Mosquito")) //false

  • 문자열에서 특정 문자 제거
var phrase = "The rain in Spain stays mainly in the plain." 
var phrase2 = "The rain in Spain stays mainly in the plain." 
let vowels: Set<Character> = ["a", "e", "i", "o", "u", "s"] 

phrase.removeAll(where: { vowels.contains($0) })
print(phrase2.filter { !vowels.contains($0) })

print(phrase)

  • 두 배열 합치기
// + 더하기를 통해 collection 을 합칠 수 있음
// 중복 제거 안됨
let myFriends = ["Jacob", "Emma", "Jason"] 
let otherFriends = ["Mike", "Luck", "Jason"] 
let totalFriends = myFriends + otherFriends 
print(totalFriends) // ["Jacob", "Emma", "Jason", "Mike", "Luck", "Jason"]

// Array -> Set형으로 변환하여 중복을 제거(순서는 보장되지 않음)
let uniqueFriends: Set<String> = Set(totalFriends)
print(uniqueFriends) //["Emma", "Jason", "Mike", "Luck", "Jacob"]

// Set -> Array형으로 변환
let uniqueFriendsArray: [String] = Array(uniqueFriends)
print(uniqueFriendsArray) //["Emma", "Jason", "Mike", "Luck", "Jacob"]

// 두 배열의 길이가 다를 경우 작은 배열의 길이 기준으로 묶어짐
// 배열 3개이상은 묶어 지지 않음 (error: extra argument in call)
let friends = ["Jacob", "Emma", "Mike", "Jeff"] 
let pets = ["코코", "나비", "똘이", "뚜기"] 
let zipped = zip(friends, pets)

for item in zipped { 
    print("\(item.0) : \(item.1)") 
} 
//Jacob : 코코
//Emma : 나비
//Mike : 똘이
//Jeff : 뚜기


let zippedArray = Array(zip(friends, pets)) 
//let zippedArray = zipped.map { $0 }과 동일
print(zippedArray) //[("Jacob", "코코"), ("Emma", "나비"), ("Mike", "똘이")]


let stringArr: [String] = ["A", "B", "C", "D"] 
let intArr: [Int] = [10, 20, 35, 15] 

for (name, age) in zip(stringArr, intArr) { 
  if age > 20 { 
    print(name, age) 
  } 
}
//C 35

  • 배열 요소의 특성 만족 여부
let names = ["Jacob", "Emma", "John"] 
let nameCountAtLeastFive = names.allSatisfy { (name: String) -> Bool in 
	name.count <= 5 
} 
print("nameCountAtLeastTwo: ", nameCountAtLeastFive) 
// nameCountAtLeastTwo:  true (모든 element의 길이가 5이하 이므로 true가 반환됨)
// names.allSatisfy { $0.count <= 5 } 구문과 동일 

let names2 = ["제시", "제임스", "맥"] 
nameCountAtLeastFive = names2.allSatisfy({ $0.count <= 2 }) 
print("nameCountAtLeastTwo: ", nameCountAtLeastFive) 
// nameCountAtLeastTwo:  false ('제임스' element의 길이가 3이므로 조건을 만족하지 않아 false가 반환됨)

2. Dictionary (key: value)

var scoreDic: [String: Int] = ["kmj": 80, "ingpdw": 30, "yangmi": 65]

print(scoreDic["kmj"]) //Optional(80)

if let score = scoreDic["kmj"] { //Optional binding
    print(score)
} else {
    print("score 없음")
}
//80

print(scoreDic.isEmpty) //false
print(scoreDic.count) //3

scoreDic["yangmi"] = 66 //수정
scoreDic["jenny"] = 85 //추가 dict["key"] = "value" append 불가
scoreDic["ingpdw"] = nil //삭제

//활용
for (name, score) in scoreDic {
    print("\(name), \(score)")
}
//yangmi, 65
//kmj, 80
//ingpdw, 30

//모든 element가 100이상인가?
print(scoreDic.allSatisfy( { $1 >= 100 } )) //false


let myPetDic: Dictionary<String, String> = ["고양이": "야옹", "강아지": "멍멍", "송아지": "음메"] 
//문자열 배열형으로 변환
let myPets: [String] = myPetDic.map { (animal, cry) in 
    return "\(animal)의 울음소리는 \(cry)이다" 
} 
//동일 구문
let myPets: [String] = myPetDic.map {  
   return "\($0)의 울음소리는 \($1)이다" 
}
// ["고양이의 울음소리는 야옹이다", "강아지의 울음소리는 멍멍이다", "송아지의 울음소리는 음메이다"]
myPetDic.filter { $0.key == "강아지" } //["강아지": "멍멍"]
myPetDic.filter { $0.value == "멍멍" } //["강아지": "멍멍"]

//키, 값 각각 출력
let alphabetDic: Dictionary<String, String> = ["a": "A", "b": "B"] 
var keys: [String] = alphabetDic.map {$0.0} //["a", "b"]
var values: [String] = alphabetDic.map {$0.1} //["A", "B"]
  • 중복 키값 정의
var scoreDic: [String: Int] = ["kmj": 80, "kmj": 75, "ingpdw": 30, "yangmi": 65] 
/main.swift:3:71: note: duplicate key declared here
var scoreDic: [String: Int] = ["kmj": 80, "ingpdw": 30, "yangmi": 65, "kmj": 75] 
                                                                    ~ ^~~~~~~~~
//key값 kmj 가 중복되어 오류 발생                                                                      
Swift/Dictionary.swift:830: Fatal error: Dictionary literal contains duplicate keys
  1. Set (아이템이 순서 보장, 중복 안됨)
var someSet: Set<Int> = [1, 2, 4, 1] // {1, 2, 4} 중복값은 제거됨

someSet.isEmpty //false
someSet.count //3

someSet.insert(5) //[2, 5, 1, 4]
someSet.remove(1) //Optional(1) [2, 4, 5]


let numberSet: Set<Int> = [1, 1, 3, 6, 4, 3, 7] 
let myNumbers: [String] = numbers.map { aNumber in 
    return "\(aNumber * 10) 입니다." 
} 
//["70 입니다.", "30 입니다.", "60 입니다.", "40 입니다.", "10 입니다."] 중복된 값은 1회만 출력


var mySetA: Set<Int> = [1, 2, 2, 3]
var mySetB: Set<Int> = [1, 3, 2, 4]
print(mySetA.union(mySetB)) //[2, 3 ,4, 1] 합집합
print(mySetA.intersection(mySetB)) //[2, 3, 1] 교집합
print(mySetA.subtracting(mySetB)) //[] 차집합 (mySetA 기준으로 mySetA에 남는 것)
print(mySetA.symmetricDifference(mySetB)) //[4] 대칭차
profile
shared knowledge is long, life is short

0개의 댓글