Coffee inTime
Coffee inTime

Reputation: 230

Why does string.contains ("text") not work with strings in swift 5?

let string = "hello Swift"
if string.contains("Swift") {
    print("exists")
}

Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')

Why is version 5 such an error and what should I do?

Upvotes: 1

Views: 635

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119310

When you use contains() and pass it a String, Swift tries to use an overload of the function that takes some kind of string like contains(_ other: StringProtocol) function that is not part of the pure Swift String. Instead it finds contains(_ element: Character) and it can't accept String as an argument and only accepts 'String.Element' (aka 'Character'). Referring to contains

The function you are looking for is defined in a protocol that String conforms to it, called StringProtocol that lives inside the Foundation.

So if you need it, make sure you import Foundation or a higher level framework like UIKit.

Upvotes: 3

Related Questions