본문 바로가기
interactive service/CS

아키텍처와 컴포지션

by jessicahan96 2022. 6. 4.
import UIKit
let result = [1, 2, 3].map { $0 + 1 }.map { "만 \($0) 살"}
print(result)
let num: Int? = nil
let result2 = num.map { $0 + 1 }
print(result2)
let myResult: Result<Int, Error> = .success(2)
let result3 = myResult.map { $0 + 1 }
//1. Generic 타입
/*
    optional -> enum Optional<Wrapped>
    sequence -> associatedtype Element
    result -> enum Result<Success, Failure> where Failure : Error
    publisher -> associatedtype Output
 
*/
//2. Transform 함수를 인자로 받음.

//3.
/*
    transform: A -> B
    F<A> -(map)-> F<B>
 */
let ageString: String? = "10"
let result4 = ageString.map { Int($0) }
/*
    transform: A -> Option<B>
    Optional<A> -(map)-> Optional<Option<B>>
 */
if let x = ageString.map(Int.init), let y = x {
    print(y)
}
if case let .some(.some(x)) = ageString.map(Int.init) {
    print(x)
}
if case let x?? = ageString.map(Int.init) {
    print(x)
}
let result5 = ageString.flatMap(Int.init)
/*
    transform: A -> Option<B>
    Optional<A> -(flatMap)-> Option<B>
 */

// UIEvent -> IndexPath -> Model -> URL -> Data -> Model -> ViewModel -> View

struct MyModel: Decodable {
    let name: String
}

let myLabel = UILabel()

if let data = UserDefaults.standard.data(forKey: "my_data_key") {
    if let model = try? JSONDecoder().decode(MyModel.self, from: data) {
        let welcomeMessage = "Hello \(model.name)"
        myLabel.text = welcomeMessage
    }
}

let welcomeMessage = UserDefaults.standard.data(forKey: "my_data_key")
    .flatMap { try? JSONDecoder().decode(MyModel.self, from: $0)}
    .map { "Hello \($0)" }

myLabel.text = welcomeMessage

실행 결과


공식문서 참고 자료

Optional

https://developer.apple.com/documentation/swift/optional

Sequence

https://developer.apple.com/documentation/swift/sequence

Result

https://developer.apple.com/documentation/swift/result

Publisher

https://developer.apple.com/documentation/combine/publisher


참고자료 (응용)

https://github.com/uber/RIBs/wiki

 

GitHub - uber/RIBs: Uber's cross-platform mobile architecture framework.

Uber's cross-platform mobile architecture framework. - GitHub - uber/RIBs: Uber's cross-platform mobile architecture framework.

github.com

 

'interactive service > CS' 카테고리의 다른 글

파이썬 코딩 테스트 연습  (0) 2022.08.17
자바스크립트 코딩 테스트 연습  (0) 2022.08.17