1

I recently upgraded my project to Swift 3 and have been having some trouble with a string interpolation error.

My code:

let coordString = "\(locationCoordinate.latitude) \(locationCoordinate.longitude)".stringByReplacingOccurrencesOfString(".", withString: ",")

The error says:

Static member 'init(stringInterpolationSegment:)' cannot be used on instance of type 'String'

How can I solve the error?

2
  • Basically use (NS)Numberformatter to display the decimal separator of a number according to the current locale. Further stringByReplacingOccurrencesOfString has been renamed in Swift 3. Commented Nov 12, 2016 at 18:43
  • I am new to swift could you please write that in code. Thanks Commented Nov 12, 2016 at 18:47

2 Answers 2

1

Replacing the decimal separator using replacingOccurrences(of... is not good programming habit.

You should use always NumberFormatter to be able to consider the current locale of the user.

This is an example. The decimal separator is displayed depending on the current locale. If you really want explicit a comma uncomment the locale line and set the locale identifier to your preferred one.

let latitude = 52.5
let longitude = 13.0
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
// formatter.locale = Locale(identifier: "DE_de")

let coordString = formatter.string(from: NSNumber(value:latitude))! + " " + formatter.string(from: NSNumber(value:longitude))!
Sign up to request clarification or add additional context in comments.

2 Comments

can you please explain me why this is better practice
For some languages (locales), "." should be used in decimal format (e.g. US English), but in others, "," should be used (e.g. many European languages). So just replacing "." with "," isn't probably a good idea because it doesn't take into account localization. It's better to let the formatter decide (based on the locale you set) whether to use "." or "," ...I think that's what @vadian is getting at.
0

The method has been renamed in Swift 3:

let coordString = "\(locationCoordinate.latitude) \(locationCoordinate.longitude)".replacingOccurrences(of: ".", with: ",")    

Comments

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.