使用 Swift 2 的 iOS 開發 - 變數



變數是指程式用來儲存和操作資料的記憶體/儲存空間。每個變數都有特定的資料型別,它決定了變數在記憶體中佔據的大小。

Swift 提供以下資料型別 -

  • Int - 用於儲存整數/程式中的整數。

  • Double - 用於儲存大浮點數 (64 位),例如 -378.878。

  • Float - 用於儲存小浮點數。例如 3.14

  • Char (字元) - 用於儲存單個字元。例如'A'

  • String - 這是字元的集合。例如 -“這是字串”。

  • Bool - 此資料型別僅用於儲存 true 或 false 值。

Swift 還允許使用其他資料型別,例如 -

  • 陣列
  • 字典
  • 結構
  • 可選項

所有這些將在後續章節中討論。

變數宣告

變數宣告用於宣告變數,即在那變數所在的記憶體中分配空間。要在 Swift 中宣告變數,我們需要使用關鍵字 var

var variableName = Initial Value   
var x = 10 or var x = "Hello" 
// We can use this method of declaration if we   
// don’t know that kind of data will be stored. 
var variableName : Data type = Initial Value  
// if we know the data type. 
Var x: Int = 10    
// can only store integer type of data

如上所示,我們可以透過上述任意方法將任何數量的變數新增到我們的程式碼中,無論哪種方法適合我們使用。

ios_development_with_swift2_playground.htm
廣告
© . All rights reserved.