vkoh
vkoh

Reputation: 11

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

I have been trying to understand the problem below. Since I am new to Swift whatever I am coding may not make any sense at all and therefore there's no way to explain. I understand. The codes are copied from some online tutorials and I am trying to incorporate data persistence into it using Core Data. This is where I got stuck half way through.

Hope someone can help.

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

    }

   }
}

Upvotes: 0

Views: 276

Answers (1)

Vincent
Vincent

Reputation: 4773

Let's consider the typing of each line:

This line:

var tempVideos : [Video]

means tempVideos is an array containing items of type Video

These lines:

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

means v1 is a String (I guess it's the URL of the image, which is a String), and t1 is also a String (the title of the video).

This line:

let video1 = [v1,t1] 

means you are building an array with 2 items (v1 and t1).

v1 and t1 are both String items, so video1 is an array containing items of type String

Let's recap:

tempVideos is an array containing items of type Video

video1 is an array containing items of type String

So:

tempVideos.append(video1)

means I want to put an array of String (which is [String?]) inside an array that can only contain Video items.

Thus, the error:

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

The solution is to create video1 as a Video object (I can't tell you how, that's your code, not mine), then you can do tempVideos.append(video1)

Upvotes: 1

Related Questions