基于结构泛型类型的调用权函数实现



具有泛型类型的struct可以使用where子句进行扩展,以便在泛型类型符合特定协议时添加新功能。我试图实现的目标略有不同。我有一个具有泛型类型的struct,如果泛型类型符合Codable,我想更改它的实现。不幸的是,如果我从结构本身中调用函数,那么扩展中的overriden函数永远不会被触发。但如果我从外部调用它,就会触发正确的实现。

struct GenericStruct<T> {
private var _value: T
var value: T {
get {
printText()
return _value
}
set {
_value = newValue
}
}
init(value: T) {
self._value = value
}
func printText() {
print("General Print Function")
}
}
extension GenericStruct where T: Codable {
func printText() {
print("Codable Function")
}
}
let test = GenericStruct(value: 1)
print(test.value) // print General Print Function
test.printText() // print Codable Function

有没有一种方法可以从结构中调用基于T类型的printText()函数?

编辑:

我试图从propertyWrapper结构内部调用正确的实现

@propertyWrapper struct Caching<Value> {
var key: String
var defaultValue: Value
var cachingType = CachingType.userDefaults
enum CachingType {
case userDefaults
case custom
}
var wrappedValue: Value {
get {
switch cachingType {
case .userDefaults:
return UserDefaults.standard.value(forKey: key) as? Value ?? defaultValue
case .custom:
return retrieveValueFromCachingLayer()
}
}
set {
switch cachingType {
case .userDefaults:
UserDefaults.standard.set(newValue, forKey: key)
case .custom:
store(value: newValue)
}
}
}
func store(value: Value) {
assertionFailure("This value type is not supported by the property wrapper")
}
func retrieveValueFromCachingLayer() -> Value {
assertionFailure("This value type is not supported by the property wrapper")
return defaultValue
}
}
extension Caching where Value: Codable {
func retrieveValueFromCachingLayer() -> Value {
print("retrieve value from a custom caching layer")
return defaultValue
}
func store(value: Value) {
print("store value in a custom caching layer")
}
}

并非没有重新定义。我认为,最干净的方法是在扩展中分离实现,但也可以保留现有的内容,只添加专用的value

struct GenericStruct<T> {
private var _value: T
init(value: T) {
_value = value
}
}
extension GenericStruct {
var value: T {
get {
printText()
return _value
}
set {
_value = newValue
}
}
func printText() {
print("General Print Function")
}
}
extension GenericStruct where T: Codable {
var value: T {
get {
printText()
return _value
}
set {
_value = newValue
}
}
func printText() {
print("Codable Function")
}
}

在了解到您正在尝试使用属性包装器后进行编辑:

@propertyWrapper struct UserDefault<Value> {
var key: String
var defaultValue: Value
var wrappedValue: Value {
get {
UserDefaults.standard.value(forKey: key) as? Value ?? defaultValue
}
set {
UserDefaults.standard.set(newValue, forKey: key)
}
}
}
@propertyWrapper struct Caching<Value: Codable> {
var defaultValue: Value
var wrappedValue: Value {
get {
print("retrieve value from a custom caching layer")
return defaultValue
}
set {
print("store value in a custom caching layer")
}
}
}

最新更新