Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yutailang0119/8f3fc026b62fcc9e2853015844770972 to your computer and use it in GitHub Desktop.
Save yutailang0119/8f3fc026b62fcc9e2853015844770972 to your computer and use it in GitHub Desktop.
import Foundation
var value: Any = "value"
@propertyWrapper
struct Wrapper<Value> {
private let defaultValue: Value
init(defaultValue: Value) {
self.defaultValue = defaultValue
}
var wrappedValue: Value {
get {
(value as? Value) ?? defaultValue
}
set {
value = newValue
}
}
}
final class Playground {
@Wrapper(defaultValue: nil)
var explicitlyOptional: String?
@Wrapper(defaultValue: nil)
var implicitlyOptional: String
@Wrapper(defaultValue: "NonOptional")
var nonOptional: String
func printExplicitlyOptionalType() {
print(type(of: self.explicitlyOptional))
}
func printImplicitlyOptionalType() {
print(type(of: self.implicitlyOptional))
}
func printNonOptionalType() {
print(type(of: self.nonOptional))
}
}
let playground = Playground()
playground.printExplicitlyOptionalType() // Optional<String>
playground.printImplicitlyOptionalType() // Optional<String>
playground.printNonOptionalType() // String
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment