Double與Float

  • 不同型別會開不同的記憶體;佔用量比較( Int < Float < Double )
  • Double表示 64 位元浮點數。當你需要儲存很大或者很高精度的浮點數時請使用此型別。
  • Float表示 32 位元浮點數。精度要求不高的話可以使用此型別。

注意:

Double精確度很高,至少有 15 位數字,而Float最少只有 6 位數字。選擇哪個型別取決於你的程式碼需要處理的值的範圍。

常見運算

var num             //error: type annotation missing in pattern. (宣告變數不能只宣告名稱。)
num = 1

var num1 = 100
var num2: Int
num1 = num2         //error: variable 'num2' used before being initialized. (num2沒給初始值。)

var max = UInt8.max
max = max + 1       //Execution was interrupted, reason: EXC_BAD_INSTRUCTION. (整數溢位會造成系統崩潰。)

var str = "hello"
str = 123           //error: cannot assign a value of type 'Int' to a value of type 'String'
           //(變數型別一旦決定就無法變更。)

var v1 = 123        //type: Int
var v2 = String(v1) //type: String (型別轉換必須顯式指定型別)

型別安全 (Type Safety)

Swift 也是一種非常龜毛嚴謹的語言。

  • 宣告變數不能只宣告名稱。
  • 常數、變數使用前必須給定初值。
  • 變數型別一旦決定就無法變更。
  • 整數溢位會造成系統崩潰。
  • 型別轉換必須顯式指定型別。
var num             //error: type annotation missing in pattern. (宣告變數不能只宣告名稱。)
num = 1

var num1 = 100
var num2: Int
num1 = num2         //error: variable 'num2' used before being initialized. (num2沒給初始值。)

var max = UInt8.max
max = max + 1       //Execution was interrupted, reason: EXC_BAD_INSTRUCTION. (整數溢位會造成系統崩潰。)

var str = "hello"
str = 123           //error: cannot assign a value of type 'Int' to a value of type 'String'
           //(變數型別一旦決定就無法變更。)

var v1 = 123        //type: Int
var v2 = String(v1) //type: String (型別轉換必須顯式指定型別)

*資料來源:https://hugolu.gitbooks.io/learn-swift/content/Basic/Types.html

results matching ""

    No results matching ""