Reputation: 1678
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)
}
}
Upvotes: 0
Views: 4863
Reputation: 47876
Two things:
The return type of array(forKey:)
is [Any]?
, its Element type Any
is useless for almost all operations. You should better cast it to an appropriate type when you know the actual Element type.
The method name contains
has many overloads, you may want to call contains(_:)
, not contains(where:)
.
Try this:
if let connectedPeripherals = UserDefaults.standard.array(forKey: "ConnectedPeripherals") as? [String] {
if connectedPeripherals.contains(peripheral.identifier.uuidString) {
manager.connect(peripheral, options: nil)
}
}
Or, as suggested by Leo Dabus, this may be better:
if let connectedPeripherals = UserDefaults.standard.stringArray(forKey: "ConnectedPeripherals") {
if connectedPeripherals.contains(peripheral.identifier.uuidString) {
manager.connect(peripheral, options: nil)
}
}
Upvotes: 2
Reputation: 733
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)
}
}
Upvotes: 3