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]