Skip to content

Instantly share code, notes, and snippets.

@takashi1975
Last active February 13, 2018 05:40
Show Gist options
  • Select an option

  • Save takashi1975/583c6a7f3556713b253dd4aa30556bda to your computer and use it in GitHub Desktop.

Select an option

Save takashi1975/583c6a7f3556713b253dd4aa30556bda to your computer and use it in GitHub Desktop.
swift4 abs
class sample {
/**
* メモ
* 標準の abs ... abs(Int32) だけなので... Int16 も扱える abs を Generics で試してみた。
*
* Generics の 型制限 をできないものかと...ググると SignedNumeric, SignedInteger を指定できる様子。
* ただ... SignedNumeric を指定すると (x < 0) の比較で エラーになるため 整数のみを指定
* Float などもまとめて処理できたらいいな...と思ったが...とりあえず見送り
*/
//整数用
static fileprivate func abs<T: SignedInteger>(_ x: T) -> T {
if (x < T(0)) { return (-1 * x) }
return x
}
//実数用
static fileprivate func abs<T: FloatingPoint>(_ x: T) -> T {
if (x < T(0)) { return (-1 * x) }
return x
}
}
@takashi1975

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment