0

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!

MLyck
  • 4,959
  • 13
  • 43
  • 74

2 Answers2

1

How about:

let stockPriceKey = "stockPrice"
var StockValueString = "$\(object[stockPriceKey]!)"
Paulw11
  • 108,386
  • 14
  • 159
  • 186
Melodius
  • 2,505
  • 3
  • 22
  • 37
  • You need the ! to prevent getting "optional" in your string and you can just include the $ sign in the literal – Paulw11 Mar 12 '15 at 06:09
1

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.

Paulw11
  • 108,386
  • 14
  • 159
  • 186