首页 > 解决方案 > 我如何定义元素并将其附加到字典数组

问题描述

我正在研究一个项目,它读取一个包含多行字典的 plist 和一个名为国家的数组包含国家,国家数组填充了我的 plist 的数据并且一切正常,现在我需要定义一个元素并使用它来附加到我的数组,

这是我的国家定义

struct Country : Codable {
    let orFlagEmoji, destFlagEmoji, : String

    private enum CointryKeys : String, CodingKey { case orFlagEmoji,destFlagEmoji }
}

var countries = [Country]()

 override func viewDidLoad() 
 {
    super.viewDidLoad()

     let urlPlist = Bundle.main.url(forResource: "ListinFirstPage", withExtension: "plist")!
    let data = try! Data(contentsOf: urlPlist)


    do
    {
        countries = try PropertyListDecoder().decode([Country].self, from: data)
    }
    catch
    {
        // Handle error
        print(error)
    }


    //The problem is in two line bottom 

    var test = [TableViewController.Country(orFlagEmoji: "something", destFlagEmoji: "one thing")]



    countries.append(test)




 }

当我添加这两行

var test = [TableViewController.Country(orFlagEmoji: "something", destFlagEmoji: "one thing")]

countries.append(test)

它遇到了这个错误 Cannot convert value of type '[TableViewController.Country]' to expected argument type 'TableViewController.Country' ,我非常感谢您的帮助。谢谢你

标签: iosarraysswiftdictionaryplist

解决方案


只需删除周围的括号test

var test = TableViewController.Country(orFlagEmoji: "something", destFlagEmoji: "one thing")

countries.append(test)

或者,如果您需要连接两个数组,请执行以下操作:

var test = [TableViewController.Country(orFlagEmoji: "something", destFlagEmoji: "one thing")]

countries += test

推荐阅读