Swift tour
输出函数:
print(“hello world!")
无需引入函数库,无须使用“;”作为语句结尾,也无须写跟其它语言一样的main()函数,Swift中,全局区的代码就是程序入口。
You don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program, so you don’t need a main()function. You also don’t need to write semicolons at the end of every statement.
一,简单数据类型
1,使用let声明常量,用var声明变量
var myVariable = 42 myVariable = 50 let myConstant = 42
a,声明常量和变量的时候,无须指明数据类型,编译器会根据初始值去推断常量和变量具体的类型;
b,若初始值没有提供足够的信息去判断该变量的类型,需要在变量之后声明其数据类型,以“:”分割。例如:
let myInteger = 40 let myDouble = 40.0 let exDouble: Double = 40
2,Swift中不会进行变量的隐式转换,如果需要转换类型,须以“待转换变量”声明一个“目标变量”的实例。
let label = “The width is " let width = 94 let widthLabel = label + String(width)
Swift提供了一种更为简洁的转换String类型的方法,将上文中的“String”用反斜线“\”代替。
let label = “The width is " let width = 94 let widthLabel = label + \(width)
3,Swift中声明数组和字典的方法:
使用”[]”进行声明,数组中value之间用逗号”,”分隔;字典中key与value之间用冒号”:”分割,key:value对之间用逗号”,”分割。可以使用下标或者key值访问对应的value。
允许最后一个value或key:value之后有一个逗号。
var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations"
若需要申明空数组或者空字典,有对应的初始化语法:
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
若数组和字典的数据类型可以由编译器推断出,如函数传值等,也可以用下列方法申明空数组or空字典:
shopList = []
occupations = [:]