Skip to content

Instantly share code, notes, and snippets.

@p-x9
Last active November 26, 2022 20:54
Show Gist options
  • Save p-x9/513e5102a0f31a8bcff71b12ce455edc to your computer and use it in GitHub Desktop.
Save p-x9/513e5102a0f31a8bcff71b12ce455edc to your computer and use it in GitHub Desktop.
Modifierを簡単に定義する方法を考えたい
import Foundation
@dynamicMemberLookup
struct DynamicMemberWrap<T: AnyObject> {
private var value: T
init(_ value: T) {
self.value = value
}
subscript<U>(dynamicMember keyPath: ReferenceWritableKeyPath<T, U>) -> (U) -> DynamicMemberWrap<T> {
{ val in
value[keyPath: keyPath] = val
return DynamicMemberWrap(value)
}
}
subscript<U>(dynamicMember keyPath: ReferenceWritableKeyPath<T, U>) -> (U) -> T {
{ val in
value[keyPath: keyPath] = val
return value
}
}
}
postfix operator ^
postfix func ^<T: AnyObject>(lhs: T) -> DynamicMemberWrap<T> {
return DynamicMemberWrap(lhs)
}
// Example:
//
//let label: UILabel = UILabel()^
// .text("こんにちは\n88888")
// .backgroundColor(.red)
// .textColor(.green)
// .shadowColor(.yellow)
// .shadowOffset(.init(width: 3, height: 3))^
// .alpha(0.5)
// .numberOfLines(0)
// .numberOfLines(1)
// .numberOfLines(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment