![](/img/trans.png)
[英]How to execute different implementation of a method of a generic struct based on the generic type?
[英]Invoking Right Function Implementation Based on Struct Generic Type
具有泛型類型的struct
可以使用where
子句進行擴展,以where
泛型類型符合特定協議時添加新功能。 我試圖完成的事情略有不同。 我有一個具有泛型類型的struct
和一個函數,如果泛型類型符合Codable
,我想更改其實現。 不幸的是,如果我從結構本身內部調用函數,則擴展中的覆蓋函數永遠不會被觸發。 但是如果我從外部調用它,就會觸發正確的實現。
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")
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.