2

So in Obj-c this would be done differently, but I was wondering if anyone had any idea how to do this in swift? I feel embarrased having to ask this, but simply cannot find any documentation on it, how do I convert a float to string?

override func viewDidLoad() {
    super.viewDidLoad()

    var userScore = receivePlayerCard?.playerScore

    var convertUserScoreToString: Float

    scoreNameLabel.text = convertUserScoreToString //need to convert it to a string here
    scoreNameLabel.textColor = UIColor.whiteColor()
    // Do any additional setup after loading the view.
}
FreeNickname
  • 7,398
  • 2
  • 30
  • 60
user3746995
  • 57
  • 2
  • 6
  • possible duplicate of [Convert float value to String in Swift](http://stackoverflow.com/questions/24123312/convert-float-value-to-string-in-swift) – Cezar Jun 23 '14 at 03:48

2 Answers2

7

You'd do it like this:

scoreNameLabel.text = "\(convertUserScoreToString)"

String Interpolation

Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
  • Wouldn't you want to specify a format string, too? Floats look very weird sometimes. – Thilo Jun 23 '14 at 01:40
  • @Thilo There are ways of doing with that with NSString, but not with a Swift string as far as I know: http://stackoverflow.com/a/24052540/754604 This works for simple interpolation though – Connor Pearson Jun 23 '14 at 01:44
  • @Thilo see http://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift – Jack Jun 23 '14 at 01:56
2

We can use format strings with Swift's String type, thanks to Obj-C bridging!

So for example:

override func viewDidLoad() {
    super.viewDidLoad()

    let userScore: Double = receivePlayerCard?.playerScore

    scoreNameLabel.text = String(format: "%.2f", userScore)

    // Do any additional setup after loading the view.
}
fqdn
  • 2,823
  • 1
  • 13
  • 16