이 함수는 어떻게
private func appendPositionNameArray() -> [String] {
var positionNameArray: [String] = []
for num in 0...selectedBand.filledPosition.count - 1 {
positionNameArray.append(selectedBand.filledPosition[num].position.toKorean())
}
return positionNameArray
}
이렇게 획기적인 한 줄이 될 수 있었는가? 에 관한 이야기.
selectedBand.filledPosition.map { ($0.position.toKorean()) }
먼저 이 코드를 이해하려면 우리 프로젝트의 데이터 구조에 대한 간략한 설명이 필요하다.
selectedBand
변수에 활용되는 bands
라는 배열은 다음과 같이 구성되어 있다.
static var bands: [BandInfo] = [
BandInfo(
bandID: "bandID-001",
band: Band(
name: "로젤리아",
filledPosition: [
.init(position: .vocal, numberOfPerson: 2),
.init(position: .bass, numberOfPerson: 1),
.init(position: .drum, numberOfPerson: 1),
.init(position: .guitar, numberOfPerson: 2),
.init(position: .keyboard, numberOfPerson: 1),
.init(position: .etc, numberOfPerson: 2)
],
repertoire: [
"Oasis - Wonderwall",
"Oasis - Champagne Supernova",
"Oasis - Stop Crying Your Heart Out"
],
ageGroups: [
.twenties,
.thirties
],
location: Location(
name: "로젤리아",
address: "경북 포항시 남구 시청로 1",
additionalAddress: "포항시청",
coordinate: Coordinate(
latitude: 36.0191816,
longitude: 129.3432983
)
),
introduction:
"""
안녕하세요.
저희는 오아시스를 좋아하는 밴드 로젤리아입니다.
"""
)
),
// 이하, 위와 같은 식으로 BandInfo 구조체의 여러 개 배열
이 map 함수를 설명하기 위해 필요한 Band
라는 구조체 안에는 다음과 같이 밴드의 정보가 나타나 있다.
열거형 PlayPosition
은 PositionSet
내의 postion
변수 값을 한글로 바꾸는 역할을 한다.
struct Band {
/// 포지션과 해당 포지션의 인원을 나타냅니다.
struct PositionSet {
var position: PlayPosition
var numberOfPerson: Int
}
/// 밴드의 이름입니다.
var name: String
/// 밴드가 갖고있는 포지션입니다.
var filledPosition: [PositionSet]
/// 밴드의 합주곡입니다.
var repertoire: [String]
/// 밴드의 연령대입니다.
var ageGroups: [AgeGroup]
/// 밴드의 합주실 위치입니다.
var location: Location
/// 밴드의 자유소개 글입니다.
var introduction: String
}
enum PlayPosition {
case vocal
case guitar
case keyboard
case drum
case bass
case etc
func toKorean() -> String {
switch self {
case .vocal: return "보컬"
case .guitar: return "기타"
case .keyboard: return "키보드"
case .drum: return "드럼"
case .bass: return "베이스"
case .etc: return "그 외"
}
}
}
다시 append
함수로 돌아가보면, 먼저 selectedBand
라는 변수는 bands
배열 중 하나의 요소인 BandInfo
구조체를 담은 변수이다.
즉, 이 함수는 BandInfo
구조체 내에 있는 filledPostion
이라는 배열 내의 값을 새로운 array에 추가하기 위한 함수이다.
private func appendPositionNameArray() -> [String] {
var positionNameArray: [String] = []
for num in 0...selectedBand.filledPosition.count - 1 {
positionNameArray.append(selectedBand.filledPosition[num].position.toKorean())
}
return positionNameArray
}
그래서 이 함수의 return 값을 map으로 나타내면 다음과 같다.
selectedBand.filledPosition.map { (filledPosition: Band.PositionSet) -> String in
return filledPosition.position.toKorean() }
이를 축약하면 다음과 같아진다.
selectedBand.filledPosition.map { ($0.position.toKorean()) }