[Swift] 4. Collection Type

도윤·2021년 7월 12일
0

Swift

목록 보기
4/21

swift는 세가지의 기초적인 Collection type인 array,dictionary,sets을 제공한다.

Mutability of Collections

위에 언급한 Collection type들은 수정이 가능.

  • adding
  • removing
  • changing

let으로 할당하게 된다면 수정이 불가능. 사이즈와 contents가 바뀔 수 없다.


Arrays

순서가 있는 list에 같은 type의 값을 저장.
같은 value는 다른 위치에서 여러번 저장 가능.

Array Shorthand Syntax

Array로 표현하며 Element에는 값의 type을 쓴다.
간편하게 [Element]로 표현도 가능.

Creating an Empty Array

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

someInts.append(3)
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]

Creating an Array with a Default Value

Array 생성 시 default value 설정 가능.

var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

Creating an Array by Adding Two Arrays Together

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]

Creating an Array with an Array Literal

array literal과 함께 array 생성 가능. 더 많이 쓰여지는 방식

var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items

배열 선언시 type을 선언하지 않아도 자동으로 type 지정.

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

Accessing and Modiftying an Array

Array.count : 배열의 길이 찾기
Array.isEmpty : 배열이 비었는지 확인
Array.append(_:) : 배열의 마지막에 item을 추가

(+=) 연산자를 통해 추가 가능

shopping List += ["Banking Poweder"]

subscript syntax를 사용하여 array에서 값을 얻음.

var firstItem = shoppingList[0]
shoppingList[0] = "Six eggs"
// index 0에 해당하는 value가 바뀜.
shoppingList[4...6] = ["bananas","apples"]
// range를 이용하여 값 변경. range의 길이와 대체 value set이 달라도 가능.

삽입 : Array.insert(_:at:)
제거 : Array.remove(at:)
-> removeLast()를 사용하게 되면 index 지정할 필요 없이 가장 마지막 element 제거.

shoppingList.insert("maple syrup", at : 0)
// value를 at:index에 삽입.
shoppingList.remove(at:0)
// at:0에 해당하는 element 제거.

interating Over an Array

for-in loop으로 Array안에 value set을 확인 가능.

for item in shoppingList{
	print(item)
}

만약 value 뿐만 아니라 index도 확인하려 한다면 enumerated() mothod 사용.

for (index,value) in shoppingList.enumerated(){
	print("Item \(index+1): \(value)")
}

Sets

set은 정해진 순서가 없다. item의 순서가 상관없을 때나 아이템이 한번만 저장되길 원한다면 Array 대신 Sets을 사용하면 된다.

Hash Values for Set Types

Set에 저장되기 위해선 hash 할 수 있어야 한다. 여기서 사용되는 해시 값은 Int형이다. 즉 A와 B가 있을 때 A의 해시 값과 B의 해시 값이 같다면 A와 B는 같다고 볼 수 있다.

모든 Swift의 기본적인 타입 (String, Int, Double, Bool)은 해시 할 수 있고 set의 값이나 dictionary의 키값이 될 수 있다.

Creating and Initailizing an Empty Set

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

> letters 변수의 타입은 Set<Character> 선언으로 추론된다.

Set이 한번 선언되고 빈 Set을 주더라도 Set의 변수 타입은 그대로이다.

letters.insert("a")
// letters now contains 1 value of type Characters
letters = []
// letters is now an empty set,but is still of type Set<Character>

Creating a Set with an Array Literal

Set 선언 시 배열을 선언할 때처럼 선언하게 되면 초기값을 설정할 수 있다.

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items

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

Set의 변수 타입을 쓰지 않아도 초기 선언된 element의 타입으로 설정 가능.

Accessing and Modifying a Set

Array와 마찬가지로 count,insert,isEmpty가 있다.

contains(_:) : Set에 특정 element가 존재하는지 확인.

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

return값은 bool타입으로 나타남.

Iterating Over a Set

for-in loop 으로 Set의 value 확인 가능.

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

Set은 순서가 정의되어 있지 않음. sorted() 메소드를 이용하여 '<'연산자로 비교하여 set을 정렬할 수 있다.

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

Performing Set Operations

집합으로, 차집합,교집합,합집합 등 사용 가능.

