티스토리 뷰

Swift 3.0.1 가이드에 대응하는 정리글을 작성하였습니다!!!

Array 정리 최신버전 링크 > http://wlaxhrl.tistory.com/35



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


들어가며

Swift에서는 값을 저장하기 위한 세 가지 기본적인 콜렉션 타입 Array, Set, Dictionary를 제공한다. Array는 넣은 순서대로 저장되는 콜렉션, Set은 값이 중복되지 않는 순서없는 콜렉션,  Dictionary는 key-value 관계를 가지는 순서없는 콜렉션이다. 이 콜렉션 타입들 역시 다른 상수 변수와 마찬가지로 type 체크에 엄격하다. 즉 한번 저장할 값의 type을 정하면 다른 type의 값은 저장할 수 없다. 만약 Any 타입으로 지정시에는 Int값과 String값을 같이 저장할 수 있다. 또한 세 가지 모두 generic collections으로 구현되었다. (이 부분은 나중에 다룹니다)

Array, Set, Dictionary를 var(변수)에 할당하면 mutable이 되고 let(상수)에 할당하면 immutable이 된다.

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

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


Array

Array는 같은 타입의 값을 들어온 순서대로 저장한다. index는 0부터 시작한다.

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 = [Double](count: 3, repeatedValue: 0.0)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

// 3. array끼리 더해서 array 생성
var anotherThreeDoubles = [Double](count: 3, repeatedValue: 2.5)
// 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가 저장하는 값의 type이 같아야 한다

// 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이 있는지 알기 위해서
print("The shopping list contains \(shoppingList.count) items.")
// prints "The shopping list contains 2 items."

// 2. array 안이 비어있는지 알기 위해서
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을 추가하기 위해 (맨 뒤에 추가된다)
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. 특정 index의 값에 접근
var firstItem = shoppingList[0]
// firstItem is equal to "Eggs”

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

// 7. 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", atIndex: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list”

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

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

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

// 9. array의 특정 index 값 삭제
let mapleSyrup = shoppingList.removeAtIndex(0)
// the item that was at index 0 has just been removed
// shoppingList now contains 6 items, and no Maple Syrup
firstItem = shoppingList[0]
// firstItem is now equal to "Six eggs”

// 10. array의 가장 마지막 값 삭제
let apples = shoppingList.removeLast()
// the last item in the array has just been removed


Iterating Over an Array

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

for item in shoppingList
{
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
// for item in shoppingList.reverse() 를 하면 뒤에서부터 돈다.

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

for (index, value) in shoppingList.enumerate()
{
    print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas


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

Control Flow  (0) 2016.03.03
Collection Types - Dictionary  (0) 2016.03.01
Collection Types - Set  (0) 2016.03.01
Strings and Characters  (0) 2016.02.28
Basic Operators  (1) 2016.02.28
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 31
글 보관함