Home > Software design >  How do I get the value of a Published<String> in swift without using debugDescription?
How do I get the value of a Published<String> in swift without using debugDescription?

Time:10-18

I've got the following code, that runs in a playground. I'm attempting to allow subscript access to @Published variables in a class. The only way I've found so far to retrieve the String value in the below implementation of getStringValue is to use the debugDescription, and pull it out -- I've looked at the interface for Published, but can't find any way to retrieve the value in a func like getStringValue

Any pointers would be greatly appreciated :)

Edited to include an example of how it works with a non-published variable.

Cheers

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)")

CodePudding user response:

Published seems to be steeped in some compiler magic, for lack of a better wording, since it can only be used as a property wrapper inside classes.

That being said, would something like this work?

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
}
  • Related