を(あるいは、Objective Cの「平均的な問題」を解決する方法を伝えること)は、AndréSlottaによって完全に答えられました。迅速な削減はそれ以上のものです。私は、戻り結果を繰り返し 初期と自己の各要素に初期化累積値と組み合わせる呼び出しの 概念は迅速
に
func reduce<T>(initial: T, @noescape combine: (T, Self.Generator.Element) throws -> T) rethrows -> T
をどのように機能するか、あなたの質問の後半部分に答えることをしようとします(自己(0)、 self [1])、... self [count-2])、self [count-1])を返します。
let arr: Array<Int> = [1,2,3,4,5]
let sum = arr.reduce(0) { (sum, i) -> Int in
return sum + i
}
print(sum) // 15
// this is an quasi equivalent of
var sum1 = 0 // ..... reduce(0)....
arr.forEach { (elementValue) -> Void in
sum1 = sum1 + elementValue // ...{ return sum + i }
}
print(sum1) // 15 reduce function will return accumulated inital value
// reduce is part of SequenceType protocol, that is why
let arr1 = ["H","e","l","l","o"," ","w","o","r","l","d"]
let str = arr1.reduce("") { (str, s) -> String in
str + s
}
// works the same way
print(str) // "Hello world"
// let have a litle bit more complex example, to see how powerful, useful and easy to use reduce can be
let dict = arr1.reduce([:]) { (var dict, s) -> Dictionary<Int,String> in
let i = dict.count
dict.updateValue(s, forKey: i+1)
return dict
}
print(dict) // [11: "d", 10: "l", 2: "e", 4: "l", 9: "r", 5: "o", 6: " ", 7: "w", 3: "l", 1: "H", 8: "o"]
どのタイプ 'graphPoints'配列を行います含む? –
推測: 'average = [graphView.graphPoints valueForKeyPath:@" @ sum。 – Larme
配列は:var graphPoints:[Int] = [4,2,6,4,5,8,3]、intオブジェクトを含んでいます。 – Adela