swift는 콜렉션의 값을 저장하기 위한 array, set, dictionary와 같은 3개의 원시적인 콜렉션 타입을 제공합니다. 배열(array)은 콜렉션 값에 순서를 가지고 있습니다. 집합(set)은 반복되지 않은 값에 순서가 없는 콜렉션 타입입니다. 딕셔너리(dictionary)는 키-값 쌍의 순서가 없는 콜렉션 타입입니다.

Untitled

Swift에 배열, 집합, 그리고 딕셔너리는 저장할 수 있는 값의 타입과 키에 대해 항상 명확합니다. 이것은 실수로 콜렉션에 잘못된 타입을 추가할 수 없다는 의미입니다. 또한 콜렉션에서 검색할 값에 대해 타입이 명확하다는 것을 의미합니다.

Swift의 배열, 집합, 딕셔너리타입은 제네릭 콜렉션(generic collections)으로 구현됩니다.

콜렉션의 가변성(Mutablility of Collections)

배열, 집합, 딕셔너리를 생성하고 변수에 할당하면 생성된 콜렉션은 변경 가능(mutable)합니다. 이것은 콜렉션이 생성된 후에 콜렉션의 아이템을 추가, 삭제, 또는 변경할 수 있다는 뜻입니다. 배열, 집합, 딕셔너리를 상수에 할당하면 이 콜렉션은 불가변성이며 크기와 콘텐츠를 변경할 수 없습니다.

var score: [Int]?
// var score: [Int]? = []

if let s = score {
  print(s);
} else {
  print("something wrong");
}

Array 는 순서를 가지고 있다.

Set는 반복되지 않는 값으로 순서가 없다.

Dictionary는 키와 값 쌍으로 순서가 없는 콜렉션 타입

Arrays


순서대로 같은 타입의 값을 저장한다. 같은 값은 배열에 다른 순서로 존재할 수 있습니다.

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

print("someInts is of type [Int] with \\(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."

/** 배열을 더해 생성 (Creating Array by Adding Two Arrays Togethe */

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) */
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items

배열 접근과 수정 (Accessing and Modifying an Array)