Swift

Swift then 사용

kkimin 2021. 5. 10. 10:06

Then 이란?

 

전수열개발자님께서 만든 then은 ReadMe에 있는 예제만 보고도 우리가 흔히 쓰던 무엇을 then으로 만들었는지 알 수 있습니다. (클로저를 통해 인스턴스를 생성했을때 원하는 처리를 할 수 있음 ) 

장점 : 코드 깔끔

단점 : ?

https://github.com/devxoul/Then

 

devxoul/Then

✨ Super sweet syntactic sugar for Swift initializers - devxoul/Then

github.com

 

적용방법

Podfile 에 

pod 'Then' 

을 적고 pod install 을 터미널 명령어에 쳐주면 설치 완료!

(Podfile이 없다면 pod init ~)

 

사용

You can use then() to all of NSObject subclasses.

라고 나와있네요. 

 

ReadMe에 나와있는 예시로 공부해봅시다.

let label: UILabel = {
  let label = UILabel()
  label.textAlignment = .center
  label.textColor = .black
  label.text = "Hello, World!"
  return label
}() // 이렇게 사용하던것을

let label = UILabel().then {
  $0.textAlignment = .center
  $0.textColor = .black
  $0.text = "Hello, World!"
} // 이렇게 바꿀 수 있습니다.

 그 외에도 내가 선언한 타입이 있다...! 하면은

class MyType: UILabel {
}

extension MyType: Then {}

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

 

그리고 with과 do의 개념이 있었습니다.

아직 with은 잘 모르겟고... 내용은 아래와 같습니다.

// Use with() when copying the value types.

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

// Use do() to do something with less typing.

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

 

내 프로젝트에 적용한 후 후기

아이들이 깔끔하게 묶여서 훨씬 가독성이 좋은것 같다. 

그런데 위의 것과 비슷하게~ 코드를 작성할 수 있는 부분을 알게 되었는데 바로 다음과 같이 작성하는 방법이다.

let view = UILabel().with
    .backgroundColor(.red)
    .numberOfLines(2)
    .font(.systemFont(ofSize: 12, weight: .bold))
    .build()

위와 같은 builder pattern은 https://kkimin.tistory.com/83 이 글을 참고하면 좋을 것 같다...!

728x90