๐NonNominalTypeWrapper
๐พ ็จๅผ๏ผpaiza.io โฌ๏ธ ้่ฆ๏ผ HasMirrors
// --------------------------------
// โญ NonNominalTypeWrapper
// --------------------------------
/// non-nominal type:
/// โ - can't be extended.
/// โ - can't conform to protocols.
/// use this type to wrap non-nominal types, so they can do these things.
public struct NonNominalTypeWrapper<T> {
let subject: T // T is non-nominal (i.e. Any, Tuple)
}
/// convenience init
/// usage: `NonNominalTypeWrapper(instance)`
extension NonNominalTypeWrapper {
// โญ ๆณจๆ๏ผ้่ฃกไธ่ฝๅฏซๆ init<T>
// ไธ็ถๆๅผ้ฒใๆฐ็ๅๅฅๅๆธ `T`ใ๏ผๆฏ็๏ผ่ทใ่็ๅๅฅๅๆธ `T`ใ
// ๅๅญไธๆจกไธๆจฃ๏ผ๏ผ็ถๅพ็ข็ใไปคไบบๅป็ผ็้ฏ่ชค่จๆฏใ๏ผ
// ใโ cannot assign value of type 'T' to type 'T'ใ
public init(_ subject: T){
self.subject = subject
}
}
/// โญ custom extension (Loggable conformance)
extension NonNominalTypeWrapper: Loggable {
@discardableResult
public func log() -> Self {
print(String(describing: self.subject))
return self
}
@discardableResult
public func reflect() -> Self {
print(String(reflecting: self.subject))
return self
}
// mirror (object tree)
@discardableResult
public func mirror() -> Self {
mirrorChildren(of: self.subject)
}
}
// ----------------------------
// โญ non-nominal types
// ----------------------------
// tuple
NonNominalTypeWrapper((true, 32))
.log() // (true, 32)
.reflect() // (true, 32)
.mirror()
// ------------------------------
// children of (true, 32)
// ------------------------------
// โข .0: true (Bool)
// โข .1: 32 (Int)
// ------------------------------
NonNominalTypeWrapper((first: "Taylor", last: "Swift"))
.log() // (first: "Taylor", last: "Swift")
.reflect() // (first: "Taylor", last: "Swift")
.mirror()
// ----------------------------------------------------
// children of (first: "Taylor", last: "Swift")
// ----------------------------------------------------
// โข first: Taylor (String)
// โข last: Swift (String)
// ----------------------------------------------------
NonNominalTypeWrapper((name: "Tony", "Stark"))
.log() // (name: "Tony", "Stark")
.reflect() // (name: "Tony", "Stark")
.mirror()
// -------------------------------------------
// children of (name: "Tony", "Stark")
// -------------------------------------------
// โข name: Tony (String)
// โข .1: Stark (String)
// -------------------------------------------
// closure
let closure = { (a: Int) -> Int in a * 2 }
NonNominalTypeWrapper(closure)
.log() // (Function)
.reflect() // (Function)
.mirror() // no children
HasMirrors - required protocol.
Last updated