Upload
tomohiro-kumagai
View
1.368
Download
0
Embed Size (px)
Citation preview
func sum<T : Numeric>(of values: Array<T>) -> T {
return values.reduce(0) { $0 + $1 }}
// Int の配列でも、Float の配列でも、使える let integers = [5, 5, 5, 5]let floats = [2.5, 2.5, 2.5, 2.5] as [Float]
sum(of: integers) // 20sum(of: floats) // 10
func average <C:Collection> (of values: C ) -> C.Element where C.Element : BinaryInteger {
return values.reduce(into: 0, +=) / C.Element(values.count)}
extension Array {
// 変換元は、要素の型が同じならどんな Sequence でも良い init<S:Sequence>(_ s: S) where Element == S.Element}
// どんな Sequence も配列型に変換できる Array([1, 5, 8, 3, 7, 3]) // ArrayArray([1, 5, 8, 3, 7, 3][2 ..< 5]) // ArraySliceArray(1 ..< 20) // CountableRangeArray(zip([1, 3, 5], [2, 4, 6])) // Zip2Sequence<Array, Array>
// この書き方はパッと思いつかなくても、
func sum<T : Numeric>(of values: Array<T>) -> T {
return values.reduce(into: 0, +=)}
// こちらなら自然と書ける人も多いはず(上記より Swift らしいと思う)
extension Array where Element : Numeric {
func sum() -> Element {
return reduce(into: 0, +=) }}
struct Array : MutableCollectionType, Sliceable, ArrayLiteralConvertible {
}
// Swift 1 は“写像(map)”が主体 func map<C:CollectionType, T>(source: C, transform: (C.Generator.Element) -> T) -> [T]
// Swift 2 は“コレクション”が主体 extension CollectionType {
func map<T>(transform: (Generator.Element) -> T) -> [T]
}
func areaOfCircle<T:FloatingPoint>(withRadius radius: T) -> T { return radius * radius * T.pi}
areaOfCircle(withRadius: 2 as Double) // 12.566370614359172areaOfCircle(withRadius: 2 as Float) // 12.56637areaOfCircle(withRadius: 2 as Float80) // 12.566370614359172464
extension String {
// 現在主流の API func repeated(_ count: Int) -> String
// Protocol-Oriented Integers を用いた API func repeated<T:BinaryInteger>(_ count: T) -> String
}
"*".repeated(5) // "*****"
extension String {
func repeated<T:UnsignedInteger>(_ count: T) -> String
}
"*".repeated(5)