1

As I am just starting my adventure with programming in general and with Swift in particular I am unable to solve my problem with filtering an array.

While working with my book, I got to a chapter where arrays are explained and I had no problem with working with arrays untill now. Here is a code from my student's book :

var city = ["Boston", "London", "Chicago", "Atlanta"]
let filtered = city.filter{$0.range(of:"o") != nil}

This is supposed to filter the cities with the letter "o" in it but when compiled this message is being shown :

error: value of type 'String' has no member 'range

So does it mean that I can't use .range for string values? What chould the code look like then? I am using ubuntu as my OS.

Thanks in advance.

8
  • 4
    Did you import Foundation? Commented Apr 6, 2017 at 14:29
  • No, I am working with a book and as the book didn't tell me to do it I didn't To this point of the book I didnt have to import anything or there wasn't even a word written in it about importing anything. Commented Apr 6, 2017 at 14:32
  • Check this stackoverflow.com/a/41517343/7250862 .And you can use contains to check whether a string has a character let filtered = city.filter{$0.contains("o")} Commented Apr 6, 2017 at 14:36
  • Without importing Foundation: let filtered = city.filter{$0.characters.contains("o")} Commented Apr 6, 2017 at 14:41
  • @vacawama Yes, this works too. Thank you. Commented Apr 6, 2017 at 14:48

1 Answer 1

2

You are getting this error because unfortunately range is not available in Linux. If you had access to a machine with macOS this would work.

As @Hamish said, I was completely wrong, you have to import Foundation in order to use range or contains on String (even though you can call contains on string.characters without importing Foundation).

Add this line to the beginning of your code:

import Foundation
Sign up to request clarification or add additional context in comments.

4 Comments

I tried the OP's code on that sandbox too and got the same error, even though it worked fine on a playground in Xcode 8.3 / Swift 3.1
The book I am working with is dedicated for programming in linux in particular so could it be it is the authors mistake?
No, @Bodeue, @Hamish was right, you have to import Foundation, check my edit.
Thank you, it solved it. Now I will wonder why did I have to import anything and what this "Foundation" thing is. I hope it will be explained in the book later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.