Hi all, I have a question related to generics in i...
# multiplatform
t
Hi all, I have a question related to generics in iOS. Following the solution from @Daniele B to make Swift consume StateFlow: https://kotlinlang.slack.com/archives/C3PQML5NU/p1600185089399100 I made a SwiftFlow
Copy code
class SwiftFlow<out T: Any>(private val flow: StateFlow<T>) {
    fun onChange(
        stateProvider: (T) -> Unit
    ) {
        flow.onEach {
            stateProvider.invoke(it)
        }.launchIn(CoroutineScope(Dispatchers.Main))
    }
}
However, in swift code, I cannot use generics <String> and it shows
requirement specified as 'T' : 'AnyObject' [with T = String]
error
Copy code
class AppViewModel: ObservableObject {
	let greetFlow = SwiftFlow<String>(flow: Greeting().greetAsFlow())
    @Published var greet: String = "Initializing"

    init() {
        greetFlow.onChange { newState in
            self.greet = newState
        }
    }
}
I need to use
AnyObject
and force-cast to
String
instead
Copy code
class AppViewModel: ObservableObject {
	let greetFlow = SwiftFlow<AnyObject>(flow: Greeting().greetAsFlow())
    @Published var greet: String = "Initializing"

    init() {
        greetFlow.onChange { newState in
            self.greet = newState as! String
        }
    }
}