Last active
September 7, 2019 00:49
-
-
Save yutailang0119/8f3fc026b62fcc9e2853015844770972 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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