Home > other >  Cannot convert value of type 'KotlinBoolean' to expected argument type 'Bool'
Cannot convert value of type 'KotlinBoolean' to expected argument type 'Bool'

Time:10-27

Im making a Multiplatform KMM project, and im having trouble assigning dynamic value to the button property.

Basically I have this like button which changes its states depending on selected property:

struct SelectFavouriteButton: View {
    
    @State var selected = false    
    let action: (Bool) -> Void
      
    var body: some View {
        Button(action: {
            selected.toggle()
            self.action(selected)
        }) {
            Image(systemName: selected ? "heart.fill" : "heart" )
                .foregroundColor(.accentRed)
        }
    }
}

The view model from Kotlin part:

@Serializable
data class Data(
...
    var isLiked: Boolean? = null,
    var isSaved: Boolean? = null,
...
}

And the view where this button is called:

struct CellView: View {
    
    @State var advert: Data?

    var body: some View {

     // Cannot convert value of type 'KotlinBoolean' to expected argument type 'Bool'
     // Insert ' as! Bool'
     SelectFavouriteButton(selected: advert?.isLiked ?? false){ isPressed in   // Error is here
         self.action(isPressed, advert?.id ?? "" , false)   
     }

   }
}

Should I use mapping? If yes how do I do it in the current context? Pls help

CodePudding user response:

Kotlin primitives transferred to NSNumber in swift, so try the following (not tested - idea only)

 let linked = advert.isLiked as? NSNumber // or NSNumber?
 SelectFavouriteButton(selected: linked?.boolValue ?? false){ isPressed in
     self.action(isPressed, advert?.id ?? "" , false)   
 }

CodePudding user response:

@Asperi's suggestion should work, but the reasoning is not quite right.

Kotlin primitives are perfectly transferable to ObjC primitives, and those are easily accessible from Swift.

But ObjC primitives such as NSInteger or BOOL do not support optionals. So when you declare an optional primitive in Kotlin, it is converted to `KotlinNumber', as an object is needed to store an optional value in ObjC.

KotlinNumber is a subclass of NSNumber, so you can use it that way:

advert?.isLiked?.boolValue
  • Related