[swift-users] Was the String contains(_:) method changed in Swift 4?

Martin R martinr448 at gmail.com
Wed Nov 8 02:47:09 CST 2017


String has also a

   func contains<T>(_ other: T) -> Bool where T : StringProtocol

method, but apparently only if Foundation is imported.


> Am 08.11.2017 um 04:03 schrieb David Keck via swift-users <swift-users at swift.org>:
> 
> I am looking at the latest version of the “App Development with Swift” iBook on page 122. There’s a code example I’ll paste below.
> 
> “Maybe you want to check if one string is somewhere within another string. You can use the contains(_:) method to return a Boolean value that indicates whether or not the substring was found.
>  
> let greeting = "Hi Rick, my name is Amy."
> if greeting.contains("my name is") {
>   print("Making an introduction")
> }”
> 
> Excerpt From: Apple Education. “App Development with Swift.” Apple Inc. - Education, 2017. iBooks. https://itunes.apple.com/us/book/app-development-with-swift/id1219117996?mt=11
> 
> When I try to run this code, I get the following error:
> 
> error: cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
> if greeting.contains("my name is") {
>                                 ^~~~~~~~~~~~
> 
> From what I can tell, the Swift 4 Strings are once again collections, so the contains method will only work with characters.
> 
> What can I use to find a substring inside a String in Swift 4?
> 
> Thank you!
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users



More information about the swift-users mailing list