码迷,mamicode.com
首页 > 编程语言 > 详细

Swift Tour 随笔总结 (3)

时间:2015-01-22 14:46:12      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

关于Optional的Control Flow

if let constantName = someOptional {

    statements

}

如果该Optional为nil,则不进入if,否则执行且constantName为该Optional的值

例子:

if let actualNumber = possibleNumber.toInt() {

    println(“\(possibleNumber) has an integer value of \(actualNumber)”)

} else {

    println(“\(possibleNumber) could not be converted to an integer”)

}

// prints “123 has an integer value of 123”

关于nil

optional可以被赋值为nil

例如:

var serverResponseCode: Int? = 404

serverResponseCode = nil

 

var surveyAnswer: String?

// surveyAnswer is automatically set to nil

 

optional的拓展:Implicitly Unwrapped Optionals

有的时候,一个optional在第一次赋值之后将是安全的,不用做nil检查

定义:String! 而不是 String?

举例:

let possibleString: String? = “An optional string.”

println(possibleString!) //  requires an exclamation mark to access this value

// prints “An optional string.”

 

let assumedString: String! = “An implicitly unwrapped optional string.”

println(assumedString) // no exclamation mark is needed to access its value

// prints “An implicitly unwrapped optional string.”

 

对于这种特殊类型(IUO),适用普通optional用法:

if assumedString {

println(assumedString)

}

 

Assertions – debugging中发现问题后的中断

let age = –3

assert(age >= 0, “A person’s age cannot be less than zero”)

// assertion trigger

Swift Tour 随笔总结 (3)

标签:

原文地址:http://www.cnblogs.com/zhjch/p/4241353.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!