Russ
Russ

Reputation: 83

Cannot convert value of type 'KotlinBoolean' to expected argument type 'Bool'

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

Upvotes: 5

Views: 2823

Answers (3)

Phil Dukhov
Phil Dukhov

Reputation: 87804

@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:

isLiked?.boolValue

Upvotes: 5

Chris Wickens
Chris Wickens

Reputation: 490

Since this is the top search result for "convert bool to KotlinBoolean", I'll put this here for devs like me going the other way:

let selected = KotlinBoolean(bool: swiftObject.selected)

Upvotes: 8

Asperi
Asperi

Reputation: 257711

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

Upvotes: 4

Related Questions