Skip to content

Instantly share code, notes, and snippets.

@stinger
Created June 12, 2018 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stinger/a1a00c92f11a572fe5d88ed44740266a to your computer and use it in GitHub Desktop.
Save stinger/a1a00c92f11a572fe5d88ed44740266a to your computer and use it in GitHub Desktop.
Swift 4.2 dynamicMemberLookup example
@dynamicMemberLookup
class Person {
let name: String
let age: Int
private let details: [String: String]
init(name: String, age: Int, details: [String: String]) {
self.name = name
self.age = age
self.details = details
}
subscript(dynamicMember key: String) -> String {
switch key {
case "info":
return "\(name) is \(age) years old."
default:
return details[key] ?? ""
}
}
}
me.info // "Xxx is 32 years old."
me.title // "Author"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment