打印徽章时摆脱可选项

时间:2017-01-19 08:16:54

标签: ios swift3

let vals2: String? = String(describing: store?.data?.newsArticles?.count)
print(vals2!)
self.newsTabBarItem.badgeValue = vals2!
self.menuList = (store?.data?.newsArticles)!

我获得了array的计数并将其设为badge值,但是它在徽章中显示可选(例如5,如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

store?.data?.newsArticles?.count

optional,然后是

String(describing: store?.data?.newsArticles?.count)

将等于"Optional(3)",其类型将为String而不是String?。您需要解开count而不是vals2

let newsArticles = store?.data?.newsArticles // newsArticles is an Optional
let vals2: String = String(describing: newsArticles!.count)
print(vals2)
self.newsTabBarItem.badgeValue = vals2
self.menuList = newsArticles!

更好的是,如果您的代码需要newsArticles

if let newsArticles = store?.data?.newsArticles { // newsArticles won't be an Optional
    let vals2 = String(describing: newsArticles.count)
    print(vals2)
    self.newsTabBarItem.badgeValue = vals2
    self.menuList = newsArticles
}

答案 1 :(得分:0)

您通过该电话获得了Optional(n)

String(describing: store?.data?.newsArticles?.count)

因为您要求Optional<Int>的说明。

你可以试试这个:

let vals2: String? = store?.data?.newsArticles?.count.map { count in
    String(describing: count)
}
self.newsTabBarItem.badgeValue = vals2 // don't use `!` here