swift

Constant `isSelected` is inferred to have type (), which may be unexpected when using the toggle() instance method on a Bool


I've got an associated value in an enum which I want to toggle the boolean value of (the associated value itself is a Bool type). I am using the toggle() instance method to toggle the value of the boolean from true to false or false to true. According to the swift documentation, the toggle() method changes the value of the boolean from true to false or false to true and does not return any value.

In my code, I am declaring an isSelected property and toggling its value, like so:

enum Item: Equatable, Hashable {
     case main(emotion: String, icon: String, red: CGFloat, green: CGFloat, blue: CGFloat, isSelected: Bool, uuid: UUID)
} 

switch identifierToChange {
     case .main(let emotion, let iconName, let red, let green, let blue, var isSelected, let uuid): ()
            let isSelected = isSelected.toggle() // warning appear here
            identifierToChange = .main(emotion: emotion, icon: iconName, red: red, green: green, blue: blue, isSelected: isSelected, uuid: uuid) // error appears here

}

But I get a warning which says: "Constant 'isSelected' inferred to have type '()', which may be unexpected", and an error: "Cannot convert value of type '()' to expected argument type 'Bool'".

How can I fix this?


Solution

  • Because it's a function that implicitly returns a Void

    @inlinable public mutating func toggle()
    

    And the toggling its value is an underlying logic, if this is what you're thinking, the function should be:

    @inlinable public mutating func toggle() -> Bool
    

    So this is enough:

    switch identifierToChange {
      case .main(..., var isSelected, ...):
        isSelected.toggle()
        identifierToChange = .main(..., isSelected: isSelected, ..)
    }