swift 类型php
用let来声明常量,用var来声明变量
能够在一行中声明多个常量或者多个变量,用逗号隔开swift
var x = 0.0, y = 0.0, z = 0.0
Swift 是一个类型安全(type safe)的语言。类型安全的语言可让你清楚地知道代码要处理的值的类型。
一个变量是什么类型,经过两种方式来表达:数组
var welcomeMessage: String
注意:当推断浮点数的类型时,Swift 老是会选择Double而不是Float。通常来讲你不多须要写类型标注。若是你在声明常量或者变量的时候赋了一个初始值,Swift能够推断出这个常量或者变量的类型xcode
println是一个用来输出的全局函数,输出的内容会在最后换行。
xcode的playground使用println,点击工具条的show the Assistant editor.即能显示输出安全
var str = "Hello, playground" println(str)
SomeType(ofInitialValue)是调用 Swift 构造器并传入一个初始值的默认方法。
注意,你并不能传入任意类型的值,只能传入SomeType内部有对应构造器的值。
不过你能够扩展示有的类型来让它能够接收其余类型的值(包括自定义类型)
不一样整数类型的变量和常量能够存储不一样范围的数字,若是数字超出了常量或者变量可存储的范围,编译的时候会报错:数据结构
let cannotBeNegative: UInt8 = -1 // UInt8 类型不能存储负数,因此会报错 let tooBig: Int8 = Int8.max + 1 // Int8 类型不能存储超过最大值的数,因此会报错 let twoThousand: UInt16 = 2_000 let one: UInt8 = 1 //在语言内部,UInt16有一个构造器,能够接受一个UInt8类型的值,因此这个构造器能够用现有的UInt8来建立一个新的UInt16 let twoThousandAndOne = twoThousand + UInt16(one)
类型别名(type aliases)就是给现有类型定义另外一个名字。你可使用typealias关键字来定义类型别名。app
typealias AudioSample = UInt16 var maxAmplitudeFound = AudioSample.min // maxAmplitudeFound 如今是 0
可使用断言来保证在运行其余代码以前,某些重要的条件已经被知足。
若是条件判断为true,代码运行会继续进行;若是条件判断为false,代码运行中止,你的应用被终止。less
let age = -3 assert(age >= 0, "A person's age cannot be less than zero") // 由于 age < 0,因此断言会触发,代码运行中止,应用被终止
能够作调试使用函数
Swift 提供了8,16,32和64位的有符号和无符号整数类型。
Swift 提供了一个特殊的整数类型Int,长度与当前平台的原生字长相同:工具
Swift 也提供了一个特殊的无符号类型UInt,长度与当前平台的原生字长相同:
尽可能不要使用UInt,除非你真的须要存储一个和当前平台原生字长相同的无符号整数。
除了这种状况,最好使用Int,即便你要存储的值已知是非负的。
统一使用Int能够提升代码的可复用性,避免不一样类型数字之间的转换,而且匹配数字的类型推断
Swift 有两个布尔常量,true和false:
let orangesAreOrange = true let turnipsAreDelicious = false
Swift 的String类型表示特定序列的Character(字符)类型值的集合,不能用下标取
for character in "Dog!🐶" { println(character) } let yenSign: Character = "¥"
字符窜链接经过+号将两个字符窜相连
var emptyString = "" // 空字符串字面量 var anotherEmptyString = String() // 初始化 String 实例 emptyString == anotherEmptyString //true if emptyString.isEmpty { println("什么都没有") } let string1 = "hello" let string2 = " there" let character1: Character = "!" let character2: Character = "?" let stringPlusCharacter = string1 + character1 // 等于 "hello!" let stringPlusString = string1 + string2 // 等于 "hello there" let characterPlusString = character1 + string1 // 等于 "!hello" let characterPlusCharacter = character1 + character2 // 等于 "!?"
字符串插值是一种构建新字符串的方式,能够在其中包含常量、变量、字面量和表达式。
let multiplier = 3 let message = "\(multiplier) 乘以 2.5 是 \(Double(multiplier) * 2.5)"
插值字符串中写在括号中的表达式不能包含非转义双引号 (") 和反斜杠 (\),而且不能包含回车或换行符。 插值能够省去额外的加号进行表达式的链接
数组按顺序存储相同类型的数据
声明数组
var shoppingList: String[] = ["Eggs", "Milk"] var shoppingList = ["Eggs", "Milk"] var someInts = Int[]() var threeDoubles = Double[](count: 3, repeatedValue:0.0)// [0.0, 0.0, 0.0] var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)//类型推断[2.5, 2.5, 2.5]
添加数据,修改数据,读取数据,删除数据,
//添加数据 shoppingList.append("Flour") shoppingList += "Baking Powder" shoppingList += ["Chocolate Spread", "Cheese", "Butter"] shoppingList.insert("Maple Syrup", atIndex: 0) //修改数据 shoppingList[0] = "aaa" shoppingList[4...6] = ["Bananas", "Apples"]//区间操做符,不能越界想数组尾部添加数据 //读取数据 var firstItem = shoppingList[0] for item in shoppingList { println(item) } //全局enumerate函数来进行数组遍历。enumerate返回一个由每个数据项索引值和数据值组成的元组 for (index, value) in enumerate(shoppingList) { println("Item \(index + 1): \(value)") } //删除数据 shoppingList.removeAtIndex(0) let apples = shoppingList.removeLast() someInts = [] //重置未空数组
无序存储相同类型数据值可是须要由独有的标识符引用和寻址(就是键值对)
声明字典
var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"] var airports = ["TYO": "Tokyo", "DUB": "Dublin"] var namesOfIntegers = Dictionary<Int, String>()ßß
读取字典和修改字典数据,删除字典数据(使用nil)
airports.updateValue("Dublin Internation", forKey: "DUB") airports["APL"] = "Apple Internation" airports["APL"] = nil // APL如今被移除了 airports.removeValueForKey("DUB") namesOfIntegers = [:]//重置为空字典
字典遍历,Swift 的字典类型是无序集合类型。其中字典键,值,键值对在遍历的时候会从新排列,并且其中顺序是不固定的。
//注意这里没有使用enumerate for (airportCode, airportName) in airports { println("\(airportCode): \(airportName)") } for airportCode in airports.keys { println("Airport code: \(airportCode)") } for airportName in airports.values { println("Airport name: \(airportName)") } //使用字典建立数组 let airportCodes = Array(airports.keys) let airportNames = Array(airports.values)
元组取下标使用.操做符..数组和字典取下标使用[];
声明元组
var http404Error = (404, "Not Found") //默认下标0,1 var http200Status = (statusCode: 200, description: "OK")//默认下标依然存在
访问元组
println(http404Error.0); println(http200Status.0); println(http200Status.statusCode);
分解元组,若是你只须要一部分元组值,分解的时候能够把要忽略的部分用下划线(_)标记
let (statusCode, statusMessage) = http404Error let (justTheStatusCode, _) = http404Error
元组很像php中的数组.可是swift是类型安全的.因此若是初始化下标和值后,而后再次赋不一样的下标或者不一样类型的值,则会报错.
http200Status = ("ddd","dddd"); //错误
元组在临时组织值的时候颇有用,可是并不适合建立复杂的数据结构。若是你的数据结构并非临时使用,请使用类或者结构体而不是元组。
要么为nil,要么有值等于x.
声明可选类型
var optional:Int? //值为nil let possibleNumber = "123" let convertedNumber = possibleNumber.toInt() // convertedNumber 被推测为类型 "Int?", 或者类型 "optional Int"
可选类型的变量不能直接使用,须要先判断其确实有值,而后使用!解析,注意!号是放在变量名后面,放在前面是表明操做符 否的意思
因为使用!来获取一个不存在的可选值会致使运行时错误。使用!来强制解析值以前,必定要肯定可选包含一个非nil的值。因此最好使用if进行判断
if convertedNumber { println("\(possibleNumber) has an integer value of \(convertedNumber!)") } else { println("\(possibleNumber) could not be converted to an integer") }
可选绑定语句,能够省略解析!.可选绑定能够用在if和while语句中来对可选类型的值进行判断并把值赋给一个常量或者变量。
if let actualNumber = possibleNumber.toInt() { // println("\(possibleNumber) has an integer value of \(actualNumber)") } else { println("\(possibleNumber) could not be converted to an integer") }
隐式解析可选类型是一个能够自动解析的可选类型。你要作的只是声明的时候把感叹号放到类型的结尾,而不是每次取值的可选名字的结尾。
let possibleString: String? = "An optional string." println(possibleString!) // 须要惊叹号来获取值 let assumedString: String! = "An implicitly unwrapped optional string." println(assumedString) // 不须要感叹号 // 输出 "An implicitly unwrapped optional string."
除了不用使用!强制解析外,其余的和可选类型同样. 一样若是你在隐式解析可选类型没有值的时候尝试取值,会触发运行时错误。和你在没有值的普通可选类型后面加一个惊叹号同样。
if assumedString { println(assumedString) } // 输出 "An implicitly unwrapped optional string." if let definiteString = assumedString { println(definiteString) } // 输出 "An implicitly unwrapped optional string."