gpt4 book ai didi

ios - Swift 3 中的 JSON 解析和可选项

转载 作者:行者123 更新时间:2023-11-28 21:20:27 25 4
gpt4 key购买 nike

所以我最近更新到 Swift 3/XCode 8 并且我的一些代码乱七八糟。我读过一些语法更改,但我似乎无法正确理解这一点。我向 Twitter 发出请求并取回 JSON:

func forLoadStats(completion: (AnyObject?, NSError?) -> Void)
{
var clientError: NSError?
let idString = api.getUserID()
let client = TWTRAPIClient()
let request = client.urlRequest(withMethod: "GET", url: "https://api.twitter.com/1.1/users/show.json", parameters: ["user_id" : 27446437], error: &clientError)
client.sendTwitterRequest(request)
{ (response, data, connectionError) in

if (connectionError == nil)
{
do {
if let json: Any = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [AnyObject]
{
if let json = json, let immage = json?["profile_image_url_https"] as? String
{
//Make ProfilePic edges round
self.profPic.layer.cornerRadius = 42
self.profPic.clipsToBounds = true

//let immage = image["profile_image_url_https"] as String
let _vImageUrl = immage.replacingOccurrences(of: "_normal", with: "")
let urlProfilePic = NSURL(string: _vImageUrl)
let urlPP = NSData(contentsOf: urlProfilePic! as URL)
self.profPic.image = UIImage(data: urlPP! as Data)

let ScrName = json["screen_name"] as! String
self.scrNameLabel.text = "@\(ScrName)"

//Populate Followers Label.text
let flwrVar = json["followers_count"] as! Int
self.followerLbl.text = "\(flwrVar)"

//Populate Following Label.text
let flwngVar = json["friends_count"] as! Int
self.followingLbl.text = "\(flwngVar)"

//Populate Bio
let bio = json["description"] as! String
self.bioLabel.text = "\(bio)"

//created at date
let accountAge = json["created_at"] as! String

self.createdLbl.text = "\(accountAge)"

let tweetCount = json["statuses_count"] as! Int
self.tweetCount.text = "\(tweetCount)"

let likes = json["favourites_count"] as! Int
self.likesCount.text = "\(likes)"

let lists = json["listed_count"] as! Int
self.listedCount.text = "\(lists)"
}
}
}
catch let error
{
print(error)
}
}
}
}

我在第二个“If let”语句中收到错误消息:“条件绑定(bind)的初始化程序必须具有可选类型,而不是‘Any。谁能解释这是为什么?

最佳答案

你的 JSON 显然是一个字典,Swift 3 中的 JSON 字典是 [String:Any]

错误是由愚蠢的 Any 注释(应该是 Any? 但实际上是无意义的)引起的,因为它混淆了编译器。

如果您使用 do block ,try 不带问号但使用可选绑定(bind):

...
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any] {
if let immage = json["profile_image_url_https"] as? String { ...

关于ios - Swift 3 中的 JSON 解析和可选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39981412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com