checkpoint 5

그루두·2024년 4월 17일
0

100 days of SwiftUI

목록 보기
14/108

100 days of swiftui: checkpoint 5
https://www.hackingwithswift.com/quick-start/beginners/checkpoint-5

challenge

With closures under your belt, it’s time to try a little coding challenge using them.

You’ve already met sorted(), filter(), map(), so I’d like you to put them together in a chain – call one, then the other, then the other back to back without using temporary variables.

Your input is this:

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

Your job is to:
1. Filter out any numbers that are even
2. Sort the array in ascending order
3. Map them to strings in the format “7 is a lucky number”
4. Print the resulting array, one item per line
So, your output should be as follows:

7 is a lucky number
15 is a lucky number
21 is a lucky number
31 is a lucky number
33 is a lucky number
49 is a lucky number

solution

let luckyNumbers = [7, 4, 38, 21, 16, 15, 12, 33, 31, 49]

// print(luckyNumbers.filter({ $0 % 2 != 0 }))
// print(luckyNumbers.filter({ $0 % 2 != 0 }).sorted(by: { $0 < $1 }))
luckyNumbers.filter({ $0 % 2 != 0 }).sorted(by: { $0 < $1 }).map({ print("\($0) is a lucky number") })

메소드를 사용할 때 함수를 넘기고, 그 값을 다음 메소드에 넘기는 형태로 코드를 작성했다. 주석은 순서대로 과제 1, 2, 3 & 4를 해결한 과정이다.

코드 파일
https://github.com/soaringwave/Ios-studying/blob/main/FilterSortMap.playground/Contents.swift

profile
계속 해보자

0개의 댓글

관련 채용 정보