通常,我们需要复制一个对象,更改其某些属性,但其余部分保持不变。此任务有一个功能copy()
。
这是该方法的说明的摘录copy()
从科特林文档。在我们的本机Swift语言中,这意味着类似以下内容:
struct User {
let id: Int
let name: String
let age: Int
}
let steve = User(id: 1, name: "Steve", age: 21)
// , `name` `age`
let steveJobs = steve.changing { newUser in
newUser.name = "Steve Jobs"
newUser.age = 41
}
看起来很好吃,不是吗?
, Swift " ". .
, var
let
?
struct User {
let id: Int
var name: String
var age: Int
}
let steve = User(id: 1, name: "Steve", age: 21)
...
var steveJobs = steve
steveJobs.name = "Steve Jobs"
steveJobs.age = 41
:
- , , , - .
- "". ,
willSet
didSet
. - , .
, — , :
// , `name`
let steveJobs = User(
id: steve.id,
name: "Steve Jobs",
age: steve.age
)
, , . - , .
, , "" , .
:
- , .
-
Changeable
-, , . - , .
, , . Key-Path , Key-Path Dynamic Member Lookup Swift 5.1 .
, generic-:
@dynamicMemberLookup
struct ChangeableWrapper<Wrapped> {
private let wrapped: Wrapped
private var changes: [PartialKeyPath<Wrapped>: Any] = [:]
init(_ wrapped: Wrapped) {
self.wrapped = wrapped
}
subscript<T>(dynamicMember keyPath: KeyPath<Wrapped, T>) -> T {
get {
changes[keyPath].flatMap { $0 as? T } ?? wrapped[keyPath: keyPath]
}
set {
changes[keyPath] = newValue
}
}
}
, KeyPath
. , , . .
changes[keyPath] as? T
,T
.nil
, , . ,flatMap(:)
, ,changes
.
@dynamicMemberLookup
, , var
.
Xcode . : .
Changeable
, , Changeable
:
protocol Changeable {
init(copy: ChangeableWrapper<Self>)
}
extension Changeable {
func changing(_ change: (inout ChangeableWrapper<Self>) -> Void) -> Self {
var copy = ChangeableWrapper<Self>(self)
change(©)
return Self(copy: copy)
}
}
changing(:)
, , .
, , Changeable
:
extension User: Changeable {
init(copy: ChangeableWrapper<Self>) {
self.init(
id: copy.id,
name: copy.name,
age: copy.age
)
}
}
, , — :
let steve = User(id: 1, name: "Steve", age: 21)
let steveJobs = steve.changing { newUser in
newUser.name = "Steve Jobs"
newUser.age = 30
}
, , …
changing(:)
, , , :
struct Company {
let name: String
let country: String
}
struct User {
let id: Int
let company: Company
}
let user = User(
id: 1,
company: Company(
name: "NeXT",
country: "USA"
)
)
user
, company.name
, :
let appleUser = user.changing { newUser in
newUser.company = newUser.company.changing { newCompany in
newCompany.name = "Apple"
}
}
, .
. — ChangeableWrapper
:
subscript<T: Changeable>(
dynamicMember keyPath: KeyPath<Wrapped, T>
) -> ChangeableWrapper<T> {
get {
ChangeableWrapper<T>(self[dynamicMember: keyPath])
}
set {
self[dynamicMember: keyPath] = T(copy: newValue)
}
}
, Changeable
. Swift - . , .
, :
let appleUser = user.changing { newUser in
newUser.company.name = "Apple"
}
, .
, , , , . Swift , .
. . !