본문 바로가기

iOS/Swift

Swift 공식문서 4. Collection Types

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/collectiontypes

 

Documentation

 

docs.swift.org

 

Swift 공식 문서 보면서 내 맘대로 정리


  • Swift에서 제공하는 Collection Type
    • Array
    • Set
    • Dictionary

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/collectiontypes/

  • 모든 Collection 들은 변경 가능하다.
    • var로 선언하면 값을 추가, 삭제, 변경 가능하다. (mutable)
    • let으로 선언하면 추가, 제거, 변경 불가능 하다. (immutable)

Array

  • Array는 같은 타입의 값들을 순서대로 저장
  • 중복된 값이 여러 장소에 존재할 수 있다.
  • 빈 Array 생성
var someInts = [Int]()
  • Array의 모든 값을 동일한 값으로 생성
var threeDoubles = Array(repeating: 0.0, count:3)
  • Array간 '+' 연산이 가능하다 → array 이어 붙이기 
var threeDoubles = Array(repeating: 0.0, count: 3)
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)

var sixDoubles = threeDoubles + anotherThreeDoubles

var shoppingList: [String] = ["Eggs", "Milk"]
shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
  • Array의 프로퍼티
    • array.count
    • array.isEmpty
  • Array의 메서드
    • append()
    • insert(_: at:)
    • remove(at:)
    • removeLast()
  • for-in
for item in shoppingList {
  print(item)
}
  • enumrated
for (index,value) in shoppingList.enumerated() {
  print("Item \\(index +1 ): \\(value)")
}

 

 

Sets

  • Set은 중복허용 안됨
  • Set에 저장하기 위해서는 hashable이어야 한다.
    • 여기서 hash 값은 Int 형이다.
    • a == b 이면 a.hashValue == b.hashValue
    • 모든 Swift의 기본 타입 (String, Int, Double, String)은 Hashable을 준수하고 Set의 값이나 dictionary의 key가 될 수 있다.
    • associated value가 없는 enum도 Hashable을 따른다
    • 사용자 정의 타입을 사용하고 싶으면 Hashable을 채택하면 된다
  • Set 생성
var letters = Set<Character>() 
letters.insert("a") 
letters = []
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
  • Set의 프로퍼티 및 메서드
    • count
    • isEmpty
    • insert(_:)
    • remove(_:)
    • removeAll()
    • contains(_:)
    • sorted()
      • return 값 - 정렬된 Array
  • Iterating
    • for - in
  • Set Operations
    • a.intersection(b) → 교집합
    • a.symmetricDifference(b) → 두 개의 합집합에서 교집합을 뺀 집합
    • a.union(b) → 합집합
    • a.subtracting(b) → 차집합

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/collectiontypes/#Fundamental-Set-Operations

 

  • Set Membership and Equality
    • == → 동일한 값을 포함하는 집합
    • isSubset(of:) → 한 집합이 다른 집합의 부분집합인가
    • isSuperset(of:) → 한 집합이 다른 집합의 상위집합인가
    • isStrictSubset(of:) → 한 집합이 다른 집합의 부분집합이지만 동일하지는 않은 경우
    • isDisjoint(with:) → 두 집합이 서로소인가

Dictionaries

  • key - value 를 갖는 컬렉션 타입
  • Foundation 클래스의 NSDictionary를 bridge를 한 타입입니다.
  • Dictionary 생성
var namesOfIntegers = Dictionary<Int, String>()
var namesOfIntegers: [Int: String] = [:]
  • Dictionary의 프로퍼티 및 메서드
    • count
    • isEmpty
    • updateValue(_:forKey:)
      • 없는 key에 대해 접근 시 수정이 아닌 생성하고 old value를 리턴
    • subscript로 갱신 가능
    • removeValue(forKey:)
      • 삭제한 값 리턴(옵셔널)
    • subscript로 삭제 가능
// updateValue(_:,forKey:)
if let oldvalue = airports.updateValue("Dublin Airport", forKey: "DUB") { 
  print("The old value : \\(oldValue)") 
}

// update with subscript
airports["LHR"] = "London"

// removeValue(forkey:)
if let removedValue = airports.removeValue(forKey: "DUB") {
    print("The removed airport's name is \(removedValue).")
} else {
    print("The airports dictionary doesn't contain a value for DUB.")
}

// remove with subsript
airports["APL"] = nil

 

  • Iterating
    • for - in
      • tuple 형태로 반환
      • keys, values 프로퍼티로 각각 접근할 수 있음
      for (airportCode, airportName) in airports {
        print("\\(airportCode), \\(airportName)")
      }
      
      for airportCode in airports.keys {
        print("\\(airportCode)")
      }
      
      for airportName in airports.values {
        print("\\(airportName)")
      }
  • 만약 Dictionary의 key, value 값을 각각 저장하고 싶다면 새로운 Array를 만들 수 있다.
let airportCode = [String](airport.keys)
let airportNames = [String](airport.values)