如何将对象多次附加到数组

时间:2016-03-31 06:25:41

标签: swift

我想将所有对象追加到一行中。我有一些像这样的对象:

let abaddon = Hero(name: "abaddon")
let ember = Hero(name: "ember")
let gondar = Hero(name: "gondar")
let kael = Hero(name: "kael")
let kunkka = Hero(name: "kunkka")
let layana = Hero(name: "layana")
let lucifer = Hero(name: "lucifer")
let omni = Hero(name: "omni")
let soul = Hero(name: "soul")
let wind = Hero(name: "wind")

Hero Object就像这样:

class Hero {

    var name: String!
    var image: UIImage? {
        return UIImage(named: "\(name)")!
    }

    required init(name: String) {
        self.name = name
    }
}

我想把它们放到这个数组中:var heroes = [Hero]()

但是我看到append每次只能放一个对象。

heroes.append(abaddon)

如何在单行中追加多个对象,如下所示:

heroes.append([abaddon, ember, gondar])

任何帮助都将不胜感激,谢谢。

4 个答案:

答案 0 :(得分:12)

如果要附加多个对象,可以将它们自己包装成数组并使用appendContentsOf。

heroes.appendContentsOf([abaddon, ember, gondor])

答案 1 :(得分:6)

我试着这样:

public View getView(int position, View convertView, final ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.list_equipment_search, null);
    enter code here
    TextView serialno = (TextView) vi.findViewById(R.id.txtSerialNo); // Serial No
    TextView unitno = (TextView) vi.findViewById(R.id.txtUnitNo);

 CheckBox checkbox = (CheckBox) row.findViewById(R.id.chkEquipment);
        checkbox.setTag(new Integer(position));
        checkbox.setOnCheckedChangeListener(null);

            if (checkBoxState[position])
                checkbox.setChecked(true);
            else
                checkbox.setChecked(false);



        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Integer pos = (Integer) buttonView.getTag();
                if (isChecked) {

                    checkBoxState[pos.intValue()] = true;
                } else {
                    checkBoxState[pos.intValue()] = false;


                }
            }
        });

所以我不需要声明所有对象

答案 2 :(得分:1)

为什么不

var heroes = [abaddon, ember, ..., wind]

答案 3 :(得分:0)

@TPlet的Swift 4.x答案

factory_name_1  factory_name_2
A                 C
B                 A
B                 C