Swift Collection Types

in #ios7 years ago (edited)
  • 개발도구 : xcode 9.4
  • 언어 및 버전 : swift 4.1


스위트는 값들을 저장하기 위해서 Arrays, Sets, Dictionaries 3가지 Collection Types을 지원합니다.

  1. Arrays : 값이 정렬되어 있습니다.
  2. Sets : 고유한 값이 정렬되어 있지 않습니다.
  3. Dictionaries : 키와 값의 쌍 형식으로 정렬되어 있지 않습니다.

예제 샘플 코드를 이용해서 사용 법을 간단하게 정리해 보았습니다.

1. Arrays

let someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.") // 아이템이 0인 기본 초기화
var shoppingList = ["Eggs", "Milk"]// 아이템이 2개인 기본 초기화
if shoppingList.isEmpty {
    print("The shopping list is empty.")
} else {
    print("The shopping list is not empty.")
}
shoppingList.append("Flour") // 아이템 1개 추가
shoppingList += ["Baking Powder"] // 연산 기호를 이용한 아이템 추가
shoppingList += ["Chocolate Spread", "Cheese", "Butter"] // 연산 기호를 이용한 여러 개 아이템 추가
shoppingList[0] = "Six eggs" // 0번째 아이템인 "Eggs”을 “Six eggs"로 변경
shoppingList.insert("Maple Syrup", at: 0) // 0번째 아이템 앞에 "Maple Syrup"를 추가 
let mapleSyrup = shoppingList.remove(at: 0)// 0번째 아이템 삭제
let apples = shoppingList.removeLast()// 마지막 아이템 삭제
for item in shoppingList {
    print(item)
}// 전체 아이템 출력
for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}// 전체 아이템 출력

2. Sets

var letters = Set<Character>()// 기본 선언 값은 0
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]// 스트링 아이템 3개인 기본 초기화
if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}// Prints "I have particular music preferences.
favoriteGenres.insert("Jazz")// 마지막 아이템 다음에 추가
let removedGenre = favoriteGenres.remove("Rock") // "Rock" 아이템 삭제
if favoriteGenres.contains("Funk") {
    print("I get up on the good foot.")
} else {
    print("It's too funky in here.")
}// "Funk" 아이템 존재 확인
for genre in favoriteGenres {
    print("\(genre)")
}// 전체 항목 출력
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}// 정렬한 전체 항목 출력


let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7] 
oddDigits.union(evenDigits).sorted()// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sorted()//[]
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()// [1, 2, 9]


let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"] 
houseAnimals.isSubset(of: farmAnimals)// true
farmAnimals.isSuperset(of: houseAnimals)// true
farmAnimals.isDisjoint(with: cityAnimals)// true

3. Dictionaries

var namesOfIntegers = [Int: String]()// 아이템이 0인 기본 초기화
namesOfIntegers[16] = "sixteen"// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]// 아이템이 0인 기본 초기화 ( [Int: String] )
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]// 아이템이 2개인 기본 초기화
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}// 아이템 유무 확인
airports["LHR"] = "London"// 아이템 추가 (키: "LHR", 값: "London")
airports["LHR"] = "London Heathrow"// 아이템 변경 (키: "LHR", 값: "London Heathrow")
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}// 값 변경 시 oldValue에 이전 값 리턴됨
if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}// airportName에 “DUB" 키에 해당하는 값 리턴됨
airports["APL"] = "Apple International"
airports["APL"] = nil// “APL”키 아이템 항목 삭제
if let removedValue = airports.removeValue(forKey: "DUB") {
    print("The removed airport's name is \(removedValue).")
} else {
    print("The airports dictionary does not contain a value for DUB.")
}// “DUB”키 아이템 항목 삭제하고 removedValue에 삭제된 아이템 값 리턴됨
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)")
}// 전체 아이템 중 값 출력
let airportCodes = [String](airports.keys)// airportCodes에 키 할당 
let airportNames = [String](airports.values)// airportNames 에 값 할당


* 본 글에서 사용한 이미지와 샘플 소스는 애플 공식 문서 “The Swift Programming Language (Swift 4.1)” 내용을 사용했습니다.