我有以下代碼,它在操場上運行。我試圖允許下標訪問類中的 @Published 變數。到目前為止,我發現在 getStringValue 的以下實作中檢索字串值的唯一方法是使用 debugDescription 并將其拉出——我查看了 Published 的介面,但找不到任何方法檢索像 getStringValue 這樣的函式中的值
任何指標將不勝感激:)
編輯以包含一個示例,說明它如何與未發布的變數一起使用。
干杯
import Foundation
import Combine
protocol PropertyReflectable {}
extension PropertyReflectable {
subscript(key: String) -> Any? {
return Mirror(reflecting: self).children.first { $0.label == key }?.value
}
}
class Foo : PropertyReflectable {
@Published var str: String = "bar"
var str2: String = "bar2"
}
// it seems like there should be a way to get the Published value without using debugDescription
func getStringValue(_ obj: Combine.Published<String>?) -> String? {
if obj == nil { return nil }
let components = obj.debugDescription.components(separatedBy: "\"")
return components[1]
}
let f = Foo()
let str = getStringValue(f["_str"] as? Published<String>)
print("got str: \(str!)")
// str == "bar" as expected
let str2 = f["str2"]!
print("got non-published string easily: \(str2)")
uj5u.com熱心網友回復:
Published
似乎沉浸在一些編譯器魔法中,因為缺乏更好的措辭,因為它只能用作類內部的屬性包裝器。
話雖如此,這樣的事情會起作用嗎?
final class PublishedExtractor<T> {
@Published var value: T
init(_ wrapper: Published<T>) {
_value = wrapper
}
}
func extractValue<T>(_ published: Published<T>) -> T {
return PublishedExtractor(published).value
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516575.html
標籤:迅速结合属性包装器发布