728x90
Swift의 Collection Type에 대해 알아보겠습니다.
Collection
Swift에서는 값을 저장하기 위한 세 가지 기본적인 콜렉션 타입 Array, Set, Dictionary를을 제공합니다.
Array
- Ordered Collection
- Zero-based Integer Index
Mutable, Immutable
// Mutable
var variableArray = [1, 2]
variableArray = []
// Immutable
let constantArray = [1, 2]
//constantArray = []
Initialize
let strArray1: Array<String> = ["apple", "orange", "melon"]
let strArray2: [String] = ["apple", "orange", "melon"]
let strArray3 = ["apple", "orange", "melon"]
let strArray4 = Array<String>(repeating: "iOS", count: 5)
Number of Elements
let fruits = ["Apple", "Orange", "Banana"]
let countOfFruits = fruits.count // 3
if !fruits.isEmpty {
print("\(countOfFruits) element(s)") //3 element(s)\n
} else {
print("empty array")
}
Element 가져오기
- [Int]
- [Array.Index]
- [a…b]
- [a…<b]
// 0 1 2
// fruits = ["Apple", "Orange", "Banana"]
fruits[0] // Apple
fruits[2] // Banana
fruits.startIndex // 0
fruits.endIndex // 3
fruits[fruits.startIndex] // Apple
fruits[fruits.endIndex - 1] // Banana
검색
let alphabet = ["A", "B", "C", "D", "E"]
if alphabet.contains("A") {
print("contains A")
}
if alphabet.contains(where: { str -> Bool in
// code...
return str == "A"
}) {
print("contains A")
}
if let index = alphabet.index(of: "D") {
print("index of D: \(index)")
//index of D: 3
}
추가
var alphabetArray = ["A"] // [A]
alphabetArray.append("B") // [A,B]
alphabetArray += ["C"] // [A,B,C]
var alphabetArray2 = ["Q", "W", "E"]
alphabetArray + alphabetArray2 // ["A", "B", "C", "Q", "W", "E"]
alphabetArray.insert("S", at: 0) // ["S", "A", "B", "C"]
alphabetArray.insert("F", at: 3) // ["S", "A", "B", "F", "C"]
제거
alphabetArray = ["A", "B", "C", "D", "E"]
let removed = alphabetArray.remove(at: 0)
alphabetArray.removeAll()
alphabetArray.removeAll(keepingCapacity: true)
let indexC = alphabetArray.index(of: "C")
alphabetArray.remove(at: indexC!)
print(alphabetArray) //["A", "B", "D", "E"]
Sorting
alphabetArray = ["B", "C", "D", "A", "E"]
var sortedArray = alphabetArray.sorted()
// ["A", "B", "C", "D", "E"]
sortedArray = alphabetArray.sorted { $0 > $1 }
alphabetArray.sorted(by: >= )
// ["E", "D", "C", "B", "A"]
Enumerating
let array = ["Apple", "Orange", "Melon"]
for value in array {
if let index = array.index(of: value) {
print("\(index) - \(value)")
//0 - Apple
//1 - Orange
//2 - Melon
}
}
print("\n---------- [ reversed ] ----------\n")
for value in array.reversed() {
if let index = array.index(of: value) {
print("\(index) - \(value)")
//0 - Apple
//1 - Orange
//2 - Melon
}
}
print("\n---------- [ enumerated ] ----------\n")
for tuple in array.enumerated() {
print("#\(tuple.0) - \(tuple.1)")
// print("#\(tuple.offset) - \(tuple.element)")
//#0 - Apple
//#1 - Orange
//#2 - Melon
}
print("\n---------- [ enumerated ] ----------\n")
for (index, word) in array.enumerated() {
print("#\(index) - \(word)")
//#0 - Apple
//#1 - Orange
//#2 - Melon
}
Dictionary
- Element = Unique Key + Value
- Unordered Collection
Initialize
let words1 = [:]
let words2: Dictionary<String, String> = ["A": "Apple", "B": "Banana", "C": "City"]
let words3: [String: String] = ["A": "Apple", "B": "Banana", "C": "City"]
let words4 = ["A": "Apple", "B": "Banana", "C": "City"]
Number of Elements
var words = ["A": "Apple", "B": "Banana", "C": "City"]
let countOfWords = words.count
if !words.isEmpty {
print("\(countOfWords) element(s)")
} else {
print("empty dictionary")
}
Element 가져오기
var words = ["A": "Apple", "B": "Banana", "C": "City"]
if let aValue = words["A"] {
print(aValue) // Apple
} else {
print("Not found")
}
if let zValue = words["Z"] {
print(zValue)
} else {
print("Not found") // Not found
}
print(words.keys)
//["C", "B", "A"]
print(words.values)
//["City", "Banana", "Apple"]
let keys = Array(words.keys)
let values = Array(words.values)
검색
if words.contains(where: ({ (key, value) -> Bool in
return key == "D"
})) {
print("Containt")
} else {
print("Not Found") // Not Found
}
if words.contains(where: { (dict) -> Bool in
return dict.value.lowercased() == "City".lowercased()
}) {
print("contains City value.")
} else {
print("Not Found")
}
if words.contains(where: { $0.1.lowercased() == "City".lowercased() }) {
print("contains City value.")
}
let filteringResult = words.filter { (key, value) -> Bool in
return value.lowercased().contains("a")
}
for (key, value) in filteringResult {
print("\(key) - \(value)")
}
추가
words = ["A": "A"]
words["A"] // Key -> Unique
words["A"] = "Apple"
words // ["A": "Apple"]
words["B"] = "Banana"
words
words["B"] = "Blue"
words // ["B": "Blue", "A": "Apple"]
제거
words = ["A": "Apple", "B": "Banana", "C": "City", "Z": "Zoo"]
words["Z"] = "ZZZ"
words["Z"] = nil
words // ["B": "Banana", "A": "Apple", "C": "City"]
words.removeAll() // [:]
Enumerating
let dict = ["A": "Apple", "B": "Banana", "C": "City"]
for (key, value) in dict {
print("\(key): \(value)")
//C: City
//B: Banana
//A: Apple
}
for (key, _) in dict {
print(key)
//C
//B
//A
}
for (_, value) in dict {
print(value)
//City
//Banana
//Apple
}
Set
- Unordered Collection
- Unique Value
- Set Literal = Array Literal
Initialize
let fruitsSet: Set<String> = ["Apple", "Orange", "Melon"]
let numbers: Set = [1, 2, 3, 3, 3]
let emptySet = Set<String>()
Number of Elements
let fruitsSet: Set<String> = ["Apple", "Orange", "Melon"]
fruitsSet.count
if !fruitsSet.isEmpty {
print("\(fruitsSet.count) element(s)")
} else {
print("empty set")
}
검색
if fruitsSet.contains("Apple") {
print("Contain")
}
let productSet: Set = ["iPhone", "iPad", "Mac Pro", "iPad Pro", "Macbook Pro"]
let filteredSet = productSet.filter { (element) -> Bool in
return element.hasPrefix("i")
}
let filteredSet2 = productSet.filter { (element) -> Bool in
return element.hasPrefix("M")
}
filteredSet // ["iPad", "iPad Pro", "iPhone"]
filteredSet2 // ["Mac Pro", "Macbook Pro"]
추가
var set: Set<String> = []
set.insert("Apple")
set.insert("Orange")
set // ["Orange", "Apple"]
제거
set = ["Apple", "Orange", "Melon"]
if let removed = set.remove("Apple") {
print("\(removed) has been removed!")
}
set
set.removeAll(keepingCapacity: true) // []
set.removeAll() // []
Compare two sets
var favoriteFruits = Set(["Apple", "Orange", "Melon"])
var tropicalFruits = Set(["Orange", "Melon", "Apple"])
if favoriteFruits == tropicalFruits {
print("favoriteFruits == tropicalFruits")
//"favoriteFruits == tropicalFruits"
} else {
print("favoriteFruits != tropicalFruits")
}
if favoriteFruits.elementsEqual(tropicalFruits) {
print("favoriteFruits == tropicalFruits")
} else {
print("favoriteFruits != tropicalFruits")
//"favoriteFruits != tropicalFruits"
}
Subset & Superset
- isSubset(of:): subset인지를 판별 (부분 집합)
- isSuperset(of:): superset인지를 판별 (상위 집합)
- isStrictSubset(of:): subset이면서, subset!=superset
- isStrictSuperset(of:): superset이면서, subset!=superset
- isDisjoint(with:): 두 Set 간의 교집합이 없음
let setTest1 = Set(["Banana", "Papaya", "Kiwi", "Pineapple"])
let setTest2 = Set(["Banana", "Papaya",])
let setTest3 = Set(["Banana", "Papaya"])
setTest2.isSubset(of: setTest1) // true
setTest2.isStrictSubset(of: setTest1) // true
setTest2.isStrictSubset(of: setTest3) // false (subset!=superset)
setTest1.isSuperset(of: setTest2) // true
setTest1.isStrictSuperset(of: setTest2) // true
setTest2.isStrictSuperset(of: setTest3) // false (subset!=superset)
setTest1.isDisjoint(with: setTest2) // true
Fundamental Set Operations
- intersection (교집합)
- union (합집합)
- subtracting (차집합)
- symmetricDifference (대칭 차집합)
intersection (교집합)
favoriteFruits = Set(["Apple", "Orange", "Melon", "Kiwi"])
tropicalFruits = Set(["Banana", "Papaya", "Kiwi", "Pineapple"])
if favoriteFruits.isDisjoint(with: tropicalFruits) {
print("favoriteFruits ∩ tropicalFruits = ∅")
} else {
print("favoriteFruits ∩ tropicalFruits")
}
let commonSet = favoriteFruits.intersection(tropicalFruits)
commonSet // Kiwi
favoriteFruits // ["Melon", "Kiwi", "Orange", "Apple"]
tropicalFruits.formIntersection(favoriteFruits) // "Kiwi"
tropicalFruits // "Kiwi"
※ formIntersection : Removes the elements of the set that aren’t also in the given sequence
union (합집합)
favoriteFruits = Set(["Apple", "Orange", "Melon", "Kiwi"])
tropicalFruits = Set(["Banana", "Papaya", "Kiwi", "Pineapple"])
var unionSet = favoriteFruits.union(tropicalFruits)
unionSet //["Melon", "Kiwi", "Orange", "Apple"]
let fruitsType = Set(["Banana","WaterMelon"])
unionSet.formUnion(fruitsType)
// ["Melon", "Kiwi", "Banana", "Orange", "Apple", "WaterMelon"]
subtracting (차집합)
favoriteFruits = Set(["Apple", "Orange", "Melon", "Kiwi"])
tropicalFruits = Set(["Banana", "Papaya", "Kiwi", "Pineapple"])
let uncommonSet = favoriteFruits.subtracting(tropicalFruits)
uncommonSet // ["Melon", "Orange", "Apple"]
favoriteFruits.subtract(tropicalFruits)
favoriteFruits // ["Melon", "Orange", "Apple"]
symmetricDifference (대칭 차집합)
let setTest1 = Set(["Banana", "Papaya", "Kiwi", "Pineapple"])
let setTest2 = Set(["Banana", "Papaya",])
setTest2.symmetricDifference(setTest1)
//["Pineapple", "Kiwi"]
'Swift' 카테고리의 다른 글
[Swift] 프로퍼티(Property) (0) | 2019.07.19 |
---|---|
[Swift] 객체지향 프로그래밍(OOP, Object-Oriented Programming) in Swift (0) | 2019.07.12 |
[Swift] 구조체와 클래스 (0) | 2019.07.12 |
[Swift] 열거형(Enumeration) (0) | 2019.07.12 |
[Swift] The Basic 문법 (0) | 2019.06.25 |