gpt4 book ai didi

swift - 类型 'Any' 的值没有成员 'valueForKeyPath'

转载 作者:行者123 更新时间:2023-11-30 11:22:39 25 4
gpt4 key购买 nike

我正在寻找其他堆栈溢出问题,但似乎它不适用于我的情况。

我正在制作 YouTube 应用,我的代码如下。

     if let JSON = response.result.value as? NSDictionary{

var arrayOfVideos = [Video]()

for video in JSON["items"] as! NSArray{
print(video)

//Create video onjects off of the JSON response
let videoObj = Video()
//I got errors following part
videoObj.videoId = video.valueForKeyPath("snippet.resourceId.videoId") as! String
videoObj.videoTitle = video.valueForKeyPath("snippet.title") as! String
videoObj.videoDescription = video.valueForKeyPath("snippet.description") as! String
videoObj.videoThumbnailUrl = video.valueForKeyPath("snippet.thumbnails.maxres.url") as! String

arrayOfVideos.append(videoObj)
}

self.videoArray = arrayOfVideos
}else{
print("couldn't get video information")
}

我还有一个视频类,它定义标题、描述和缩略图。

class Video: NSObject {

var videoId:String = ""
var videoTitle:String = ""
var videoDescription:String = ""
var videoThumbnailUrl:String = ""
}

我得到了这些错误。

Value of type 'Any' has no member 'valueForKeyPath'

还有这个

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我很感激任何帮助。预先感谢您。

最佳答案

你可以试试

if let JSON = response.result.value as? [String:Any] {

var arrayOfVideos = [Video]()

if let videos = JSON["items"] as? [[String:Any]] {

for video in videos {

let videoObj = Video()

if let videoId = video["snippet.resourceId.videoId"] as? String {

videoObj.videoId = videoId
}
if let videoTitle = video["snippet.title"] as? String {

videoObj.videoTitle = videoTitle
}
if let videoDescription = video["snippet.description"] as? String {

videoObj.videoDescription = videoDescription
}
if let videoThumbnailUrl = video["snippet.thumbnails.maxres.url"] as? String {

videoObj.videoThumbnailUrl = videoThumbnailUrl
}

arrayOfVideos.append(videoObj)
}
}
}

关于swift - 类型 'Any' 的值没有成员 'valueForKeyPath',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51116053/

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