Fundamental Set Operating

  • intersecion(_:) : 교집합
  • symmetricDifference(_:) : 집합의 중복값 제거한 집합
  • union(_:) : 합집합
  • subtracting(_:) : 차집합
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 Membership and Equality

집합 a는 b의 superset, b의 모든 요소를 포함하고 있다.
반대로 집합b는 a의 subset. b의 모든 요소가 a에 포함된다.
집합b와 c는 disjoint. 교집합이 없다.

  • 두 집합의 모든 value가 같은지 확인하기 위해 == 연산자 사용.
  • isSubset(of:) 한집합의 모든 값이 다른 집합에 포함되는지 확인.
  • isSuperset(of:) 한 집합이 다른 집합의 모든 value를 포함하는지 확인
  • isStrictSubset(of:),isStrictSuperset(of:) : 두 집합이 같지 않으면서 subset,superset인지 확인.
  • isDisjoint(with:) : 교집합이 하나도 없는지 확인.
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

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

Dictionary

dictionary는 같은 타입의 key와 같은 타입의 value사이의 관계를 저장
Set처럼 순서가 정의되어 있지 않다. 모든 값들은 unique하다.

Dictionary Type Shorthand Syntax

Dictionary<key,Value>로 쓰인다.
또한 [Key:Value]로 간편하게도 쓸 수 있다.

Creating an Empty Dictionary

var namesOfIntegers = [Int: String]() 
// namesOfIntegers is an empty [Int: String] dictionary
namesOfIntegers[16] = "sixteen" 
// namesOfIntegers now contains 1 key-value pair 
namesOfIntegers = [:] 
// namesOfIntegers is once again an empty dictionary of type [Int: String]

Creating a Dictionary with a Dictionary Literal

Dictionary Literal로도 생성 가능.

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
//Dictionary 타입을 쓰지 않아도 type 자동 유추.

Accessing and Modifying a Dicionary

Array,Set처럼 count,isEmpty 사용 가능.

subscript index로써 key를 이용하여 새로운 value 할당 가능하고 값도 변경 가능.

airports["LHR"] = "London" 
// the airports dictionary now contains 3 items
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"

updateValue(_:ofKey:) : 만약 해당 key가 dictionary에 존재하지 않는다면 새로운 key/value를 할당하고 key가 존재한다면 value변경.

위의 subscript와 다르게 update후 기존에 저장되어 있던 값을 return해주는데 이때 optional type으로 반환한다.

즉 String value가 저장되었다면 String? or "optional String"을 반환하며, 만약 기존에 저장된 값이 없다면 nil을 반환.
그렇기에 optional binding을 통해 값을 얻어야 한다.

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

subscript syntax로도 위 처럼 value를 얻을 수 있다. 하지만 해당 key값이 존재하지 않을 가능성이 있으므로 마찬가지로 optional binding을 사용해야 한다.

if let airportName = airports["DUB"] { 
	print("The name of the airport is \(airportName).") 
} else { 
	print("That airport is not in the airports dictionary.") 
} 
// Prints "The name of the airport is Dublin Airport."

존재하고 있는 key에 대해 nil을 할당하게 되면 삭제하는 기능을 한다.

airports["APL"] = "Apple International" 
// "Apple International" is not the real airport for APL, so delete it airports["APL"] = nil 
// APL has now been removed from the dictionary

removeValue(forkey:)을 사용해도 제거 가능. 해당하는 key의 값이 존재한다면 제거된 값을 반환하지만 값이 존재하지 않는다면 nil을 반환.

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.") 
} 
// Prints "The removed airport's name is Dublin Airport."

Iterating Over a Dictionary

foo-in loop : 각 아이템은 (key,value) tuple로 반환

for (airportCode,airportName) in airports {
	print("\(airportCode):\(airportName)")
}
// LHR : London Heathrow
// YYZ : Toronto Pearson

Dictionary의 key,value 프로퍼티를 각각 접근 가능

for airportCode in airports.keys{
	print("Airport Code : \(airportCode)")
}
// Airport code : LHR
// Airport code : YYZ

for airportName in airports.values{
	print("Airport name : \(airportName)")
}
// AirportName : London Heathrow
// AirportName : Toronto Pearson

Array instance 이용하여 keys,values 접근 가능.

let airportCodes = [String](airports.keys)
let airportNames = [String](airports.values)

순서가 정의되어 있지 않아서 정렬하려면 sorted()를 이용.

0개의 댓글