-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweak_box.swift
53 lines (43 loc) · 1.31 KB
/
weak_box.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// Box.swift
// SwiftExtensions
//
// Created by Tatsuya Tanaka on 2019/12/08.
// Copyright © 2019 tattn. All rights reserved.
//
import Foundation
@propertyWrapper @dynamicMemberLookup
public class Ref<Wrapped> {
public var wrappedValue: Wrapped
public init(wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
public init(_ wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
public subscript<T>(dynamicMember keyPath: KeyPath<Wrapped, T>) -> T {
wrappedValue[keyPath: keyPath]
}
}
@dynamicMemberLookup
public class Weak<Wrapped: AnyObject> {
public weak var wrappedValue: Wrapped?
public init(wrappedValue: Wrapped?) {
self.wrappedValue = wrappedValue
}
public init(_ wrappedValue: Wrapped?) {
self.wrappedValue = wrappedValue
}
public subscript<T>(dynamicMember keyPath: ReferenceWritableKeyPath<Wrapped, T>) -> T? {
get { wrappedValue?[keyPath: keyPath] }
set {
if let newValue = newValue {
wrappedValue?[keyPath: keyPath] = newValue
}
}
}
public subscript<T>(dynamicMember keyPath: ReferenceWritableKeyPath<Wrapped, T?>) -> T? {
get { wrappedValue?[keyPath: keyPath] }
set { wrappedValue?[keyPath: keyPath] = newValue }
}
}