ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Swift 정리 #4 컬렉션 타입
    코딩/Swift 2022. 12. 14. 04:13
    728x90

    Arrays: ordered list

    Array Type Shorthand Syntax

    Array<Element>
    [Element] // shorthand

    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."
    
    someInts.append(3)
    // someInts now contains 1 value of type Int
    
    someInts = []
    // someInts is now an empty array, but is still of type [Int]

    Creating an Array with a Default Value

    var threeDoubles = Array(repeating: 0.0, count: 3)
    // threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

    Creating an Array by Adding Two Arrays Together

    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

    [value 1, value 2, value 3]
    var shoppingList: [String] = ["Eggs", "Milk"]
    // shoppingList has been initialized with two initial items
    // shorter form
    var shoppingList = ["Eggs", "Milk"]

    Accessing and Modifying an Array

    print("The shopping list contains \(shoppingList.count) items.")
    // Prints "The shopping list contains 2 items."
    
    if shoppingList.isEmpty {
        print("The shopping list is empty.")
    } else {
        print("The shopping list isn't empty.")
    }
    // Prints "The shopping list isn't empty."
    
    shoppingList.append("Flour")
    // shoppingList now contains 3 items, and someone is making pancakes
    
    shoppingList += ["Baking Powder"]
    // shoppingList now contains 4 items
    
    shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
    // shoppingList now contains 7 items
    
    // subscript syntax
    var firstItem = shoppingList[0]
    // firstItem is equal to "Eggs"
    
    shoppingList[0] = "Six eggs"
    // the first item in the list is now equal to "Six eggs" rather than "Eggs"
    
    // change range
    shoppingList[4...6] = ["Bananas", "Apples"]
    // shoppingList now contains 6 items
    
    // insert an item
    shoppingList.insert("Maple Syrup", at: 0)
    // shoppingList now contains 7 items
    // "Maple Syrup" is now the first item in the list
    
    // remove an item
    let mapleSyrup = shoppingList.remove(at: 0)
    // the item that was at index 0 has just been removed
    // shoppingList now contains 6 items, and no Maple Syrup
    // the mapleSyrup constant is now equal to the removed "Maple Syrup" string
    
    firstItem = shoppingList[0]
    // firstItem is now equal to "Six eggs"
    
    // remove the final item
    let apples = shoppingList.removeLast()
    // the last item in the array has just been removed
    // shoppingList now contains 5 items, and no apples
    // the apples constant is now equal to the removed "Apples" string

    Iterating Over an Array

    for item in shoppingList {
        print(item)
    }
    // Six eggs
    // Milk
    // Flour
    // Baking Powder
    // Bananas
    
    // integer index of each item as well as its 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

    Sets: unordered, unique

    Hash Values for Set Types

    Hashable protocol from the Swift standard library

    Set Type Syntax

    Set<Element>

    Creating and Initializing an Empty Set

    // initializer syntax
    var letters = Set()  
    print("letters is of type Set with (letters.count) items.")  
    // Prints "letters is of type Set with 0 items."  
    
    letters.insert("a")
    // letters now contains 1 value of type Character
    
    letters = []
    // letters is now an empty set, but is still of type Set<Character>

    Creating a Set with an Array Literal

    var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
    // favoriteGenres has been initialized with three initial items
    
    // shorter form
    var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

    Accessing and Modifying a Set

    // find out the number of items in a set
    print("I have \(favoriteGenres.count) favorite music genres.")
    // Prints "I have 3 favorite music genres."
    
    // isEmpty property
    if favoriteGenres.isEmpty {
        print("As far as music goes, I'm not picky.")
    } else {
        print("I have particular music preferences.")
    }
    // Prints "I have particular music preferences."
    
    // add a new item: insert(_:) method
    favoriteGenres.insert("Jazz")
    // favoriteGenres now contains 4 items
    
    // remove an item: remove(_:) method
    // remove all items: removeAll() method
    if let removedGenre = favoriteGenres.remove("Rock") {
        print("\(removedGenre)? I'm over it.")
    } else {
        print("I never much cared for that.")
    }
    // Prints "Rock? I'm over it."
    
    // check whether a set contains a particular item: contains(_:) method
    if favoriteGenres.contains("Funk") {
        print("I get up on the good foot.")
    } else {
        print("It's too funky in here.")
    }
    // Prints "It's too funky in here."

    Iterating Over a Set

    for genre in favoriteGenres {
        print("\(genre)")
    }
    // Classical
    // Jazz
    // Hip hop
    // iterate over the values of a set in a specific order: sorted() method
    for genre in favoriteGenres.sorted() {
        print("\(genre)")
    }
    // Classical
    // Hip hop
    // Jazz

    Performing Set Operations

    Fundamental Set Operations

    • intersection(_:) method: create a new set with only the values common to both sets
    • symmetricDifference(_:) method: create a new set with values in either set, but not both
    • union(_:) method: create a new set with all of the values in both sets
    • subtracting(_:) method: create a new set with values not in the specified set
    let oddDigits: Set = [1, 3, 5, 7, 9]
    let evenDigits: Set = [0, 2, 4, 6, 8]
    let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
    
    oddDigits.union(evenDigits).sorted()
    // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    oddDigits.intersection(evenDigits).sorted()
    // []
    oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
    // [1, 9]
    oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
    // [1, 2, 9]

    Set Membership and Equality

    • ==: contain all of the same values
    • isSubset(of:) method: all of the values of a set are contained in the specified set
    • isSuperset(of:) method: all of the values in a specified set
    • isStrictSubset(of:) or isStrictSuperset(of:) methods: a set is a subset or superset, but not equal to, a specified set
    • isDisjoint(with:) method: two sets have no values in common
    let houseAnimals: Set = ["🐶", "🐱"]
    let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
    let cityAnimals: Set = ["🐦", "🐭"]
    
    houseAnimals.isSubset(of: farmAnimals)
    // true
    farmAnimals.isSuperset(of: houseAnimals)
    // true
    farmAnimals.isDisjoint(with: cityAnimals)
    // true

    Dictionary: unordered, key-value

    Dictionary Type Shorthand Syntax

    // Dictionary<Key, Value>
    // short form [Key: Value]

    Creating an Empty Dictionary

    // initializer syntax:
    var namesOfIntegers: [Int: String] = [:]
    // namesOfIntegers is an empty [Int: String] dictionary
    
    namesOfIntegers[16] = "sixteen"
    // namesOfIntegers now contains 1 key-value pair
    
    namesOfIntegers = [:]
    // namesOfIntegers is once again an empty dictionary of type [Int: String]

    Creating a Dictionary with a Dictionary Literal

    // Dictionary Literal
    // [key 1: value 1, key 2: value 2, key 3: value 3]
    
    var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
    
    // shorter form
    var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

    Accessing and Modifying a Dictionary

    // count property
    print("The airports dictionary contains \(airports.count) items.")
    // Prints "The airports dictionary contains 2 items."
    
    // isEmpty property
    if airports.isEmpty {
        print("The airports dictionary is empty.")
    } else {
        print("The airports dictionary isn't empty.")
    }
    // Prints "The airports dictionary isn't empty."
    
    // add new item: subscript syntax
    airports["LHR"] = "London"
    // the airports dictionary now contains 3 items
    
    // change the value: subscript syntax
    airports["LHR"] = "London Heathrow"
    // the value for "LHR" has been changed to "London Heathrow"
    
    // updateValue(_:forKey:) method: set or update the value
    if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
        print("The old value for DUB was \(oldValue).")
    }
    // Prints "The old value for DUB was Dublin."
    
    // retrieve a value: subscript syntax
    if let airportName = airports["DUB"] {
        print("The name of the airport is \(airportName).")
    } else {
        print("That airport isn't in the airports dictionary.")
    }
    // Prints "The name of the airport is Dublin Airport."
    
    // remove a key-value pair: subscript syntax
    airports["APL"] = "Apple International"
    // "Apple International" isn't the real airport for APL, so delete it
    airports["APL"] = nil
    // APL has now been removed from the dictionary
    
    // remove a key-value pair: removeValue(forKey:) method
    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.")
    }
    // Prints "The removed airport's name is Dublin Airport."

    Iterating Over a Dictionary

    for (airportCode, airportName) in airports {
        print("\(airportCode): \(airportName)")
    }
    // LHR: London Heathrow
    // YYZ: Toronto Pearson
    
    // retrieve
    for airportCode in airports.keys {
        print("Airport code: \(airportCode)")
    }
    // Airport code: LHR
    // Airport code: YYZ
    
    for airportName in airports.values {
        print("Airport name: \(airportName)")
    }
    // Airport name: London Heathrow
    // Airport name: Toronto Pearson
    
    // array
    let airportCodes = [String](airports.keys)
    // airportCodes is ["LHR", "YYZ"]
    
    let airportNames = [String](airports.values)
    // airportNames is ["London Heathrow", "Toronto Pearson"]
    
    // sorted() method: sort
    728x90

    '코딩 > Swift' 카테고리의 다른 글

    Swift 정리 #6 함수  (0) 2022.12.14
    Swift 정리 #5 Control flow  (1) 2022.12.14
    Swift 정리 #3 문자열과 문자  (0) 2022.12.13
    Swift 정리 #2 연산자  (0) 2022.12.13
    Swift 정리 #1 기본  (0) 2022.12.09

    댓글

Designed by Tistory.