Bodeue
Bodeue

Reputation: 47

Filtering 'string' values of elements in array in Swift

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.

Upvotes: 1

Views: 2777

Answers (1)

Edgar
Edgar

Reputation: 2540

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

Upvotes: 2

Related Questions