Search code examples
iosstringswiftdoubledowncast

Swift Downcasting AnyObject (Float) to String


I'm currently working with some dummy data, before I start using an actual API. But I'm having some problems filling one of my labels, with a number, that needs a symbol added to it.

Rather than explaining everything, here's a screencap of an early design below: enter image description here

I have a double, that will be provided as a double in a dictionary, that contains diferent types of values. (String : AnyObject)

Here's my dummy array of dictionaries:

var objects = NSMutableArray()
var dataArray = [   ["stockName":"CTC Media Inc.","action":"sell","stockPrice":12.44],
                    ["stockName":"Transglobal Energy","action":"buy","stockPrice":39.40],
                    ["stockName":"NU Skin Enterprises","action":"buy","stockPrice":4.18]
                ]

Now here's my attempt to make this into a string.

First I found another similar problem but with an Int. And their solution works for integers:

var StockValueString = String(object["stockPrice"] as Int)

however, when I try to use a Float or a Double. I get an error:

var StockValueString = String(object["stockPrice"] as Double)

Error:

Type 'String' does not conform to protocol 'NSCopying'

I tried adding a "?" after the "as", but it didn't fix it.

I need to convert it to a string, so I can add the Dollar sign. And display it in the label.

Any help would be greatly appreciated!


Solution

  • You can simply use variable interpolation in a string with Swift. First get your price and then just use it in a string with the $ prepended-

    var stockValueString=""
    if let price=dataArray[0]["stockPrice"] {
        stockValueString="$\(price)"
    }
    

    Also, note by (strong) convention variable should start with a lower-case letter. Class names start with a capital.