I was able to retrieve a binding Swift Array from a Kotlin MutableList source,
but I can’t find the way to retrieve a binding Swift Array from a Kotlin MutableMap of MutableLists source, given the map key.
=====
Kotlin MutableList to binding Swift Array
Kotlin MutableList definition:
var path : MutableList<ScreenIdentifier> = mutableListOf()
retrieving Binding Swift Array => SUCCESSFUL!
extension Binding where Value == NSMutableArray {
public func cast() -> Binding<[ScreenIdentifier]> {
return Binding<[ScreenIdentifier]>(
get:{ self.wrappedValue as NSArray as! [ScreenIdentifier] },
set: { self.wrappedValue = NSMutableArray(array: $0) }
)
}
}
===
NavigationStack(path: $path.cast()) {
...
}
===
=====
Kotlin MutableMap of MutableList to binding Swift Array
Kotlin MutableMap of MutableLists definition:
var paths : MutableMap<String, MutableList<ScreenIdentifier>> = mutableMapOf()
retrieving Binding Swift Array => NOT WORKING
extension Binding where Value == NSMutableDictionary {
public func getPath(level1URI: String) -> Binding<[ScreenIdentifier]> {
return Binding<[ScreenIdentifier]>(
get:{
let dict = self.wrappedValue as NSDictionary as! [String:[ScreenIdentifier]]
return dict[level1URI] as! NSMutableArray as NSArray as! [ScreenIdentifier]
},
set: {
var modifiedDict = self.wrappedValue as! [NSString:NSMutableArray]
modifiedDict[level1URI as NSString] = NSMutableArray(array: $0)
self.wrappedValue = NSMutableDictionary(dictionary: modifiedDict as! KotlinMutableDictionary<NSString,NSMutableArray>)
}
)
}
}
===
NavigationStack(path: $paths.getPath(level1URI: myString)) {
...
}
===
this is the error given by XCode:
Referencing instance method 'getPath(level1URI:)' on 'Binding' requires the types 'KotlinMutableDictionary<NSString, NSMutableArray>' and 'NSMutableDictionary' be equivalent
I found it!!!
On the Kotlin documentation, it's explained that Kotlin's
MutableMapcannot cast directly toNSMutableDictionary, unlikeMutableListwhich can instead cast directly toNSMutableArray.So, the solution is to ignore
NSMutableDictionaryand to deal directly withKotlinMutableDictionary.Here is the correct extension code: