如何在<String>不使用 debugDescription 的情况下获取 T已发布 swift 的值?



我有下面的代码,它在操场上运行。我正试图允许对类中的@Published变量进行下标访问。到目前为止,我找到的唯一方法是在以下的实现中检索String值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)")

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
}

相关内容

最新更新