【问题标题】:How I can define and appended an element to an array of dictionaries我如何定义元素并将其附加到字典数组
【发布时间】:2020-02-14 16:14:21
【问题描述】:

我正在研究一个项目,它读取一个 plist 包含字典行,一个名为 countries 的数组包含国家,国家数组填充了我的 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' ,我真的很感激任何帮助。谢谢你

【问题讨论】:

    标签: ios arrays swift dictionary plist


    【解决方案1】:

    只需删除 test 周围的括号:

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

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

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

    【讨论】:

    • 是的,非常感谢,它有效,真的非常感谢大卫
    猜你喜欢
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2021-10-08
    • 2015-02-03
    • 1970-01-01
    相关资源
    最近更新 更多