显示从Firebase中解析的JSON数据。无法摆脱可选的字符串打印

时间:2016-03-08 07:23:15

标签: json swift firebase swifty-json

我能够使用此功能正确地从firebase中提取JSON数据。

func makeLeaderboard() {
    let scoresRef = Firebase(url: "https://URL.firebaseio.com/High%20Scores")

    scoresRef.observeEventType(.Value, withBlock: { snapshot in
        var newItems = [LeaderboardItem]()

        for item in snapshot.children {
            let leaderboardItem = LeaderboardItem(snapshot: item as! FDataSnapshot)
            newItems.append(leaderboardItem)
            print(item)
        }
        self.leaderboardItems = newItems
    })
}

json数据有很多对象,如下所示:

Snap (-KCIjxAHgGrNnBbL7jsI) {
    ".priority" = "-11";
    Date = "1457398993.668789";
    Name = brendan;
    Score = 11;
    UUID = "BD561F1C-72A8-4A01-A71A-850682E49D61";
}
Snap (-KC3MktapH6Mebw2sAUe) {
    ".priority" = "-10";
    Date = "1457140993.692581";
    Name = brendan;
    Score = 10;
    UUID = "BD561F1C-72A8-4A01-A71A-850682E49D61";
}  etc etc etc

我正在从这些快照创建leaderboardItem对象。这是基本结构:

import Foundation
import Firebase

struct LeaderboardItem {

let key: String!
var score: String!
let name: String!
let ref: Firebase?


// Initialize from arbitrary data
init(name: String, score: String, completed: Bool, key: String = "") {
    self.key = key
    self.name = name
    self.score = score

    self.ref = nil
}

init(snapshot: FDataSnapshot!) {
    key = snapshot.key!
    name = snapshot.value["Name"]! as! String!
    score = String(snapshot.value["Score"]) //String(snapshot.value["Score"]!)
    ref = snapshot.ref!
}

func toAnyObject() -> AnyObject {
    return [
        "name": name,
        "score": score,
    ]
  }
}

当我尝试显示leaderboardItem数组对象的score属性时,它显示为可选项。无论我如何强制打开属性,它仍然显示可选。

我正在使用以下代码显示标签:

func populateLeaderBoard() {

    leaderboardScore1.text = "\(leaderboardItems[0].score!) \(leaderboardItems[0].name)"
    leaderboardScore2.text = "\(leaderboardItems[1].score) \(leaderboardItems[1].name)"
    leaderboardScore3.text = "\(leaderboardItems[2].score) \(leaderboardItems[2].name)"
    leaderboardScore4.text = "\(leaderboardItems[3].score) \(leaderboardItems[3].name)"
    leaderboardScore5.text = "\(leaderboardItems[4].score) \(leaderboardItems[4].name)"

}

当我运行代码时,这是显示的输出 enter image description here

2 个答案:

答案 0 :(得分:2)

您需要解包可选值。你也可以这样做:

if let score = leaderboardItems[0].score {
     leaderboardScore1.text = String(format: "%zd", score)
}

答案 1 :(得分:-1)

这似乎是有问题的一行:

得分=字符串(snapshot.value ["得分"])