티스토리 뷰

반응형
SMALL

이번 포스트에서는 Swift에서 제공하는 Collection 타입에 대해 알아보도록 하겠습니다.

 

Swift에서는 Collection Type으로 Array (배열), Dictionary (딕셔너리), Set (집합) 을 제공합니다.

Objective-C에서는 Immutable과 Mutable이 구분되어 있었는데 Swift에서는 var와 let으로 그 기능을 사용할 수 있습니다.

 

var로 정의하게 되면 Mutable이 되는 것이며 let으로 정의되면 Immutable이 됩니다.

(예를 들어, NSMutableArray와 NSArray는 swift에서 var arr: [Int]? / let arr = [Int]() 와 같이 사용할 수 있습니다.)

var arrayMutable: [Int]? // 변경 가능
let arrayImmutable: [Int] = [Int]() // 변경 불가능

배열 (Array)

Swift에서 배열을 선언하는 방법은 여러 가지가 있습니다만, 주로 간편하게 다음과 같이 사용합니다.

var persons: [Person] = [Person]()
var names = [String]()

혹은, repeating과 count를 사용하여 기본 값으로 빈 배열을 만들 수 있습니다.

var multiNumbers = Array(repeating: 0.3, count: 2)

// multiNumbers : Double 타입의 수가 들어있는 [0.3, 0.3] 배열

다른 배열을 추가한 배열을 생성할 수도 있습니다.

var array1 = Array(repeating: 1.2, count: 2)
var array2 = Array(repeating: 2.4, count: 4)

var array3 = array1 + array2

// array3 : [1.2, 1.2, 2.4, 2.4, 2.4, 2.4]

직접 리터럴 값을 사용하여 배열을 선언할 수도 있습니다.

var persons: [String] = ["Kevin", "Denny", "Mike"]

var simplePersons = ["Kevin", "Denny", "Mike"] // 타입을 명시하지 않고도 가능

배열의 접근 및 각종 연산 소개

// 배열의 요소 개수 확인
print("name의 개수는 \(persons.count) 입니다.")

// 배열에 원소 추가
persons.append("Julie")
persons += ["Elliott"]
persons += ["Jack", "Tom"]


// 배열이 비어있는지 확인
if persons.isEmpty {
	print("비었습니다.")
} else {
	print("비어있지 않습니다.")
}

// 특정 위치의 값 접근
var item = persons[0]

persons[1..3] = ["AAA", "BBB"]
// 인덱스 1부터3까지의 아이템을 AAA, BBB로 변경한다.
// 즉, 1부터 3까지의 3개의 요소를 2개의 요소(AAA, BBB)로 변경한다는 뜻
// 배열의 크기가 1 감소한다.

// 특정 위치에 아이템 추가/삭제/접근
persons.insert("DDD", at: 2)

let person = persons.remove(at: 1)
let lastPersons = persons.removeLast()

배열의 순회 (Traverse)

for in 구문을 통해 배열의 모든 원소를 순회할 수 있습니다.

for person in persons {
	print("TEST : \(person)")
}

Java로 치면 for each 구문이라고 보면 될 것 같습니다.

 

Index를 사용하고 싶다면 다음과 같이 사용할 수 있습니다.

for (index, person) in persons.enumerated() {
	print("index \(index) => \(person)")
}

Set (집합)

Set으로 저장되려면 데이터 타입은 반드시 Hashable이어야만 합니다. 

Swift에서는 Int, Double, String, 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.insert("a")
letters = []

배열 리터럴을 이용한 Set 생성

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

var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"] // 타입 추론이 되므로 타입 생략
if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}
// I have particular preferences.

기본적인 추가, 삭제, 접근 등은 배열과 동일합니다.

 

Set에서 제공하는 Method

 

Set에서 제공하는 Method는 크게 4가지며 사용 예시는 아래 코드와 같습니다.

집합이기 때문에 교집합, 합집합, 차집합, 교집합의 여집합 (ㅡ,.ㅡ 이름이 뭐였더라...) 4가지가 있습니다.

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]

Set의 맴버십과 동등 비교

Set의 동등비교와 맴버 여부를 확인하기 위해 각각 == 연산자와

isSuperset(of:), isStrictSubset(of:), isStrictSuperset(of:), isDisjoint(with:)

메소드를 사용합니다.

isDisjoint(with:) 메소드는 둘 간의 공통된 값이 없는 경우에 true (참)을 리턴합니다.

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

houseAnimals.isSubset(of: farmAnimals)
// 참
farmAnimals.isSuperset(of: houseAnimals)
// 참
farmAnimals.isDisjoint(with: cityAnimals)
// 참

사전(Dictionaries)

(유의)
Swift의
Dictionary타입은 Foundation 클래스의 NSDictionary를 bridge한 타입입니다.

Swift에서는 [Key: Value] 형태로 Dictionary를 선언해 사용할 수 있습니다.

var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"
namesOfIntegers = [:]  // 빈 Dictionary

리터럴를 이용한 Dictionary의 생성

[key 1: value 1, key 2: value 2, key 3: value 3] 형태로 Dictionary를 선언할 수 있습니다.

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

Dictionary의 접근과 변경

// 개수를 반환하는 방법
print("The airports dictionary contains \(airports.count) items.")

// 값을 할당하는 방법
airports["LHR"] = "London"

// 비어있는지 체크하는 방법
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}

 

이번 포스트에서는 Swift에서 제공하는 Collection Type에 대해 알아보았습니다.

 

반응형
LIST

'프로그래밍언어 > Swift' 카테고리의 다른 글

Swift 함수  (0) 2020.02.23
Swift 메모리 안정성  (0) 2020.02.16
Swift 제어문 (조건문, 반복문)  (0) 2020.02.14
Swift 문자열과 문자  (0) 2020.02.09
Swift의 기본 연산자  (0) 2020.02.09
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함