ios - xcode swift AnyObject 到 Swift 转换

标签 ios xcode swift

    let dataJSON = response .dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    let decodedJson = NSJSONSerialization.JSONObjectWithData(dataJSON!, options: nil, error: nil) as NSDictionary
    println(decodedJson["UserId"])

    let BlockedValue = decodedJson["UserId"] as NSString
    NSLog("USER ID : %@",BlockedValue)

当我构建代码部分时,此代码不起作用;

首先 println 工作输出:可选(1269) 但是第二个 NSLog 不起作用

我如何将 AnyObject 转换为 String 我在谷歌上研究了这个主题,我发现了一些代码部分,但这些都不起作用

我发现这个不行

if let receiver = decodedJson["UserId"] as? NSString {

    self.receiver = receiver
}

请问有什么帮助吗?

最佳答案

看来decodedJson["UserId"]是一个可选的数字。

一种方法(你必须确保 decodedJson["UserId"] 不是'nil):

let number = decodedJson["UserId"]
if number != nil {
    let string = "\(number!)"
}

或者在凝聚态:

if let number = decodedJson["UserId"] {
   let string = "\(number)"
}

关于ios - xcode swift AnyObject 到 Swift 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28250496/

相关文章:

ios - 从框架加载初始 View

ios - 无需堆叠的推送 View Controller

ios - 使用XCode 5为iOS编译Opus 1.1-rc2

xcode - iOS 7 中的 CoreData 迁移

ios - 如何在不使用按钮的情况下直接点击将显示地址的单元格?

ios - 从终端构建应用程序时代码设计失败

ios - 保存由结构体对象数组组成的 Realm 列表

ios - 如何防止选择器 View 重复

ios - 对于哪些用例,可以选择 tableView :didSelectRowAtIndexPath: rather than prepareForSegue:sender:?

ios - Mac Catalyst for Mac 菜单栏中的 NSPopover