-
Swift 5.6 Arrays기술/iOS 2022. 2. 26. 15:52
배열은 순서대로 같은 타입의 값을 저장합니다. 같은 값은 배열에 다른 순서로 존재할 수 있습니다.
Array Type Shorthand Syntax
Swift 배열의 타입은
Element
를 저장할 배열 값의 타입을 나타내는Array<Element>
로 작성합니다. 또한 짧게[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."
Creating an Array with a Default Value
Swift 의
Array
타입은 기본 값으로 설정하고 크기를 고정하여 배열을 생성하는 초기화도 제공합니다. 적절한 타입의 기본 값과 새로운 배열에 반복될 값의 횟수를 초기화에 전달합니다.var threeDoubles = Array(repeating: 0.0, count: 3) // threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
Creating Array by Adding Two Arrays Together
동등한 타입의 2개의 존재하는 배열을 더하기 연산자를 통해 새로운 배열을 생성할 수 있습니다. 새로운 배열 타입은 2개의 배열의 타입으로 부터 추론됩니다.
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
배열은 콜렉션으로 하나 이상의 값을 작성하여 배열 리터럴로 배열을 생성할 수 있습니다. 배열 맅럴은 값은 목록으로 작성하고 콤마로 구분하며 대괄호로 둘러싸서 작성합니다.
Accessing and Modifying an Array
메서드와 프로퍼티, 서브스크립트 구문을 사용하여 배열에 접근 및 수정이 가능합니다.
배열의 아이템 개수를 알려면 읽기전용
count
프로퍼티로 확인합니다.print("The shopping list contains \(shoppingList.count) items.") // Prints "The shopping list contains 2 items."
부울형
isEmpty
프로퍼티를 사용하여 배열의count
프로퍼티 값이0
인지 아닌지 빠르게 판단할 수 있습니다.if shoppingList.isEmpty { print("The shopping list is empty.") } else { print("The shopping list is not empty.") } // Prints "The shopping list is not empty."
배열의
append(_:)
메서드를 호출하여 배열의 끝에 새로운 아이템을 추가할 수 있습니다.shoppingList.append("Flour") // shoppingList now contains 3 items, and someone is making pancakes
또한 하나의 동등한 아이템 배열은 덧셈 대입 연산자를 통해 추가할 수 있습니다.
shoppingList += ["Baking Powder"] // shoppingList now contains 4 items shoppingList += ["Chocolate Spread", "Cheese", "Butter"] // shoppingList now contains 7 items
서브스크립트 구문을 통해 접근, 수정이 가능합니다. 범위 수정 또한 가능합니다.
var firstItem = shoppingList[0] // firstItem is equal to "Eggs" shoppingList[4...6] = ["Bananas", "Apples"] // shoppingList now contains 6 items
배열의 특정 인덱스에 아이템을 추가하려면
insert(_:at:)
메서드를 호출합니다.shoppingList.insert("Maple Syrup", at: 0) // shoppingList now contains 7 items // "Maple Syrup" is now the first item in the list
비슷하게
remove(at:)
메서드를 통해 배열의 아이템을 삭제할 수 있습니다. 이 메서드는 해당 인덱스의 아이템을 삭제하고 삭제한 아이템을 반환합니다.let mapleSyrup = shoppingList.remove(at: 0) // the item that was at index 0 has just been removed // shoppingList now contains 6 items, and no Maple Syrup // the mapleSyrup constant is now equal to the removed "Maple Syrup" string
배열의 마지막 아이템을 삭제하고싶으면
count
프로퍼티 사용을 피하기 위해remove(at:)
메서드보다removeLast()
메서드를 사용합니다.let apples = shoppingList.removeLast() // the last item in the array has just been removed // shoppingList now contains 5 items, and no apples // the apples constant is now equal to the removed "Apples" string
Iterating Over and Array
for-in
루프를 통하여 배열의 전체 값을 알 수 있습니다.각 아이템의 인덱스뿐만아니라 값도 필요하다면
enumerated()
메서드를 사용합니다. 이 메서드는 정수와 아이템을 조합한 튜플을 반환합니다.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
Sets
집합은 콜렉션 순서와 상관없이 같은 타입의 다른 값을 저장합니다. 아이템의 순서가 중요하지 않거나 아이템이 반복되면 안될 때 배열 대신 집합을 사용할 수 있습니다.
Hash Values for Set Types
집합에 저장하기 위해 타입은 반드시
hashable
해야 합니다. 즉, 해쉬 값을 계산할 수 있는 방법을 타입은 제공해야 합니다.Swift 의 모든 기본 타입은 기본적으로
hashable
이고 집합의 값 타입 또는 딕셔너리의 키 타입으로 사용할 수 있습니다. 연관된 값이 없는 열거형 케이스 값은 기본적으로hashable
입니다.Set Type Syntax
Swift 의 집합 타입은
Set<Element>
로 작성됩니다. 배열과 반대로 짧은 등가 형식이 없습니다.Creating Initializing an Empty Set
초기화 구문을 사용하여 타입을 포함한 빈 집합을 생성할 수 있습니다.
var letters = Set<Character>() print("letters is of type Set<Character> with \(letters.count) items.") // Prints "letters is of type Set<Character> with 0 items."
Creating a Set with an Array Literal
집합 콜렉션으로 하나 이상의 값으로 짧은 방법과 같이 배열 리터럴을 사용하여 집합을 초기화할 수 있습니다
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] // favoriteGenres has been initialized with three initial items
집합 타입은 배열 리터럴에서 추론할 수 없기 때문에
Set
타입은 명시적으로 선언되어야 합니다.Accessing and Modifying a Set
메서드와 프로퍼티로 집합에 접근과 수정할 수 있습니다.
읽기 전용
count
프로퍼티로 집합 아이템 개수를 알 수 있습니다.count
프로퍼티가0
과 같은지를 부울isEmpty
프로퍼티를 사용해 확인할 수 있습니다.집합의
insert(_:)
메서드를 호출하여 집합에 새로운 아이템을 추가할 수 있습니다.집합의
remove(_:)
메서드를 호출하여 집합의 아이템을 삭제할 수 있습니다.
이 메서드는 집합에 아이템이 있는 경우 삭제하고 삭제된 값을 반환하거나 해당 아이템이 없을 경우nil
을 반환합니다. 또한removeAll()
메서드를 통해 전체 아이템을 삭제할 수 있습니다.contian(_:)
메서드를 사용하여 집합에 특정 아이템이 포함되어 있는 지 알 수 있습니다.Iterating Over a Set
for-in
루프와 함께 집합에 값을 반복할 수 있습니다.for genre in favoriteGenres { print("\(genre)") } // Classical // Jazz // Hip hop
Swift 의
Set
타입은 정의된 순서를 가지고 있지 않습니다. 특정 순서로 집합의 값을 반복하려면sorted()
메서드를 사용합니다.for genre in favoriteGenres.sorted() { print("\(genre)") } // Classical // Hip hop // Jazz
Performing Set Operations
두 집합을 합치거나 두 집합의 공통 값을 구하거나 두 집합이 모두 같은 값을 갖고 있거나 한쪽에만 존재하거나 아예 없거나와 같은 기본적인 집합 연산을 효율적으로 수행할 수 있습니다.
Fundamental Set Operations
Set Membership and Equality
아래 그림은 세 집합
a
,b
,c
를 나타내며 공통 요소는 겹쳐 표현합니다.a
는b
의 모든 요소를 포함하므로 집합a
는b
의 초집합이라고 합니다.- 반대로
b
의 요소가a
에 포함되어 있으므로b
는a
의 부분집합이라고 합니다. b
와c
는 공통 요소가 없으므로 분리집합이라 합니다.
let houseAnimals: Set = ["🐶", "🐱"] let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = ["🐦", "🐭"] houseAnimals.isSubset(of: farmAnimals) // true farmAnimals.isSuperset(of: houseAnimals) // true farmAnimals.isDisjoint(with: cityAnimals) // true
Dictionaries
딕셔너리는 순서와 상관없이 콜렉션에 같은 타입의 키와 같은 타입의 값을 저장합니다. 배열과 다르게 특정 순서를 가지고 있지 않습니다. 특정 단어를 찾기 위해서는 사전을 찾는 방법과 같이 식별자를 기준으로 값을 찾을 때 딕셔너리를 사용합니다.
Dictionary Type Shorthand Syntax
Swift 딕셔너리 타입은
Dictionary<Key, Value>
로 적으며Key
는 딕셔너리 키로 사용되는 값의 타입이고Value
는 딕셔너리에 저장될 값의 타입입니다.[Key: Value]
와 같이 짧은 형식으로도 딕셔너리를 작성할 수 있습니다. 두 형식은 기능적으로 동일하지만 짧은 형식을 더 선호합니다.Creating an Empty Dictionary
배열처럼 초기화 구문을 사용하여 타입을 포함한 빈
Dictionary
를 생성할 수 있습니다.var namesOfIntegers = [Int: String]() // namesOfIntegers is an empty [Int: String] dictionary
Creating a Dictionary with a Dictionary Literal
Accessing and Modifying a Dictionary
메서드와 프로퍼티 또는 서브스크립트 구분을 사용하여 딕셔너리에 접근과 수정이 가능합니다. 배열과 마찬가지로 읽기 전용
count
프로퍼티로Dictionary
에 아이템 개수를 확인할 수 있습니다.count
프로퍼티가0
과 같은지 아닌지 부울isEmpty
프로퍼티를 이용하여 확인할 수 있습니다.서브스크립트 구문을 사용하여 새로운 아이템을 추가할 수 있습니다.
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(_:forKey:)
메서드를 사용하여 특정 키에 값을 설정하거나 업데이트 할 수 있습니다. 위의 서브 스크립트 예제와 같이updateValue(_:forKey:)
메서드는 해당 키에 값이 존재하지 않으면 값을 설정 하거나 해당 키에 값이 존재하면 값을 업데이트 합니다. 그러나 서브 스크립트와 다르게updateValue(_:forKey:)
메서드는 업데이트 수행 후에 이전 값을 반환합니다. 이를 통해 업데이트가 발생했는지 여부를 알 수 있습니다.updateValue(_:forKey:)
메서드는 딕셔너리의 값 타입의 옵셔널 값을 반환합니다. 예를 들어 딕셔너리에String
값을 저장하면String?
타입 또는 "옵셔널String
"을 메서드는 반환합니다. 이 옵셔널 값은 해당 키에 존재한 업데이트 전에 값 또는 존재한 값이 없었을 때는nil
을 포함합니다: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
을 반환합니다.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."
딕셔너리의 해당 키에
nil
값을 할당하여 키-값 쌍을 서브 스크립트 구문을 사용하여 삭제할 수 있습니다.또한 딕셔너리에
removeValue(forKey:)
메서드를 사용하여 키-값 쌍을 삭제할 수 있습니다. 이 메서드는 키-값 쌍이 존재하면 삭제하고 삭제된 값을 반환하거나 값이 존재하지 않으면nil
을 반환합니다.Iterating Over a Dictionary
for-in
루프로 딕셔너리에 키-값 쌍을 반복할 수 있습니다. 딕셔너리의 각 아이템은(key, value)
튜플로 반환됩니다.for (airportCode, airportName) in airports { print("\(airportCode): \(airportName)") } // LHR: London Heathrow // YYZ: Toronto Pearson
keys
,values
프로퍼티를 통해 키 또는 값에 반복 가능한 콜렉션을 가져올 수 있습니다.for airportCode in airports.keys { print("Airport code: \(airportCode)") } // Airport code: LHR // Airport code: YYZ for airportName in airports.values { print("Airport name: \(airportName)") } // Airport name: London Heathrow // Airport name: Toronto Pearson
Swift의
Dictionary
타입은 정의된 순서를 가지고 있지 않습니다. 특정 순서로 딕셔리의 키 또는 값을 반복하려면keys
또는values
프로퍼티에sorted()
메서드를 사용 합니다.'기술 > iOS' 카테고리의 다른 글
Swift 5.6 Functions (0) 2022.03.20 Swift 5.6 Control Flow (0) 2022.02.26 Swift 5.6 Strings and Characters (0) 2022.02.25 Swift 5.6 Basic Operators (0) 2022.02.25 Swift 5.6 The Basics (0) 2022.02.25