Swift는 값 컬렉션을 저장하기 위해 배열, 집합, 딕셔너리 로 알려진 세가지 기본 컬렉션 유형을 제공한다.
Array, Set, Dictionary
컬렉션의 가변성 (Mutability of Collections)
배열, 집합, 딕셔너리를 변수에 할당해서 생성하면 항목을 추가, 제거, 변경이 가능하다.
하지만 상수에 할당하였을 경우 변경할 수 없으며 크기와 내용을 변경할 수 없다.
배열(Arrays)
배열은 값을 순서가 있는 리스트와 같은 형식으로 값을 저장한다. 같은 값이 다른 위치에서 나타날 수 있다.
즉 중복을 허용한다.
- Array<Element Type>
- [Element] : 축약 형식
초기화 구문을 통해 빈 배열을 만들 수 있고 기본값을 넣어 배열을 만들 수 있다.
var intArray: [Int] = [] // 빈 배열
intArray.append(3) // [3]
intArray.append(5) // [3,5]
var threeDoubles = Array(repeating: 0.0, count: 3)
// [0.0, 0.0, 0.0]
배열 리터럴을 통해 배열을 추가할 수 있고 여러 개의 배열을 포함해서 배열을 만들 수도 있다.
var shoppingBag = ["Eggs", "Milk"]
// Swift는 해당 배열의 타입이 String임을 추측한다.
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
Array.count 속성을 통해 배열의 항목 수를 알 수 있다.
Array.isEmpty 속성을 통해 배열이 비어있는지 true/false 로 확인할 수 있다.
Array.append(~) 로 배열 끝에 새 항목을 추가할 수 있다.
+= 연산자를 통해 여러 배열을 하나로 합칠 수 있다.
Array.insert(_, at: ) 메소드로 원하는 곳에 항목을 추가할 수 있다.
Array.remove(at : ) 메소드로 항목을 삭제할 수 있다.
만약 중간 항목이 삭제되면 자동으로 앞으로 당겨진다. (C 에서 Linked List 처럼)
for - in 루프를 이용해서 배열 전체 값 세트를 반복할 수 있다. 값만 가져올수도 있고 index 도 포함해서 순회할 수 있다.
for item in shoppingList {
print(item)
}
// Six eggs ...
for (index, value) in shoppingList.enumerated() {
print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs ...
Set (집합)
순서가 없고 중복을 허락하지 않음.
딕셔너리 (Dictionaries)
[key:value] 형식으로 나타낼 수 있는 사전 형식의 자료구조이다.
순서가 없고 sort 하려면 key 혹은 value의 속성 메소드를 사용해야 한다.
Dictionary<Key Type, Value Type>
혹은 [Key: Value]
마찬가지로 비어 있는 딕셔너리로 초기화가 가능하다.
var namesOfIntegers: [Int: String] = [:]
namesOfIntegers[16] = "sixteen" // 배열처럼 할당 가능
namesOfIntegers = [:] // 다시 빈 딕셔너리로 초기화 가능
딕셔너리도 마찬가지로 딕셔너리 리터럴로 생성이 가능하다.
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
배열과 마찬가지로 count와 isEmpty 속성을 이용할 수 있다.
print("The airports dictionary contains \(airports.count) items.")
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary isn't empty.")
}
서브스크립트 구문을 통해 새로운 키와 값을 할당해서 새 항목을 추가하거나 기존 항목을 수정할 수 있다.
airports["LHR"] = "London"
위 과정을 조금 더 명시적으로 나타낼 수 있는 메소드를 통해 수정 할 수 있다. (updateValue)
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
// Prints "The old value for DUB was Dublin."
서브 스크립트 구문을 통해 nil 값을 할당해서 값을 제거할 수 있고 마찬가지로 명시적으로 removeValue 메소드를 통해 나타낼 수 도 있다.
airports["APL"] = nil
if let removedValue = airports.removeValue(forKey: "DUB") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary doesn't contain a value for DUB.")
}
키 밸류를 이용해 for-in 문을 돌릴 수 있다. 당연히 따로따로 돌릴 수도 있다.
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
for airportName in airports.values {
print("Airport name: \(airportName)")
}
for - in 구문에서 결과값들을 배열에 넣고 싶으면 아래와 같이 할 수도 있다.
let airportCodes = [String](airports.keys)
// airportCodes is ["LHR", "YYZ"]
let airportNames = [String](airports.values)
// airportNames is ["London Heathrow", "Toronto Pearson"]
[Swift] 함수 (0) | 2022.01.01 |
---|---|
[Swift] 제어 흐름 (0) | 2022.01.01 |
[Swift] 문자 및 문자열 (0) | 2022.01.01 |
[Swift] 기본 연산자 (0) | 2022.01.01 |
[Swift] 첫 시작과 계기, 기초 (0) | 2022.01.01 |
댓글 영역