본문 바로가기
Smart Device/Swift

Swift Dictionary

by 언덕너머에 2014. 6. 12.

- Dictionary<KeyType, ValueType>


  Dictionary는 key-value쌍의 정렬되지 않은 Generic Type의 Collection으로 사용된다.

  Dictionary Key들의 모든 값들은 KeyType과 호환되어야 하고, Dictionary의 모든 Value들

  또한 ValueType과 호환되어야 한다.


* init(minimumCapacity: = 2)

  Dictionary는 key-value 쌍으로 초기화되어야 한다.

  init(minimumCapacity: Int = 2)


  예)

  var emptyDictionary = Dictionary<String, Int>()

  // constructs an empty dictionary ready to contain String keys and integer values


* Accessing and Changing Dictionary Elements

  대괄호를 사용해서 Dictionary Elements를 가져오거나 설정하거나 삭제한다.


  예)

  var dictionary = ["one": 1, "two": 2, "three": 3]

  let value = dictionary["two"]

  // value is an optional integer with an underlying value of 2


  if let unwrappedValue = dictionary["three"] {

      println("The integer value for \"three\" was: \(unwrappedValue)")

  }

  // prints "The integer value for "three" was: 3"


  Dictionary에 있는 키로 대괄호를 사용해서 값을 변경하거나 추가 할 수 있다.

  dictionary["three"] = 33

  // dictionary is now ["one": 1, "two": 2, "three": 33]

  

  dictionary["four"] = 4

  // dictionary is now ["one": 1, "two": 2, "three": 33, "four": 4]


  nil을 사용하면 해당 key를 삭제할 수 있다.

  dictionary["three"] = nil

  // dictionary is now ["one": 1, "two": 2, "four": 4]


  Dictionary는 var로 선언될 때만 추가, 수정, 삭제할 수 있다.

  let으로 선언되면 다음과 같은 오류가 발생한다.

  let dictionary = ["one": 1, "two": 2, "three": 3]

  dictionary["four"] = 4

  // Error: could not find an overload for 'subscript' that accepts the supplied arguments

 

  선언된 Dictionary를 초기화(빈 딕셔너리)하는 방법은 다음과 같다.

  dictionary = [:]


updateValue()

  기존의 값을 반환하고, 새로운 값으로 업데이트하는 기능을 한다.

  값이 존재하지 않으면 nil을 반환한다.

  예)

  var dictionaryV = ["one": 1, "two": 2, "three": 33]

  if let oldThree = dictionaryV.updateValue(3, forKey: "three") {

      println("three 과거 값은 \(oldThree) 였다")

      //"three 과거 값은 33 였다"

  } 

  var threeC = dictionaryV["three"]

  println("현재의 three \(threeC) 이다.")

  //"현재의 three Optional(3) 이다."


* removeValueForKey(_:) -> ValueType?

  지정된 key로 key-value 쌍을 삭제하고 해당 key의 값을 반환한다. 

  존재하지 않는 key라면 nil을 반환한다.


  예)

  var dictionary = ["one": 1, "two": 2, "three": 3]

  let previousValue = dictionary.removeValueForKey("two")

  // previousValue is an optional integer with an underlying value of 2


  if let unwrappedPreviousValue = dictionary.removeValueForKey("three") {

      println("Removed the old value: \(unwrappedPreviousValue)")

  } else {

      println("Didn't find a value for the given key to delete")

  }

  // prints "Removed the old value: 3"


  'var'로 선언된 경우에만 가능하고 'let'으로 선언된 경우에는 오류를 발생시킨다.


* removeAll(keepCapacity: = false)

  Dictionary의 모든 key-value 쌍을 삭제하고, storage buffer를 지운다.


  예)

  var dictionary = ["one": 1, "two": 2, "three": 3]

  dictionary.removeAll()

  // previousValue is an optional integer with an underlying value of 2


  'var'로 선언된 경우에만 가능하고 'let'으로 선언된 경우에는 오류를 발생시킨다.


- Querying a Dictionary


* var count { get }

  Dictionary에서 key-value 쌍의 갯수를 나타내는 정수 값을 반환(읽기 전용)


  예)

  var dictionary = ["one": 1, "two": 2, "three": 3]

  let elementCount = dictionary.count

  // elementCount is 3


* var keys { get }

  Dictionary의 모든 key를 unordered iterable collection으로 반환한다.


  예)

  var dictionary = ["one": 1, "two": 2, "three": 3]

  for key in dictionary.keys {

      println("Key: \(key)")

  }

  /* Key: one

      Key: three

      Key: two */



  다음과 같이 Dictionary의 Key로 초기화된 배열을 생성할 수 있다.

  let array = Array(dictionary.keys)

  // array is ["one", "two", "three"]


* var values { get }

  Dictionary의 모든 value를 unordered iterable collection으로 반환한다.


  예)

  var dictionary = ["one": 1, "two": 2, "three": 3]

  for value in dictionary.values {

      println("Value: \(value)")

  }

  /* Value: 1

      Value: 3

      Value: 2 */


  다음과 같이 Dictionary의 Value로 초기화된 배열을 생성할 수 있다.

  let array = Array(dictionary.values)

  // array is [1, 2, 3]


- Operators


* ==

  

  예)

  let dictionary1 = ["one": 1, "two": 2]

  var dictionary2 = ["one": 1]

  dictionary2["two"] = 2

  let result = dictionary1 == dictionary2

  // result is true


* !=


  예)

  let dictionary1 = ["one": 1, "two": 2]

  let dictionary2 = ["one": 1]

  let result = dictionary1 != dictionary2

  // result is true

'Smart Device > Swift' 카테고리의 다른 글

Swift Objects and Classes #2 - Properties getter setter  (0) 2014.06.24
Swift Numeric Types  (0) 2014.06.12
Swift Array #2  (0) 2014.06.11
Swift Array #1  (0) 2014.06.11
Swift String  (0) 2014.06.11