Kitson88 Kitson88 - 1 month ago 27
Swift Question

stringByReplacingOccurencesOfString() for Swift 3.0

I'm having a problem when using

stringByReplacingOccurencesOfString()
into the latest version of Xcode 8.2 Beta. When using the function, Xcode is showing that the value type of string has no member.

var clockworkSmsUrl = "https://api.clockworksms.com/http/send.aspx?"
+ "key=123456789abcd"
+ "to="
+ usersNumber!
+ "&content="
+ usersTextMessage!

clockworkSmsUrl.stringByReplacingOccurrencesOfString(" ", withString: "+")
var clockworkSmsURLconvert = NSURL(string: clockworkSmsUrl)


Any ideas?

Answer

You can fix your snippet using ...

clockworkSmsUrl.replacingOccurrences(of: " ", with: "+")

Swift 3 changed the way how objc APIs are imported.

Please note that there are some issues with the code you posted:

  • the result of replacingOccurrences is discarded.
  • there are more characters to be escaped.
  • URLCompontents exposes safer ways to construct URLs.