나의 발자취
Swift Notes for Professionals PDF (3) Arrays 본문
Syntatic sugar란?
컴퓨터과학에서 사용하는 용어로, 좀 더 쉽게 읽고 쓸 수 있는 syntax를 말한다.
스위프트에서 배열을 만들 때 Array<T>보다 [Int] 가 더 직관적으로 와닿으므로, [Int]가 syntatic sugar이라고 할 수 있다.
Array에서의 Type Annotation
> as를 쓰면 된다.
let arrayOfUInt8s: [UInt8] = [2, 4, 7] // type annotation on the variable
let arrayOfUInt8s = [2, 4, 7] as [UInt8] // type annotation on the initializer expression
let arrayOfUInt8s = [2 as UInt8, 4, 7] // explicit for one element, inferred for the others
Arrays with repeated values
반복되는 걸 넣고싶으면 Array() 메서드의 count 인자를 사용해서 값을 채워준다.
// An immutable array of type [String], containing ["Example", "Example", "Example"]
let arrayOfStrings = Array(repeating: "Example",count: 3)
Multidimensional Array
예를 들어, 3차원 배열을 만들고싶으면 아래와 같이..;; 하거나,
var array3x4x5 = Array(repeating: Array(repeating: Array(repeating: 0,count: 5),count: 4),count: 3)
(심기가 불편해서) Pythonic Code 잠깐 삽입
array_3x4x5 = [[[0 for _ in range(5)] for _ in range(4)] for _ in range(3)]
또는 함수를 만들어서 인자값으로 넣는다.
func create3DArray(dim1: Int, dim2: Int, dim3: Int, initialValue: Int) -> [[[Int]]] {
return Array(repeating: Array(repeating: Array(repeating: initialValue, count: dim3), count: dim2), count: dim1)
}
let array3x4x5 = create3DArray(dim1: 3, dim2: 4, dim3: 5, initialValue: 0)
또는 노가다가 있다. ^^
let array3x4x5: [[[Int]]] = [[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]],
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]]
Any 타입의 Array에서 원하는 자료형만 추출하기 - compactMap()
let things: [Any] = [1, "Hello", 2, true, false, "World", 3]
let numbers = things.compactMap { $0 as? Int } // [1, 2, 3]
Array 요소 결합하기 - reduce(_: combine: )
reduce() 는 초기값이 필요하다. sum 을 위해서 논리적 초기값을 0으로 주어진다. 아래의 예시에서 만약 reduce()에 N을 집어넣으면, sum의 결과값은 N+36이 될 것이다.
let numbers = [2, 5, 7, 8, 10, 4]
let sum = numbers.reduce(0) {accumulator, element in
return accumulator + element
}
print(sum) // 36
위의 예시에서처럼, reduce에 전달되는 클로저는 두 개의 argument가 있다. accumulator는 각 iteration을 돌면서 클로져가 반환하는 값이고, element는 iteration에 사용되는 현재 요소의 값이다.
위처럼 사용할 수도 있지만, 간단하게 아래와 같이 사용할 수 있다.
let numbers = [2, 5, 7, 8, 10, 4]
let sum = numbers.reduce(0, combine: +)
Array 내의 결과값들을 납작하게 만들기 - flatMap(_:)
배열에 있는 모든 숫자들을 납작하게 만드는 것인데, 이 원리는 다음과 같다.
let primes = ["2", "3", "5", "7", "11", "13", "17", "19"]
let allCharacters = primes.flatMap { $0 }
print(allCharacters)
// ["2", "3", "5", "7", "1", "1", "1", "3", "1", "7", "1", "9"]
1. primes는 [String] 인데, 배열은 시퀀스이므로 flatMap(_:)를 사용할 수 있다. (Swift의 대표적인 Collection Type인 Array, Set, Dictionary는 Collection 프로토콜을 conform하고, 이 Collection 프로토콜은 Sequence를 conform함)
extension SequenceType {
public func flatMap<S : SequenceType>(transform: (Self.Generator.Element) throws -> S) rethrows
-> [S.Generator.Element]
}
다차원 Array를 납작하게 만들기 - flatMap { $0 }
// A 2D array of type [[Int]]
let array2D = [[1, 3], [4], [6, 8, 10], [11]]
// A 1D array of type [Int]
let flattenedArray = array2D.flatMap { $0 }
print(flattenedArray) // [1, 3, 4, 6, 8, 10, 11]
여기서 .flatMap { Int($0) } 을 써주면 Int만 납작하게 해주거나, nil은 필터링하고 반환한다.
다차원 Array를 납작하게 만들기 - flatMap(\.self)
// A 2D array of type [[Int]]
let array2D = [[1, 3], [4], [6, 8, 10], [11]]
// A FlattenBidirectionalCollection<[[Int]]>
let lazilyFlattenedArray = array2D.flatMap(\.self)
print(lazilyFlattenedArray)
위에서는 요소를 하나씩 가져왔지만, 여기에서의 \.self는 각 배열 요소(즉, [1, 3], [4], [6, 8, 10], [11])를 그대로 가져오는 역할을 한다. 즉, 각 요소를 변환하지 않고 그대로 사용하겠다는 뜻이다.
배열의 nil을 필터해서 가져오기 - compactMap
flatMap()은 옵셔널이랑 컬렉션 타입에서는 Swift에서 더이상 사용하지 않기 때문에, 이 때는 compactMap을 써줘야 한다!
let strings = ["1", "foo", "3", "4", "bar", "6"]
let numbersThatCanBeConverted = strings.compactMap { Int($0) }
print(numbersThatCanBeConverted) // [1, 3, 4, 6]
let optionalNumbers : [Int?] = [nil, 1, nil, 2, nil, 3]
let numbers = optionalNumbers.compactMap { $0 }
print(numbers) // [1, 2, 3]
'앱 개발 > iOS' 카테고리의 다른 글
[iOS] 테이블뷰컨트롤러에서 데이터 추가/삭제하기 (3) | 2024.10.22 |
---|---|
[iOS] 로컬에 데이터를 저장하는 PList (2) | 2024.10.21 |
Swift Notes for Professionals PDF (2) Booleans 요약 (0) | 2024.09.19 |
Swift Notes for Professionals PDF (1) 문자열 (0) | 2024.09.19 |
iOS 무한 스크롤 구현하는 법: How to implement an Infinite Scrolling List (2) | 2024.09.16 |