Created
May 23, 2017 16:58
-
-
Save devxoul/fe4217c4a82c8158514cf8a1dd917915 to your computer and use it in GitHub Desktop.
패스트캠퍼스 iOS 프로젝트 캠프 - 교재에 없는 Swift 예시
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 배열과 클로저 활용 | |
// | |
[1, 3, 6, 2, 7, 9] | |
.filter { $0 % 2 == 0 } // 짝수 필터링 | |
.map { $0 * 2 } // 모든 값에 곱하기 2 | |
.reduce(0, +) // 초깃값부터 각각의 값에 더하기 연산 | |
// | |
// 튜플 활용 | |
// | |
typealias CoffeeInfo = (name: String, price: Int) | |
let coffeeInfo: [CoffeeInfo] = [ | |
("아메리카노", 4300), | |
("롱블랙", 5000), | |
("라떼", 4500), | |
("플랫화이트", 5200), | |
] | |
func findCoffee(withName name: String) -> CoffeeInfo? { | |
return coffeeInfo | |
.lazy // lazy evaluation | |
.filter { $0.name == name } // 이름이 같은 커피 정보를 필터링 | |
.first // 결과 중 가장 첫 번째 결과 | |
} | |
findCoffee(withName: "롱블랙")?.price // 5000 | |
// | |
// Enum 활용 | |
// | |
enum APIResult { | |
case success(String) | |
case failure(APIError) | |
} | |
enum APIError { | |
case timeout | |
case invalidParameter(field: String, reason: String) | |
} | |
func fetchUsername(userID: Int, completion: (APIResult) -> Void) { | |
print("fetchUsername(userID: \(userID))") | |
if userID > 0 { | |
return completion(.success("fastcampus")) | |
} else { | |
return completion(.failure(.invalidParameter(field: "userID", reason: "userID는 0보다 커야 합니다."))) | |
} | |
} | |
fetchUsername(userID: 123) { result in | |
switch result { | |
case .success(let username): | |
print("사용자 이름: \(username)") | |
case .failure(let error): | |
print("API 요청 실패: \(error)") | |
} | |
} | |
fetchUsername(userID: -100) { result in | |
switch result { | |
case .success(let username): | |
print("사용자 이름: \(username)") | |
case .failure(let error): | |
print("API 요청 실패: \(error)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment