Swift - map

2020. 6. 29. 14:34Language/Swift

반응형

map(_:)

Returns an array containing the results of mapping the given closure over the sequence’s elements.

데이터 컨테이너의 지정 된 값을 매핑하여 반환해 준다.

 

딕셔너리 타입의 key 값만 추출 한 배열을 생성할때는 아래와 같이 사용하며,

var dic: Dictionary<Int, Int> = [ 2 : 0, 1 : 0, 3 : 0, 5 : 0, 7 : 0,
                                  6 : 0, 10 : 0, 9 : 0, 4 : 0, 8 : 0]

let keyIntArray = dic.map { (key: Int, value: Int) -> Int in
    return key
}
// [4, 1, 9, 6, 3, 5, 7, 8, 2, 10]

 

조금더 활용해 보면 키값에 대해 타입을 변경하여 추가적인 데이터를 가공하여 아래 처럼 생성 할 수 있다.

var dic: Dictionary<Int, Int> = [ 2 : 0, 1 : 0, 3 : 0, 5 : 0, 7 : 0,
                                  6 : 0, 10 : 0, 9 : 0, 4 : 0, 8 : 0]

let keyStringArray = dic.map { (key: Int, value: Int) -> String in
    return "Dic Key = \(key)"
}
// ["Dic Key = 5", "Dic Key = 4", "Dic Key = 7", "Dic Key = 2", "Dic Key = 1", "Dic Key = 6", "Dic Key = 9", "Dic Key = 8", "Dic Key = 3", "Dic Key = 10"]
반응형

'Language > Swift' 카테고리의 다른 글

Swift - flatMap, compactMap  (0) 2020.07.02
Swift - stride  (0) 2020.07.01
Swift - filter  (0) 2020.06.29
Swift - sort, sorted  (0) 2020.06.29
Swift - forEach  (0) 2020.06.29