无法将类型“ [String?]”的值转换为预期的参数类型“ Video”

我一直试图了解以下问题。由于我是Swift的新手,无论我编写什么代码,都可能毫无意义,因此无法解释。我明白。这些代码是从一些在线教程中复制而来的,我正在尝试使用Core Data将数据持久性纳入其中。这是我陷入困境的地方。

希望有人可以提供帮助。

enter code here

Core Data model attached to the following view controller : 

entity    : Video
attribute : image - String
attribute : title - String


   import UIKit
   import CoreData

class VideoListScreenVC: UIViewController {

     @IBOutlet weak var tableView: UITableView!

     var videos : [Video] = [ ]


override func viewDidLoad() {
    super.viewDidLoad()

    videos = createArray()

}

   func createArray() -> [Video] {

      var tempVideos : [Video] = []


     if let context = (UIApplication.shared.delegate as     AppDelegate)?.persistentContainer.viewContext{

            let videoX = Video(context: context)

                let v1 = videoX.image
                let t1 = videoX.title

       let video1 = [v1,t1]
       let video2 = [v1,t1]
       let video3 = [v1,t1]
       let video4 = [v1,t1]
       let video5 = [v1,t1]

       tempVideos.append(video1) // error : Cannot convert value of type '[String?]' to expected argument type 'Video'
 //       tempVideos.append(video2)
 //      tempVideos.append(video3)
//      tempVideos.append(video4)
//       tempVideos.append(video5)

          return tempVideos

    }

   }
}
houxingyu555 回答:无法将类型“ [String?]”的值转换为预期的参数类型“ Video”

让我们考虑一下每行的键入:

此行:

var tempVideos : [Video]

表示tempVideos是一个数组,其中包含类型为Video的项目

这些行:

let v1 = videoX.image
let t1 = videoX.title

v1是一个字符串(我想它是图像的URL,它是一个字符串),而t1也是一个字符串(视频的标题)。

此行:

let video1 = [v1,t1] 

表示您要构建一个包含2个项(v1和t1)的数组。

v1和t1都是String项,因此video1是一个数组,其中包含类型为String的项

回顾一下:

tempVideos是一个数组,其中包含类型为Video

的项

video1是一个数组,其中包含类型为String的项目

所以:

tempVideos.append(video1)

意味着我想在只能包含[String?]个项目的数组中放置一个String数组(Video)。

因此,错误:

error : Cannot convert value of type '[String?]' to expected argument type 'Video'

解决方案是将video1创建为Video对象(我不能告诉你如何,那是你的代码,不是我的),然后可以执行tempVideos.append(video1)

本文链接:https://www.f2er.com/3096511.html

大家都在问