random1234
random1234

Reputation: 817

Cannot convert value of type '[Message]' to expected argument type 'Message'

I'm following this tutorial and I'm getting the error that you can see in the title, here is my code:

func loadData()
{
    let delegate = UIApplication.shared.delegate as? AppDelegate

    if let context = delegate?.persistentContainer.viewContext
    {
        if let friends = fetchFriends()
        {
            messages = [Message]()

            for friend in friends
            {
                print(friend.name) // This line btw for some reason is giving me: Expression implicitly coerced from 'String?' to Any

                let fetchRequest:NSFetchRequest<Message> = Message.fetchRequest()
                fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
                fetchRequest.predicate = NSPredicate(format: "friend.name = %@", friend.name!)
                fetchRequest.fetchLimit = 1

                do
                {
                    let fetchedMessages = try(context.fetch(fetchRequest))
                    messages?.append(fetchedMessages)
                    // This above line is the line which is giving me this error:
                    //Cannot convert value of type '[Message]' to expected argument type 'Message'
                }
                catch let err
                {
                    print(err)
                }
            }
        }
    }
}

As you can see from about 13min my code does not look exactly the same, since the video is a bit old and using an older version of swift.

I'm hoping someone can help me to solve the error since I do not know what to do, thank you in advance.

Upvotes: 0

Views: 1002

Answers (2)

Moayad Al kouz
Moayad Al kouz

Reputation: 1392

try below line

messages.append(contentsOf: fetchedMessages) 

instead of: messages.append(fetchedMessages)

Upvotes: 2

JeremyP
JeremyP

Reputation: 86651

append is to append individual elements to an array. You can use += to concatenate two arrays.

messages! += fetchedMessages 

If messages is of optional type, you can force unwrap it because you know you have already set it to an empty array, but frankly, I would no make messages optional - just initialise it to []

Upvotes: 1

Related Questions