티스토리 뷰

Apple 제공 Swift 프로그래밍 가이드(3.0.1)의 Collection Types 중 Array 부분을 공부하며 정리한 글입니다. 개인적인 생각도 조금 들어가있습니다.


들어가며

Swift에서는 값을 저장하기 위한 세 가지 기본적인 콜렉션 타입 Array, Set, Dictionary를 제공한다.

  • Array : 넣은 순서대로 저장되는 콜렉션

  • Set : 값이 중복되지 않는 순서없는 콜렉션

  • Dictionary : key-value 관계를 가지는 순서없는 콜렉션

이 콜렉션 타입들 역시 다른 상수 변수와 마찬가지로 type 체크에 엄격하다. 즉 한번 저장할 값의 type을 정하면 다른 type의 값은 저장할 수 없다. (Any 타입으로 지정시에는 다른 타입의 값들을 저장할 수 있다. Any 타입에 대해서는 나중에 자세히) 

<note> Array, Set, Dictionary 모두 generic collections으로 구현되었다. (Generics 파트에서 자세히)


Mutability of Collections

Array, Set, Dictionary 가 var(변수)일 경우 mutable이 되고 let(상수)일 경우 immutable이 된다.

  • mutable : 생성한 후 자유롭게 콜렉션에 아이템을 추가, 삭제할 수 있다.

  • immutable : 생성한 후에는 콜렉션의 사이즈와 내용을 변경할 수 없다.


Array

Array는 같은 타입의 값을 들어온 순서대로 그냥 저장한다. 따라서 인덱스는 달라도 값이 같은 경우도 생길 수 있다.

<note> Swift’s Array type is bridged to Foundation’s NSArray class.


Array Type Shorthand Syntax

Array<Element> 타입을 [Element] 로 축약해서 나타낼 수 있다.

(이때, Element는 저장할 값의 타입)


Creating an Array

 // 1. initializer syntax를 사용하여 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]

// 2. default value를 지정하여 특정 사이즈의 array 생성
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

// 3. array끼리 더해서 array 생성
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]
// 더해서 새로 만들어지는 Array의 타입은, 더해지는 두 Array의 타입으로부터 유추된다

// [String] 타입과 [Double] 타입의 배열은 + 를 통해 더할 수 없다 (컴파일 에러)
// [Int] 타입과 [Double] 타입도 마찬가지

// 4. Array Literal로 array 생성
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
// var shoppingList = ["Eggs", "Milk"] 만 해도 
// 알아서 shoppingList는 [String] type이 된다.(타입유추)


Accessing and Modifying an Array

 // 1. array 안에 몇 개의 item이 있는지 알기 위해 -> count 프로퍼티
print("The shopping list contains \(shoppingList.count) items.")
// prints "The shopping list contains 2 items."

// 2. array 안이 비어있는지 알기 위해 -> isEmpty 프로퍼티
if shoppingList.isEmpty {
    print("The shopping list is empty.")
}
else {
    print("The shopping list is not empty.")
}
// prints "The shopping list is not empty.”

// 3. array 에 새로운 item을 추가하기 위해 -> append 메서드 (맨 뒤에 추가된다)
shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes

// 4. array + array (저장되는 값의 type이 같아야 함)
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items

// 5. subscript syntax로 특정 index의 값에 접근하기
// (여기서의 subscript syntax란, Array[인덱스넘버]로 Array의 특정 인덱스를 가리키는 문법)
var firstItem = shoppingList[0]
// firstItem is equal to "Eggs”

// 6. subscript syntax로 특정 index의 값을 update 하기
shoppingList[0] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs”

// 7. subscript syntax로 array의 특정 range를 다른 array로 교체
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items (3 item이 새로운 2 item 으로 교체됨)

// 윗 부분의 보충설명
var array:[Int] = [0, 1, 2, 3, 4, 5, 6]
array[2...5] = [9] // array는 [0, 1, 9, 6] 이 된다.
array[0...4] = [0, 1, 2, 3, 4] // 이런 식으로 기존 array의 범위를 넘은 Range 지정시 Runtime Error
// 오직 기존 index의 값을 바꿀때만 
// array[N] = value 또는 array[n...m] = [x, x, x] 문법을 사용가능

// 8. array의 특정 위치에 새로운 item 삽입
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list”

// 보충설명
array = [0, 1, 3];
array.insert(2, at: 2); // [0, 1, 2, 3] 이 된다. 즉 value가 들어갈 index를 지정해주면 되는 것.

array = [0, 1, 2];
array.insert(3, at: 3); // [0, 1, 2, 3] 이 된다.

array = [0, 1, 2];
array.insert(4, at: 4); // Runtime error

// 9. array의 특정 index 값 삭제
let mapleSyrup = shoppingList.remove(at: 0)
// remove 메서드는 지정한 인덱스의 아이템을 remove하고 그 아이템의 값을 return한다
// mapleSyrup 상수에 들어있는 값은 shoppingList Array의 첫번째 아이템이었던 "Maple Syrup"
firstItem = shoppingList[0]
// "Six eggs”

// 10. array의 가장 마지막 값 삭제
let apples = shoppingList.removeLast()
// apples 상수에 들어있는 값은 shoppingList Array의 마지막 아이템이었던 "Apples"


Iterating Over an Array

for-in loop 를 사용하여 Array를 순회할 수 있다.

for item in shoppingList {
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas

for-in loop 안에서 배열의 값만이 아니라 index도 필요한 경우에는 enumerated() 메서드를 사용한다. 그러면 (index, value)의 tuple을 for-in loop안에서 사용할 수 있다. 이때의 index는 integer value다.

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


'Swift 공식 가이드 > Swift 3' 카테고리의 다른 글

Control Flow  (0) 2017.02.15
Collection Types - Dictionary  (0) 2017.02.11
Collection Types - Set  (0) 2017.02.11
Strings and Characters  (2) 2017.02.05
Basic Operators  (0) 2017.02.05
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함