2017-08-02 61 views
2

我有一個項目追加屬性降低

struct Item { 
    var id: String 
} 

我如何可以追加所有的IDS使用減少功能的數組的數組?

我嘗試:

self.items.reduce([String](), { $0.0.append($0.1.id)}) 

但是編譯顯示了一個錯誤:

Contextual closure type '(_, [Item]) -> _' expects 2 arguments, but 1 was used in closure body

回答

1

如果你想這樣做與減少,這裏是斯威夫特3段和4:

struct Item { 
    var id: String 
} 

var items = [Item(id: "text1"), Item(id: "text2")] 
let reduceResult = items.reduce([String](), { $0 + [$1.id] }) 
reduceResult // ["text1", "text2"] 

有2個問題:

  1. 減少是給你2個參數,不有2個值
  2. 不能編輯傳遞給你塊參數單個元組,你必須返回新對象

但在這種情況下,最好的解決辦法是使用地圖:

let reduceResult = items.map { $0.id } 
1

試試這個:

items.reduce([String](), { res, item in 
    var arr = res 
    arr.append(item.id) 
    return arr 
}) 
+0

錯誤:類型爲「[項目]」沒有成員「id」值 –

+0

對不起,更新......至於@vadian雖然說,你可能真的想使用'map'。 – paulvs

1

你大概的意思map而不是reduce

let ids = items.map{ $0.id }