티스토리 뷰

Swift에서는 Collection Type으로 Array, Set, Dictionary 이렇게 세 가지를 지원한다.

기본적인 내용이지만, 한번 더 복습해보도록 하자.

1.  Array

 - Basic: 

 

아래와 같이 빈 배열을 선언할 수 있다.

var someInts = [Int] ()
print("someInts is of type [Int] with \(someInts.count) items.")

// someInts is of type [Int] with 0 items.

someInts.append(3)
// 배열에 3을 추가 했습니다.
someInts = []
// 배열을 비웠습니다. 배열의 아이템 타입은 그대로 Int로 유지됩니다.

 

repeating 메서드와 count 메서드를 사용하여 기본 값으로 빈 배열을 생성할 수도 있다.

var threeDoubles = Array(repeating: 0.0, count: 3)

print(threeDoubles)
//[0.0, 0.0, 0.0]

 

+ 연산자로 서로 다른 두 배열을 합칠 수 있다. (이 때 배열의 타입은 동일해야 한다.)

var threeDoubles = Array(repeating: 0.0, count: 3)

print(threeDoubles)
//[0.0, 0.0, 0.0]

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles : [2.5, 2.5, 2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles : [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

print(sixDoubles)
//[0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

 

아니면 아래와 같이 리터럴을 이용하여 배열을 생성할 수 있다.

var shoppingList: [String] = ["Eggs", "Milk"]

var shoppingList = ["Eggs", "Milk"]

 

- 접근 및 수정:

 

배열의 원소의 개수는 count 프로퍼티를 사용하여 확인하며, isEmpty로 해당 배열이 빈 배열인지 확인할 수 있다.

var shoppingList = ["Eggs", "Milk"]

print("The shopping list contains \(shoppingList.count) items.")
// The shopping list contains 2 items.

if shoppingList.isEmpty {
    print("The shopping list is empty.")
} else {
    print("The shopping list is not empty.")
}
// The shopping list is not empty.

 

append로 해당 배열에 원소를 추가할 수 있으며, + 연산자 또한 사용이 가능하다.

var shoppingList = ["Eggs", "Milk"]

shoppingList.append("Four")

shoppingList += ["Baking Powder"]
// shoppingList.count = 4
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]

print(shoppingList)
//["Eggs", "Milk", "Baking Powder", "Chocolate Spread", "Cheese", "Butter"]

 

[index]로 특정 원소에 접근하며, range 변수도 사용할 수 있다.

var shoppingList = ["Eggs", "Milk"]

shoppingList.append("Four")

shoppingList += ["Baking Powder"]
// shoppingList.count = 4
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]

print(shoppingList)

var firstItem = shoppingList[0]
// firstItem : "Eggs"

shoppingList[4...6] = ["Bananas", "Apples"]
// 4, 5, 6번째 인덱스 아이템을 Banana, Apples로 변환
// 즉, 아이템 3개가 2개로 줄었다.

 

특정 위치의 원소 추가/삭제/접근은 아래 예제와 같이 할 수 있다.

var shoppingList = ["Eggs", "Milk"]

shoppingList.append("Four")

shoppingList += ["Baking Powder"]
// shoppingList.count = 4
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]

print(shoppingList)

var firstItem = shoppingList[0]
// firstItem : "Eggs"

shoppingList[4...6] = ["Bananas", "Apples"]
// 4, 5, 6번째 인덱스 아이템을 Banana, Apples로 변환
// 즉, 아이템 3개가 2개로 줄었다.

shoppingList.insert("Maple Syrup", at:0)

print(shoppingList)
//["Maple Syrup", "Eggs", "Milk", "Four", "Baking Powder", "Bananas", "Apples"]

let mapleSyrup = shoppingList.remove(at: 0)

print(shoppingList)
//["Eggs", "Milk", "Four", "Baking Powder", "Bananas", "Apples"]

let apples = shoppingList.removeLast()

print(shoppingList)
//["Eggs", "Milk", "Four", "Baking Powder", "Bananas"]

 

- 배열의 순회:

for in 구문에서 간편하게 배열을 돌 수 있으며, enumerated() 를 사용하여 인덱스와 함께 값을 확인할 수 있다.

var shoppingList = ["Eggs", "Milk"]

shoppingList.append("Four")

shoppingList += ["Baking Powder"]
// shoppingList.count = 4
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]

for item in shoppingList {
    print(item)
}

// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas

for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas

2.  Set

set 은 중복이 허용되지 않는 배열이라고 생각하면 편하다. set 형태로 저장되기 위해서는 반드시 타입이 hashable 이어야만 한다.

swift에서 String, Int, Double, Bool 같은 기본 타입은 기본적으로 hashable 이기 때문에 따로 신경쓰지 않아도 되지만 커스텀 클래스를 사용할 때는 확인이 필요하다. 

 

- Set의 생성: 

var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")

// letters is of type Set<Character> with 0 items.

letters = []

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

 

- Set의 접근과 변경:

// count
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

print("I have \(favoriteGenres.count) favorite music genres.")

// isEmpty
if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have paricular music preferences.")
}
// I have particular preferences.

// insert
favoriteGenres.insert("jazz")

// remove
if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.")
} else {
    print("I never much cared for that")
}
// Rock? I'm over it.


// contains
if favoriteGenres.contains("Funk") {
    print("I get up on the good foot.")
} else {
    print("It's too funky in here.")
}
// It's too funky in here.

 

- Set의 순회:

마찬가지로 for-in을 이용하여 set을 순회할 수 있다.

for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz

 

- Set Operation:

let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

print(oddDigits.union(evenDigits).sorted())
//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(oddDigits.intersection(evenDigits).sorted())
//[]

print(oddDigits.subtracting(singleDigitPrimeNumbers).sorted())
//[1, 9]

print(oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted())
//[1, 2, 9]

 

- Set의 멤버 여부 비교:

Set의 동등 여부와 멤버 여부를 확인하기 위해 각각 == 연산자와 isSuperset(of:), isSubset(of:), isStrictSuperset(of:), isStrictSubset(of:), isDisjoint(with:) 메서드를 사용한다. super set과 sub set은 각각 포함하는, 포함되는 관계를 나타내며, disjoint는 두 set이 공통 값을 가지지 않는 경우에 true를 반환한다.

 

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.  Dictionary

[Key:Value] 형태로 Dictinary를 선언하여 사용할 수 있다.

 

- Dictionary의 생성

var namesOfIntegers = [Int: String] ()

namesOfIntegers[17] = "seventeen"

namesOfIntegers = [:]

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

 

- 값 할당과 count, isEmpty:

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

//count
print("The airports dictionary contains \(airports.count) items.")
// The airports dictionary contains 2 items.

//isEmpty
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// The airports dictionary is not empty.
Comments