user1904273
user1904273

Reputation: 4764

Contains where syntax different when placed in own method in Swift

I am trying to refactor some code out of one method into its own method but the compiler is complaining.

This code works fine inside a longer method

let aboutLocation = self.locationWords.contains(where: {$0.caseInsensitiveCompare((newmessage)!) == .orderedSame})

if (aboutLocation) {
    self.startLocationServices()
}

When I try to place the code in its own method as follows it gives error message: Extraneous argument label 'where' in call and suggests I delete the word.

func startLocationServicesIfLocation(newmessage:String){
    let aboutLocation = self.locationWords.contains(where: {$0.caseInsensitiveCompare((newmessage)!) == .orderedSame})

    if (aboutLocation) {
        self.startLocationServices()
    }
}

Why would it be different inside one method compared with the other

Upvotes: 0

Views: 96

Answers (1)

vadian
vadian

Reputation: 285082

The error is misleading.

In the function the parameter newmessage is non-optional so you have to remove the exclamation mark (and the enclosing parentheses – also around the if condition – anyway).

let aboutLocation = self.locationWords.contains(where: {$0.caseInsensitiveCompare(newmessage) == .orderedSame})
if aboutLocation { ...

But you can indeed omit the where parameter label using trailing closure syntax

let aboutLocation = locationWords.contains{ $0.caseInsensitiveCompare(newmessage) == .orderedSame }

Upvotes: 1

Related Questions