08月19, 2017

Swift系列一 | 初识Swift-简单值

简单值

变量&常量

  • let 声明常量, var 声明变量
  • 变量或常量声明并赋值不需要制定类型,编译器会自动推断类型
  • 声明变量或常量如果没有初始值则需要在后面类型声明,用冒号分割 let explicitDouble: Double = 70
  • 值永远不会隐式转换为其他类型,如果需要把一个值转换成其他类型,必须显示转换
let label = "The width is" let 
let width = 94
let withLebal = label + String(width)
  • 把值转换成字符串: 把值写到括号中,并在括号之前写一个反斜杠
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I hav \(apples + oranges) pieces of fruit."

数组&&字典

  • 使用方括号[]来创建数组和字典,使用下标或者键(key)来访问元素。最后一个元素后面允许有个逗号
var shopingList = ["catfish","water","tulips","blue paint"]

shopingList[i] = "bottle of water"

var occupations = [
    "Malcolm""Captain",
    "Kaylee"  : "Mechanic"
]
occupations["Jayne"] = "Public Relations"
  • 创建一个空数组或空字典,使用初始化方法
let emptyArray = [String]()
let empayDictionary = [String: Float]()
  • 如果类型信息可以被推断出来,可以使用[],[:]来创建空数组和空字典
shopingList = []
occupations = [:]

本文链接:http://codepowers.com/post/basic-knowledge-simple-value.html

-- EOF --

Comments