2017-06-27 71 views
0

我有一個結構的一類:如何在struct中循環項目?

class ShoppingItems : NSObject 
{ 
    struct historyLists { 
     var id: String 
     var name: String 
     var description: String 
     var itemCount: Int 
     var date: String 
     var img: String 
     var marktName: String 
     var price: Float 
     var productsOnList = [items]() 
    } 

    struct items { 
     var id: String 
     var quantity: Int 
    } 
} 

現在我附上一些東西:

var myStructHistoryItemLists = [historyLists]() 

myStructHistoryItemLists.append(historyLists(id: "l1", name: "NAME1", description: "DESC1", itemCount: 10, date: "22.02.2014", img: "IMG1", marktName: "marktNAME", price: 22.50, productsOnList: [ 
     items(id: "p1", quantity: 11), 
     items(id: "p2", quantity: 1), 
     items(id: "p3", quantity: 5) 
    ] 
)) 

myStructHistoryItemLists.append(historyLists(id: "l2", name: "NAME2", description: "DESC2", itemCount: 5, date: "10.01.2017", img: "IMG2", marktName: "marktNAME2", price: 22.50, productsOnList: [ 
     items(id: "p4", quantity: 11), 
     items(id: "p5", quantity: 1), 
     items(id: "p6", quantity: 5), 
     items(id: "s1", quantity: 5) 
    ] 
)) 

我的問題是我怎麼能追加在一個循環的項目從一個數組?

myStructHistoryItemLists.append(historyLists(id: "l3", name: "NAME3", description: "DESC3", itemCount: otherItemsArray.count, date: "10.01.2017", img: "IMG3", marktName: "marktNAME3", price: 22.50, productsOnList: [ 
     for items in otherItemsArray .... 
     items(id: otherItemsArray[item].id, quantity: otherItemsArray[item].quantity), 
    ] 
)) 

我怎樣才能從另一個類訪問這個?

感謝

+1

在調用myStructHistoryItemLists.append(...)之前創建items數組。然後只分配它。 – CoderFrom94

回答

2

如果otherItemsArrayitems一個數組,那麼所有你需要做的是通過你的數組中productsOnList參數。

let historyList = historyLists(
    id: "l3", name: "NAME3", 
    description: "DESC3", 
    itemCount: otherItemsArray.count, 
    date: "10.01.2017", img: "IMG3", 
    marktName: "marktNAME3", 
    price: 22.50, 
    productsOnList: otherItemsArray 
) 
myStructHistoryItemLists.append(historyList) 

而且你的名字你的結構方式是錯誤的。它們應該是單數,並以大寫字母開頭(HistoryListItem)。

+0

非常感謝!它非常容易;)(thx,我會重命名結構!) – silazzz