associatedtype Magnitude
Overview 概要
The Numeric
protocol provides a suitable basis for arithmetic on scalar values, such as integers and floating-point numbers. You can write generic methods that operate on any numeric type in the standard library by using the Numeric
protocol as a generic constraint.
Numeric
プロトコルは、例えば整数および浮動小数点数など、スカラー値に関する算術にふさわしい基礎を提供します。あなたは、Numeric
プロトコルを総称体制約として使うことで、標準ライブラリのあらゆる数値型上で作用する総称体メソッドを書くことができます。
The following example extends Sequence
with a method that returns an array with the sequence’s values multiplied by two.
以下の例は、Sequence
をあるメソッドで拡張します、それはそのシーケンスの2を掛けた値を持つ配列を返すものです。
extension Sequence where Element: Numeric {
func doublingAll() -> [Element] {
return map { $0 * 2 }
}
}
With this extension, any sequence with elements that conform to Numeric
has the doubling
method. For example, you can double the elements of an array of doubles or a range of integers:
この拡張で、Numeric
に準拠する要素をもつあらゆるシーケンスは、doubling
メソッドを持ちます。例えば、あなたはdoubleのある配列または整数のある範囲の要素を倍にできます。
let observations = [1.5, 2.0, 3.25, 4.875, 5.5]
let doubledObservations = observations.doublingAll()
// doubledObservations == [3.0, 4.0, 6.5, 9.75, 11.0]
let integers = 0..<8
let doubledIntegers = integers.doublingAll()
// doubledIntegers == [0, 2, 4, 6, 8, 10, 12, 14]
Conforming to the Numeric Protocol Numericプロトコルに準拠する
To add Numeric
protocol conformance to your own custom type, implement the required initializer and operators, and provide a magnitude
property using a type that can represent the magnitude of any value of your custom type.
Numeric
プロトコル準拠をあなた独自のカスタム型に加えるには、必須イニシャライザおよび演算子を実装してください、そしてあなたのあつらえの型のあらゆる値の規模を表現できる型を使ってmagnitude
プロパティを提供してください。