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

David Keck davidskeck at fastmail.com
Tue Nov 7 21:03:31 CST 2017


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 <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!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171107/f2301af0/attachment.html>


More information about the swift-users mailing list