Search code examples
arraysswiftstringclosures

Cannot convert value of type 'String' to expected argument type '(Any) throws -> Bool'


I am struggling with the syntax for checking an array to see if it contains a string. I am checking a string array using contains function. But get an error noted, and I can't work out the syntax for the closure. Can anyone help?

var connectedPeripherals = [String]()

if let connectedPeripherals = UserDefaults.standard.array(forKey: "ConnectedPeripherals") {
    if connectedPeripherals.contains(where: (peripheral.identifier.uuidString)) {
     // Gives error: "Cannot convert value of type 'String' to expected argument type '(Any) throws -> Bool'"
     manager.connect(peripheral, options: nil)
    }
}

Solution

  • The function contains(where:) expects a closure as parameter, you are passing a String.

    So to fix your code it should be:

    var connectedPeripherals = [String]()
    
    if let connectedPeripherals = UserDefaults.standard.array(forKey: "ConnectedPeripherals") as? String {
        if connectedPeripherals.contains(where: { $0 == peripheral.identifier.uuidString }) {
            manager.connect(peripheral, options: nil)
        }
    }