gpt4 book ai didi

ios - fatal error : unexpectedly found nil while unwrapping an Optional value while using Swift

转载 作者:搜寻专家 更新时间:2023-11-01 05:51:31 24 4
gpt4 key购买 nike

我正在尝试在 Swift 中实现 UICollectionView

我对 let array = objects.objectForKey("image_url") as [String] 行中的可选值有疑问

我不知道我的代码有什么问题。

ViewController.swift

import UIKit

var data: [String] = [] ;

class ViewController: UICollectionViewController{

override func viewDidLoad() {
super.viewDidLoad()

var collectionView: UICollectionView

let json = "https://api.photozou.jp/rest/search_public.json?keyword=bike"//"http://dl.dropboxusercontent.com/u/7817937/nameko.json"
let uri = NSURL(string: json)
let uridata = NSData(contentsOfURL: uri)
let objects = uridata.objectFromJSONData() as NSDictionary
let array = objects.objectForKey("image_url") as [String]
data += array

//println(array)



}

override func numberOfSectionsInCollectionView(collectionView: UICollectionView?) -> Int {
return 1
}

override func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int {
return data.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as CollectionViewCell
let url = NSURL(string: data[indexPath.row])
cell.image.setImageWithURL(url, placeholderImage: nil)

return cell
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

有人解决这个错误吗?

最佳答案

你可以这样避免崩溃:

 if objects != nil  
{
if objects.objectForKey("image_url") != nil
{
let array = objects.objectForKey("image_url") as [String]
data += array
}
}

关于ios - fatal error : unexpectedly found nil while unwrapping an Optional value while using Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203000/

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