Skip to content

Instantly share code, notes, and snippets.

@Adobels
Created May 30, 2023 06:44
Show Gist options
  • Save Adobels/8e90eb6a9f7e9a20413dcbb7a219531a to your computer and use it in GitHub Desktop.
Save Adobels/8e90eb6a9f7e9a20413dcbb7a219531a to your computer and use it in GitHub Desktop.
UIKit+ResultBuilder.swift
import UIKit
@resultBuilder
struct SubviewBuilder {
static func buildEither(first component: UIView) -> UIView {
print(#function + "2")
return component
}
static func buildEither(second component: UIView) -> UIView {
print(#function + "1")
return component
}
static func buildBlock(_ components: UIView...) -> UIView {
print(#function + "2" + components.map { $0.tag }.description)
let view = IfBlockView()
components.forEach { view.addSubview($0) }
return view
}
static func buildBlock(_ components: UIView...) -> [UIView] {
print(#function + "1" + components.map { $0.tag }.description)
let result = components.flatMap {
if $0 is IfBlockView {
return $0.subviews
} else {
return [$0]
}
}
return result
}
static func buildOptional(_ component: UIView?) -> UIView {
print(#function + "2" + (component?.description ?? "-") ?? "-")
return component ?? UIView()
}
static func buildIf(_ component: UIView?) -> [UIView] {
print(#function)
switch component {
case .none:
return []
case .some(let wrapped):
return [wrapped]
}
}
}
class IfBlockView: UIView { }
extension UIView {
func addSubviews(@SubviewBuilder builder: () -> [UIView]) -> UIView {
builder().forEach { addSubview($0) }
return self
}
}
extension UIView {
convenience init(tag: Int) {
self.init(frame: .zero)
self.tag = tag
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.addSubviews {
UILabel(tag: 10)
UILabel(tag: 11)
UILabel(tag: 12)
if 1 == 1 {
UILabel(tag: 13)
UILabel(tag: 14)
UILabel(tag: 16)
UIView(tag: 30).addSubviews {
UILabel(tag: 140)
UILabel(tag: 160)
}
}
else {
UILabel(tag: 15)
}
if true {
UILabel(tag: 20)
UILabel(tag: 21)
UILabel(tag: 22)
}
#if RELEASE
if true {
}
#endif
}
print(view.subviews.map { $0.tag })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment