Then

2023. 1. 6. 13:10iOS

⚠️ 티스토리 관리자의 플러그인에서 Syntax Highlight를 적용하기 전 문서입니다. 



Then은 Kotlin의 범위지정함수(= apply, with, let, also, run) 역할을 하며, 특히 initializer를 더 예쁘게 사용 할 수 있도록 도와줍니다.

 

then, with, do가 있으며 예시는 아래와 같습니다.

//then

//NSObject subclasse라면 아래와 같이 사용 가능합니다.
let queue = OperationQueue().then {
  $0.maxConcurrentOperationCount = 1
}

//CustomClass라면, 아래와 같이 extension하여 사용합니다.
extension MyType: Then {}

let instance = MyType().then {
  $0.really = "awesome!"
}


//with
let newFrame = oldFrame.with {
  $0.size.width = 200
  $0.size.height = 100
}
newFrame.width // 200
newFrame.height // 100


//do
UserDefaults.standard.do {
  $0.set("devxoul", forKey: "username")
  $0.set("devxoul@gmail.com", forKey: "email")
  $0.synchronize()
}

 

 

구현 코드는 아래와 같습니다.

import Foundation
#if !os(Linux)
  import CoreGraphics
#endif
#if os(iOS) || os(tvOS)
  import UIKit.UIGeometry
#endif

public protocol Then {}     //Custom Class에서도 사용을 위함

extension Then where Self: Any { //모든 인스턴스, AnyObject(=모든 인스턴스가 아닌 class type의 인스턴스만 캐스팅할 수 있음)는 
                                 //아래에 있으니 여기서는 구조체일 때 사용한다.

  @inlinable
  public func with(_ block: (inout Self) throws -> Void) rethrows -> Self { //inout: 파라미터를 수정할 수 있도록, pass to reference
    var copy = self   
    try block(&copy)
    return copy
  }

  @inlinable
  public func `do`(_ block: (Self) throws -> Void) rethrows {
    try block(self)
  }

}

extension Then where Self: AnyObject { // AnyObject = 모든 클래스

  @inlinable  //컴파일러 성능향상 ➡️ 함수를 스택에 쌓지않고, 구현 코드를 직접 복사하여 사용
  public func then(_ block: (Self) throws -> Void) rethrows -> Self {
    try block(self)
    return self
  }
  //throw, throws, rethrows
  //throw ➡️ do, try, catch를 통해 잡힌 에러를 던지는 명령어 
  //throws ➡️ 함수 종료 전, 에러가 나오면 에러객체를 던질 수 있음을 표기
  //rethrows ➡️ throws인 함수를 매개변수로 받은 함수는 에러를 다시 던질 수 있음
}

extension NSObject: Then {}

#if !os(Linux)
  extension CGPoint: Then {}
  extension CGRect: Then {}
  extension CGSize: Then {}
  extension CGVector: Then {}
#endif

extension Array: Then {}
extension Dictionary: Then {}
extension Set: Then {}
extension JSONDecoder: Then {}
extension JSONEncoder: Then {}

#if os(iOS) || os(tvOS)
  extension UIEdgeInsets: Then {}
  extension UIOffset: Then {}
  extension UIRectEdge: Then {}
#endif

 

'iOS' 카테고리의 다른 글

ㅜㄷㅌㅅ  (0) 2023.01.22
https://velog.io/@eddy_song/stack-view  (0) 2023.01.07
required init?(coder: NSCoder), init 마지막  (0) 2023.01.03
UIView.init()를 알아보자.  (0) 2023.01.02
1월 1일, convenience init은 왜 무한루프일까?  (0) 2023.01.01