Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] 자주 쓰지 않지만 유용한 연산자 (isMultiple(of:), compactMapValues, 딕셔너리 value 변환) 본문

iOS 응용 (swift)

[iOS - swift] 자주 쓰지 않지만 유용한 연산자 (isMultiple(of:), compactMapValues, 딕셔너리 value 변환)

jake-kim 2024. 4. 3. 01:43

isMultiple(of:) 연산자

  • 나누어 떨어지는지 판단하는 연산자
// bad
print(6 % 3 == 0) // true

// good
print(6.isMultiple(of: 3)) // true

compactMapValues 연산자

  • 딕셔너리의 value값을 mapping하는 연산자
let dictionary = ["a": "1", "b": "2", "c": "three"]

// bad
var convertedDictionary1 = [String: Int]()
dictionary
    .forEach {
        if let val = dictionary[$0.key], let int = Int(val) {
            convertedDictionary1[$0.key] = int
        }
    }
print(convertedDictionary1) // ["a": 1, "b": 2]

// good
let convertedDictionary2 = dictionary.compactMapValues { Int($0) }
print(convertedDictionary2) // ["a": 1, "b": 2]

 

* 전체 코드: https://github.com/JK0369/ExCompactMapValues

Comments