在Swift中附加[(String,Double)]

时间:2017-03-27 06:34:40

标签: ios arrays swift string

我还在学习Swift,我正在学习这个我在Web上找到的Stock Service Web教程。我很难将提取的值从服务追加到我的数组中。以下是示例代码。

数组初始化

private var sampleStocks: [(String, Double)] = [("GOOG", +2.2), ("YHOO", +3.22), ("AAPL", -4.1)];

附加

let values = (notification.userInfo as! Dictionary<String,NSArray>)
    let stocksReceived:NSArray = values[constantNotifUpdate]!;
    sampleStocks.removeAll();
    for quote in stocksReceived {
        let quoteDict:NSDictionary = quote as! NSDictionary;
        var changeInPercentString = quoteDict["ChangeinPercent"] as! String;
        let changeInPercentStringClean: String = changeInPercentString.substring(to: changeInPercentString.index(before: changeInPercentString.endIndex));
        var me: [(String,Double)] = [(quoteDict["symbol"] as! String, Double(changeInPercentStringClean))];
        sampleStocks.append(me);


    }

我总是遇到“无法将类型[(String,Double)]转换为预期的参数类型(String,Double)”的错误。

请你帮助我并给我一个短暂的经历?

2 个答案:

答案 0 :(得分:3)

var me: [(String,Double)]是一个数组。你需要的是一个元组。像这样声明me变量:

var me: (String,Double) = (quoteDict["symbol"] as! String, Double(changeInPercentStringClean)!);

答案 1 :(得分:0)

您可以在swift 3.0.2中使用:

sampleStocks.append(contentsOf: me)

var me: (String,Double) = (quoteDict["symbol"] as! String, Double(changeInPercentStringClean))
sampleStocks.append(me)