0

I'm trying to create a simple iOS app that takes user input ( a city ) and searches a website for that city, and then will display the forecasts for that city.

What I'm currently stuck on and unable to find much documentation that isn't overwhelming is how I can be sure that the user input will translate well to a URL if there are more then one words in the name of the city.

aka if a user inputs Salt Lake City into my text field, how can I write an if else statement that determines the amount of spaces, and if the amount of spaces is greater than 0 will convert those spaces to "-".

So far I've tried creating an array out of the string, but still can't figure out how I can append a - to each element in the array. I don't think it's possible.

Does anyone know how I can do what I'm trying to do? Or am I approaching it the incorrect way?

Here's a poor first attempt. I know this doesn't work, but hopefully it explains it a bit more of what I'm trying to accomplish than my text above.

var cityText = "Salt Lake City" let cityArray = cityText.componentsSeparatedByString(" ") let combineDashUrl = cityArray[0] + "-" + cityArray[1] + "-" + cityArray[2]

print(combineDashUrl)

2 Answers2

-1

Assuming there are never multiple spaces in a row you should be able to use stringByReplacingOccurrencesOfString.

let cityText = "Salt Lake City" 
let newCityText = cityText.stringByReplacingOccurrencesOfString(
  " ", 
  withString: "-")

Replacing variable numbers of spaces with a dash would be more complicated. I'd probably use regular expressions for that.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • What's with the down-vote? I tested this code in a Playground and it works. If you feel my answer is somehow deficient, please explain yourself! – Duncan C Nov 06 '15 at 01:08
-1

You can use map over the array of characters to transform spaces into hyphens.

let city = "Salt Lake City"
let hyphenatedCity = String(city.characters.map{$0 == " " ? "-" : $0})

enter image description here

Price Ringo
  • 3,424
  • 1
  • 19
  • 33