【问题标题】:How to create arraylist of object in swift如何在swift中创建对象的arraylist
【发布时间】:2015-11-24 11:29:22
【问题描述】:

在java中,我们可以像这样创建对象的arraylist:

ArrayList<Country> countryList = new ArrayList<Country>();

        Country aBucket = new Country();
        aBucket.setName("Canada");
        aBucket.setCity("Ottawa");
        countryList.add(aBucket);

或者像这样:

ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );

但是我怎样才能在 SWIFT 中获得相同的东西/替代方法

【问题讨论】:

    标签: arrays swift


    【解决方案1】:

    您可以使用数组来做到这一点。 查看here 了解有关数组的更多信息。

    您可以使用append(...) 函数添加对象。

    var array = [Country]() //alternatively (does the same): var array = Array<Country>()
    array.append(Country())
    array.append(Country())
    

    【讨论】:

      【解决方案2】:

      尝试使代码尽可能接近您的示例代码,这是我的答案(需要在某处声明 Country 类:

      var countryList : Array<Country> = Array()
      var aBucket     : Country        = Country()
      ....
      countryList.append(aBucket)
      

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        尝试使代码尽可能接近您的示例代码,因此我使用 Set 数据结构:

        var mSet = Set<Country>()
        var aBucket : Country = Country()
        ...
        mSet.insert(aBucket)
        

        【讨论】:

          【解决方案4】:

          返回列表的函数

          func getCountries() -> Array<Country>{
          
              var countryList = Array<Country>()              //Initialization
          
              let iceland = Country()                         // Set up
              iceland.name = "Iceland"
              iceland.city = "Reykjavik"
          
              let usa = Country()
              usa.name = "United States of America"
              usa.city = "New York"
          
              countryList.append(iceland)                    // Add to list
              countryList.append(usa)
          
              return countryList                             // Return
          
          }
              
          

          【讨论】:

          • 在 Country 的第二个区块中,您正在更新冰岛...
          • 更新了@LetynSOFT 好收获
          猜你喜欢
          • 2018-03-17
          • 1970-01-01
          • 2020-03-21
          • 2015-05-04
          • 2011-04-28
          • 2019-09-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多