Swift-1-基本概念

// Playground - noun: a place where people can play

// 通过代码快速了解swift常用知识,需要一定object-c基础 import UIKit // 声明常量
let maximumNumberOfAttemps = // 声明变量
var currentLoginAttempt = // 同时声明多个常量/变量
var x = 0.0, y = 1.0, z = 2.0
let a = 0.0, b = 1.0, c = 2.0 // 注意: 如果一个值不应该被改变,应该声明为let。如果一个值可以被改变,必须声明为var // 类型标注 type annotations
var welcomMessage : String // 声明一次类型为String的变量welcomeMessage println("\(x) is in line : \(__LINE__) \nfile: \(__FILE__)") // 整型与浮点型转换
let three =
let pointOneFourOneFive = 0.1415
let pi = Double(three) + pointOneFourOneFive
let pb = three + Int(pointOneFourOneFive) // typealias
typealias CustomInt16 = Int16
var ci : CustomInt16 = // boolean
let rightIsRight = true
if rightIsRight {
println("right thing")
} let i =
if i { // Error: Type 'Int' does not conform to protocol 'BooleanType'
// 不能使用非Bool值作为判断依据
} // Tuples 元组
let http404Error = (, "Not Found") // (Int, String)类型的元组 // 分解元组[读取元组中的值]
// 方式1
let (statusCode, statusMessage) = http404Error
println("the status code is \(statusCode), And the statusMessage is \(statusMessage)")
// 忽略读取某些内容,忽略的部分用 _ 代替
let (statusCode2, _) = http404Error
println("the status code 2 is \(statusCode2)") // 方式2 : 直接通过索引来读取
let statusCode3 = http404Error.
println("the status code 3 is \(statusCode3)") // 方式3 : 为元组中元素命名,通过元素名称直接获取
let http404Error2 = (code : , message : "Not Found")
let statusCode4 = http404Error2.code
println("the status code is \(statusCode4)") // 注意:元组在临时将多个值组织到一起时很有用,但是不适合用来创建复杂的数据结构。如果你的数据结构不是临时使用,应该使用类或者结构体 // 可选值 optional : 使用可选来表示值可能为空的情况.
// nil : 只能赋值给可选类型。如果一个常量或者变量在特定的情况下需要表示值缺失,那么它必须声明为可选值
var serverResponseCode: Int? = // 如果没有初始值404,则该变量默认初始值为nil
serverResponseCode = nil // OC中nil是一个指向不存在对象的指针,swift中nil表示一个已确定类型的变量值缺失,任何可选值都可以被设为nil。 // optional解包:使用!对optional值进行强制解包,如果optional值为nil,则会发生错误,所以强制解包前一定要确保optional值不为nil
if serverResponseCode != nil {
println("serverResponseCode contains some non-nil value")
} // 可选绑定[optional binding]
if let code = serverResponseCode { // if serverResponseCode != nil, let code = serverResponseCode!
println("serverResponseCode contains some non-nil value of \(code)")
} else {
println("serverResponseCode is nil")
} // 隐式解析可选值 : 与普通 ? 可选值 区别在于可以直接访问,不用进行强制解析。但是被设置隐式解析的变量在每次访问时必须有值(非nil),否则会出现运行时错误
let possibleString : String? = "a possible string"
let forcedString = possibleString! // 必须加 !进行强制解析 let assumingString : String! = "an implicitly unwrapped optional string."
let implicitString = assumingString // 不需要 ! 进行强制解析
// 注意:如果一个变量可能为nil,那么应该始终设置成可选,而不是隐式解析的可选值。 // 断言 assert (与OC中NSAssert一致)
let age = -
assert(age >= , "A person's age connot be less than zero") // 会自动打印出 file line
上一篇:2-Twenty First Scrum Meeting-20151221


下一篇:Ubuntu 下配置ftp服务端