无法转换类型' [消息]'的值预期参数类型'消息'

时间:2018-03-19 10:48:23

标签: swift xcode core-data

我正在关注this教程,并且我收到了标题中可以看到的错误,这是我的代码:

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)
                }
            }
        }
    }
}

正如您从大约13分钟看到的那样,我的代码看起来并不完全相同,因为视频有点旧并使用较旧版本的swift。

我希望有人可以帮助我解决错误,因为我不知道该怎么做,请提前谢谢。

2 个答案:

答案 0 :(得分:1)

append是将单个元素追加到数组中。您可以使用+=连接两个数组。

messages! += fetchedMessages 

如果messages是可选类型,你可以强行打开它,因为你知道你已经将它设置为空数组,但坦率地说,我不会让messages可选 - 只需将其初始化为[]

答案 1 :(得分:1)

尝试下面的行

messages.append(contentsOf: fetchedMessages) 

代替:messages.append(fetchedMessages)