本系列学习教程对应的原文地址:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-XID_1
第二讲 Swift中的简单值类型
学习任何一门语言,首先要知道它的值是怎么声明,怎么使用的,这里说明下:
1. 常量
用 let 声明:
let i = 0
而C++中用constant, Java中用final
2. 变量
用 var 声明:
var value = 0
3. 不管是用let还是var都可以不用显式的指定数据类型,比如上面的例子,也可以显式的指定:
let width:Int = 10
格式为:(值名称 : 类型)
4. 对于类型转换,Swift不支持隐式类型转换,必须显式的生成目标类型的新实例,见下面例子:
let label ="The width is "
let width =94
let widthLabel =label + String(width)
5. 对于string,可以采用下面更简单的办法:\(stringValue)
let apples =3
let oranges =5
let appleSummary ="I have \(apples) apples."
let fruitSummary ="I have \(apples + oranges) pieces of fruit."
6. 数组 (Array)
很简单,用中括号[]:
var shoppingList = ["catfish","water", "tulips", "blue paint"]
读取的时候,使用index:
shoppingList[1] = "bottle of water"
7.字典 (Dictionary)
类似与Array,使用中括号[]
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic"
]
读取的使用使用key
occupations["Jayne"] ="Public Relations"
8.如果要生成一个空的Array或Dictionary,使用
initializer
let emptyArray = [String]()
let emptyDictionary = [String:Float]()
总结:上面主要介绍了Swift中如何声明常量、变量、数组、字典,其实还是挺简单的。Swift中只有两种集合类型,即Array和Dictionary,没有C++和Java中丰富,
不过也够用了。
下面提供下英文版的资料,供参考:
Simple values
1) Use let
to make a constant andvar
to make a variable
2) A constant or variable must have the same type as the value you want to assign to it
3) However, you don’t always have to write the type explicitly
4) If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.
let explicitDouble: Double = 70
5) Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.
let label ="The width is "
let width =94
let widthLabel =label + String(width)
6)
There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (\
) before the parentheses.
let apples =3
let oranges =5
let appleSummary ="I have \(apples) apples."
let fruitSummary ="I have \(apples + oranges) pieces of fruit."
[]
), and access their elements by writing the index or key in brackets.
var shoppingList = ["catfish","water", "tulips", "blue paint"]
shoppingList[1] ="bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] ="Public Relations"
8) To create an empty array or dictionary, use the initializer syntax.
let emptyArray = [String]()
let emptyDictionary = [String:Float]()
[]
and an empty dictionary as [:]
—for example, when you set a new value for a variable or pass an argument to a function.
shoppingList = []
occupations = [:]