Last active
February 13, 2018 05:40
-
-
Save takashi1975/583c6a7f3556713b253dd4aa30556bda to your computer and use it in GitHub Desktop.
swift4 abs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://developer.apple.com/documentation/swift/signedinteger