Skip to content

Instantly share code, notes, and snippets.

@takasek
Created March 21, 2019 08:34
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 takasek/6d208a6c075860205c1110d7662bc156 to your computer and use it in GitHub Desktop.
Save takasek/6d208a6c075860205c1110d7662bc156 to your computer and use it in GitHub Desktop.
`KeyPath` for immutable property works differently between Swift4.2 / 5 #CodePiece #tryswiftconf
func replace<T>(_ root: inout T, keyPath: KeyPath<T, String>) {
if let k = keyPath as? WritableKeyPath<T, String> {
print("writable:", keyPath)
root[keyPath: k] += " ๐Ÿ–"
} else {
print("not writable:", keyPath)
}
}
struct S {
let a = "let"
private(set) var b = "private(set) var"
var c = "var"
}
var s = S()
replace(&s, keyPath: \S.a) //
replace(&s, keyPath: \S.b)
replace(&s, keyPath: \S.c)
dump(s)
/* @ Swift 4.2 (Xcode 10.1)
writable: Swift.WritableKeyPath<__lldb_expr_2.S, Swift.String>
writable: Swift.WritableKeyPath<__lldb_expr_2.S, Swift.String>
writable: Swift.WritableKeyPath<__lldb_expr_2.S, Swift.String>
โ–ฟ __lldb_expr_2.S
- a: "let ๐Ÿ–"
- b: "private(set) var ๐Ÿ–"
- c: "var ๐Ÿ–"
*/
/* @ Swift 5 (Xcode 10.2 beta)
not writable: Swift.KeyPath<__lldb_expr_14.S, Swift.String>
writable: Swift.WritableKeyPath<__lldb_expr_14.S, Swift.String>
writable: Swift.WritableKeyPath<__lldb_expr_14.S, Swift.String>
โ–ฟ __lldb_expr_14.S
- a: "let"
- b: "private(set) var ๐Ÿ–"
- c: "var ๐Ÿ–"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment