Skip to content

Instantly share code, notes, and snippets.

@yesleon
Last active October 3, 2019 16:21
Show Gist options
  • Save yesleon/494636252ffa67f7721c5b47b880549a to your computer and use it in GitHub Desktop.
Save yesleon/494636252ffa67f7721c5b47b880549a to your computer and use it in GitHub Desktop.
func makeObject() -> (getter: () -> String, setter: (String) -> Void) {
var text = "Hello "
return (
getter: { text },
setter: { text = $0 }
)
}
let object = makeObject()
print(object.getter()) // "Hello "
object.setter("world!")
print(object.getter()) // "world!"
func makeObject<T>(value: T) -> (T?) -> T {
var value = value
return {
if let newValue = $0 {
value = newValue
}
return value
}
}
let number = makeObject(value: 1234)
// 取值
print(number(nil)) // 1234
// 存值
number(4321)
// 取值
print(number(nil)) // 4321
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment