如何对Swift中的字典对象分配的变量执行操作?

时间:2014-06-08 15:30:48

标签: swift

我正在尝试区分两个值:

var lastValue = eminiSP["data"]![0]![4]
var previousDayValue = eminiSP["data"]![1]![4]
var netChange = lastValue - previousDayValue  //throws error

我假设它与类型有关,但是如何转换lastValue和previousDayValue以便我可以执行操作? previousDayValue.doubleValueDouble(previousDayValue)也会抛出错误。也许我从一个完全不正确的角度思考它,因为我正在处理字典?

eminiSP [“data”]![0]和eminiSP [“data”]![1]分别如下所示:

(
    "2014-06-05",
    "1918.25",
    "1933.25",
    "1913.5",
    "1931.25",
    "12.75",
    1931,
    30181,
    99537
)
(
    "2014-06-04",
    "1915.75",
    "1919.5",
    "1908.75",
    "1918.25",
    "3.5",
    "1918.25",
    19024,
    86475
)

以下是完整代码:

// Playground - noun: a place where people can play

import Cocoa

func getJSON(urlToRequest: String) -> NSData{
    return NSData(contentsOfURL: NSURL(string: urlToRequest))
}

func parseJSON(inputData: NSData) -> NSDictionary{
    var error: NSError?
    var dataDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData,     options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
return dataDictionary
}

var parsedJSON =   parseJSON(getJSON("http://www.quandl.com/api/v1/datasets/CME/ESU2014.json?auth_token=REMOVED_AUTH_TOKEN"))

let eminiSP = parsedJSON

var lastValue = eminiSP["data"]![0]![4]
var previousDayValue = eminiSP["data"]![1]![4]
var netChange = lastValue - previousDayValue  //throws error

println(lastValue)
println(previousDayValue)
println(netChange)

1 个答案:

答案 0 :(得分:1)

您可以使用:

let a = "123.456"
let b = (a as NSString).doubleValue