Swift基本概念
Hello, world
类似于脚本语言,下面的代码即是一个完整的 Swift 程序。
1 println ("Hello, world")
变量与常量
Swift 使用var
声明变量,let
声明常量。
1 var myVariable = 42
2 myVariable = 50
3 let myConstant = 42
类型推导
Swift 支持类型推导(Type Inference),所以上面的代码不需指定类型,如果需要指定类型:
1 let explicitDouble : Double = 70
Swift 不支持隐式类型转换(Implicitly casting),所以下面的代码需要显式类型转换(Explicitly casting):
1 let label = "The width is "
2 let width = 94
3 let width = label + String (width)
字符串格式化
Swift 使用\(item)
的形式进行字符串格式化:
1 let apples = 3
2 let oranges = 5
3 let appleSummary = "I have \(apples) apples."
4 let appleSummary = "I have \(apples + oranges) pieces of fruit."
数组和字典
Swift 使用[]
操作符声明数组(array)和字典(dictionary):
1 var shoppingList = ["catfish", "water", "tulips", "blue paint"]
2 shoppingList[1] = "bottle of water" var occupations = [
3 "Malcolm": "Captain",
4 "Kaylee": "Mechanic",
5 ]
6 occupations["Jayne"] = "Public Relations"
一般使用初始化器(initializer)语法创建空数组和空字典:
1 let emptyArray = String[]()
2 let emptyDictionary = Dictionary<String, Float>()
如果类型信息已知,则可以使用[]
声明空数组,使用[:]
声明空字典。