2017년 7월 16일 일요일

Swift 4에서 강화된 Set, Dictionary입니다.

    @IBAction func btn4(_ sender: Any) {
        //swift4에서 튜플의 배열로부터 사전구조를 생성하는 방법
        let tupleArray = [("Monday",30), ("Tuesday",25),
            ("Wednesday",27), ("Thursday",20), ("Friday",24),
            ("Saturday",22), ("Sunday",26)]
        //dict의 init(uniqueKeyWithValues:)를 통해서
        //튜플 배열에서 새로운 사전구조를 생성한다.
        let dictionary = Dictionary(uniqueKeysWithValues:
            tupleArray)
        print("dictionary: \(dictionary)")
        
        //아래와 같이 사용할 수 도 있다.
        let keys = ["Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday", "Sunday"]
        let values = [30, 25, 27, 20, 24, 22, 26]
        let newDictionary = Dictionary(uniqueKeysWithValues:
            zip(keys, values))
        print("newDictionary:\(newDictionary)")
        
        //swift3에서 사용하는 nil병합 연산자(??)
        var seasons = ["Spring": 20, "Summer": 30, "Autumn": 10]
        let winterTemperature = seasons["Winter"] ?? 0
        print("winterTemperature: \(winterTemperature)")
        //swift4에서 사용하는 코드
        let winterTemperature2 = seasons["Winter", default: 0]
        print("winterTemperature2: \(winterTemperature2)")
        
        //기존 swift3에서 기존에 있는 키를 통한 업데이트
        if let authumnTemperature = seasons["Autumn"] {
            seasons["Autumn"] = authumnTemperature + 5
        }
        //if let을 사용해서 옵셔널에서 nil을 체크하고 접근했는데
        //이제는 아래와 같이 default value subscript를 통해
        //접근할 수 있다.
        seasons["Autumn", default: 0] += 5
        print(seasons["Autumn"] ?? "")
        
        //map()과 filter()도 swift4에서 새롭게 디자인되었다.
        //swift3에서 사전이 아닌 배열을 리턴했다.
        //let mappedArrayValues = seasons.map{$0.value * 2}
        let mappedArray = seasons.map{key, value in (key, value*2)}
        print("mappedArray: \(mappedArray)")
        //swift4에서는 아래와 같이 사용한다.
        let mappedArray2 = seasons.map{season in
            (season.key, season.value * 2)}
        print("mappedArray2: \(mappedArray2)")
        //좀 더 축약을 하면
        let mappedArrayShorthandVersion = seasons.map{($0.0, $0.1 * 2)}
        print("mappedArrayShorthandVersion: \(mappedArrayShorthandVersion)")
        //아니면 아래와 같이 접근해도 된다.
        let mappedDictionary = seasons.mapValues{$0 * 2}
        print("mappedDictionary:\(mappedDictionary)")
        
        //swift3에서의 필터
        let filteredArray = seasons.filter{$0.value > 15}
        print("filteredArray:\(filteredArray)")
        //swift4에서의 필터
        //완벽하게 동일한 결과이지만 원본과 동일한 구조의 필터링된
        //사전을 리턴한다.
        let filteredDictionary = seasons.filter{$0.value > 15}
        print("filteredDictionary:\(filteredDictionary)")
        
        //swift4는 사전구조를 스플릿할 수 있다.
        let scores = [7, 20, 5, 30, 100, 40, 200]
        let groupedDictionary = Dictionary(grouping: scores,
                                           by:{String($0).count})
        print("groupedDictionary:\(groupedDictionary)")
        //후행 클로저를 사용하면 다음과 같이 작성할 수 있다.
        let groupedDictionaryTrailingClosure =
            Dictionary(grouping: scores)
            {String($0).count}
        print("groupedDictionaryTrailingClosure:\(groupedDictionaryTrailingClosure)")
        
        //swift3에서 초기 용량을 지정해서 사전을 생성하는 코드
        let ratings: Dictionary<String, Int> =
            Dictionary(minimumCapacity:10)
        //swift4에서 처리
        seasons.capacity
        seasons.reserveCapacity(4)
        
        //swift3에서 필터
        let categories: Set<String> = ["Swift", "iOS",
           "macOS", "watchOS", "tvOS"]
        let filteredCategories = categories.filter{$0.hasSuffix("OS")}
        print("filteredCategories: \(filteredCategories)")
        

    }

[1, 5]
[1, 5, 2]
openFirstSlice: [1, 5]
closedFirstSlice: [1, 5, 2]
openSecondHalf: [8, 4, 10]
closedSecondHalf: [8, 4, 10]
closedSecondSlice: [8, 4, 10]
1: 1
2: 5
3: 2
4: 8
5: 4
6: 10
1: 1
2: 5
3: 2
4: 8
5: 4
6: 10
Your favourite number is a positive one.
교환 이후:[5, 1, 2, 8, 4, 10]
dictionary: ["Tuesday": 25, "Saturday": 22, "Sunday": 26, "Friday": 24, "Monday": 30, "Wednesday": 27, "Thursday": 20]
newDictionary:["Tuesday": 25, "Saturday": 22, "Sunday": 26, "Friday": 24, "Monday": 30, "Wednesday": 27, "Thursday": 20]
winterTemperature: 0
winterTemperature2: 0
20
mappedArray: [("Summer", 60), ("Spring", 40), ("Autumn", 40)]
mappedArray2: [("Summer", 60), ("Spring", 40), ("Autumn", 40)]
mappedArrayShorthandVersion: [("Summer", 60), ("Spring", 40), ("Autumn", 40)]
mappedDictionary:["Summer": 60, "Spring": 40, "Autumn": 40]
filteredArray:["Summer": 30, "Spring": 20, "Autumn": 20]
filteredDictionary:["Summer": 30, "Spring": 20, "Autumn": 20]
groupedDictionary:[2: [20, 30, 40], 3: [100, 200], 1: [7, 5]]
groupedDictionaryTrailingClosure:[2: [20, 30, 40], 3: [100, 200], 1: [7, 5]]
filteredCategories: ["watchOS", "iOS", "macOS", "tvOS"]

댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.

5월 14일 새벽에 chatGPT 4o가 발표되었습니다. 옵티마이즈, 옴니라는 의미인데 실시간 통역, 다자간 회의, 멀티모달 기능의 강화등이 보이네요.

  초격차로 OpenAI진영이 다시 앞서가는 모양을 보여주고 있습니다. 저도 새벽에 일어나자 마자 올라온 영상들과 글을 정리하고 있습니다. ㅎㅎ 영화 HER의 사진이 새벽에 많이 올라왔었는데 저도 안본 영화입니다. 주말에 한번 봐야 할 것 같습니다....