LoginSignup
78
78

More than 5 years have passed since last update.

意外と知られていないSwift数値型の細かい仕様

Last updated at Posted at 2015-12-23

Swiftの数値型の細かい仕様について書いていきます。

Swiftの数値を表す型

整数

最大値 最小値
Int 2147483647
9223372036854775807
-2147483648
-9223372036854775808
(実行環境が32bitか64bitによって違う)
Int8 127 -128
Int16 32767 -32768
Int32 2147483647 -2147483648
Int64 9223372036854775807 -9223372036854775808
UInt 4294967295
18446744073709551615
(実行環境が32bitか64bitによって違う)
0
UInt8 255 0
UInt16 65535 0
UInt32 4294967295 0
UInt64 18446744073709551615 0

小数

長さ
Double 64bit
Float 32bit
Float32 32bit
Float64 64bit
Float80 80bit
CGFloat 32bit/64bit(実行環境が何bitかに依る)

エイリアス

数値型ではないものもありますが、関連するAliasもまとめてみました。

元クラス
CChar Int8
CChar16 UInt16
CChar32 UnicodeScalar(文字列)
CInt Int32
CLong Int
CLongLong Int64
CShort Int16
CSignedChar Int8
CUnsignedChar UInt8
CUnsignedInt UInt32
CUnsignedLong UInt
CUnsignedLongLong UInt64
CUnsignedShort UInt16
IntegerLiteralType Int
CDouble Double
CFloat Float

その他

数値型とは少し違いますが、Bitという1と0を表現する列挙型もあります。
.Zero.Oneの2種類の値を取ります。

Swiftのリテラルでできる事

アンダーバーを利用

1_000
0.000_1

2進数・8進数・16進数

0b10001 // → 17
0o21 // → 17
0x11 // → 17

指数

12e2 // → 1200(12 * 10の2乗)
0x10p4 // → 256(16 * 2の4乗)

数値の剰余を求める計算

通常の剰余の求め方です。

5 % 3 // → 2
1 % 3 // → 1

負の数に対する計算も正の値と同様に行えます。
計算結果は左の値の符号に依存します。

-1 % 3 // → -1
-4 % -3 // → -1
7 % -5 // → 2

小数点に対しても行えます。

print(1.1 % 3.1) // → 1.1
print(-3.1 % 3) // → -0.1
78
78
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
78
78