设为首页 加入收藏

TOP

Swift Optional(一)
2017-10-09 14:22:59 】 浏览:1906
Tags:Swift Optional

拆包和解包的原因:

  其实所谓的 nil 就是 Optional.None, 非 nil 就是Optional.Some, 然后会通过Some(T)包装(wrap)原始值,这也是为什么在使用 Optional 的时候要拆包(从 enum 里取出来原始值)的原因, 也是 PlayGround 会把 Optional 值显示为类似 {Some "hello world"}的原因.

1.swift ?和 !的区别

  1.1 Swift语言使用var定义变量,但和别的语言不同,Swift里不会自动给变量赋初始值,也就是说变量不会有默认值,所以要求使用变量之前必须要对其初始化。如果在使用变量之前不进行初始化就会报错:

1 var stringValue : String 
2 //error: variable 'stringValue' used before being initialized
3 //let hashValue = stringValue.hashValue
4 let hashValue = stringValue.hashValue

  若在一个视图控制器中 class xxxController

 1 class AdjustFontViewController: UIViewController{    //报错error: Class 'xxxx' has no initializers  
 2 //Fix-it Stored property 'stringValue' without initial value prevents synthesized initalizers
 3 
 4 var stringValue: String
 5 
 6 }
 7 
 8 //    修改为:
 9 //    当我们不知道变量的值时,可以将改变量设置为可选类型
10 var stringValue: String?  
11 
12 
13 
14 //    表明str是可选类型(是string类型或者nil类型)  
15 var value: String?="hello world"  
16 //value = value?.uppercaseString  
17         
18 //    拆包  
19       if let unwrappedStr = value{  
20           print("拆包:\(unwrappedStr.uppercaseString)")     //如果value(有值,将值复制给常量unwrappedStr)  
21       }  
22       else  
23       {  
24           print("value是nil")    //str不赋初始值时  
25       }  
26        
27 //    确定value有存在的值(如果str没有被赋实际意义的值,强制拆包将造成应用程序崩溃)  
28       print(" 拆包:\(str!.uppercaseString)")  
29  
30 
31 
32 //    两种拆包方式       
33 //    1.隐性拆包  
34       var str1:String! = "hello world"    //已经确定变量str1是有值的(如果未赋值,应用程序将崩溃)  
35       str1 = str1.lowercaseString  
36       print("拆包:\(str1)")  
37         
38       print(str)  
39         
40 //    2.显性拆包
41       var str2:String?="Hello World"  
42       let lowerStr2 = str2?.lowercaseString//lowerStr2是可选的,如果有值,则值为“hello world”否则为nil 
43 
44 
45 
46 
47                       

 

 

 

  1.2 上面了解到的是普通值,接下来Optional值要上场了。

    Optional其实是个enum,里面有None和Some两种类型。其实所谓的nil就是Optional.None, 非nil就是Optional.Some, 然后会通过Some(T)包装(wrap)原始值,这也是为什么在使用Optional的时候要拆包(从enum里取出来原始值)的原因, 也是PlayGround会把Optional值显示为类似{Some "hello world"}的原因,这里是enum Optional的定义:

 1 enum Optional<T> : LogicValue, Reflectable {
 2     case None
 3     case Some(T)
 4     init()
 5     init(_ some: T)
 6 
 7     /// Allow use in a Boolean context.
 8     func getLogicValue() -> Bool
 9 
10     /// Haskell's fmap, which was mis-named
11     func map<U>(f: (T) -> U) -> U?
12     func getMirror() -> Mirror
13 }

1.2.1  ?的几种使用场景:

a. 声明 Optional 值为可选变量

b. 用在对 Optional 值操作中,用来判断是否能响应后面 的操作

c. 用于安全调用 protocol 的 optional 方法

d. 使用 as? 向下转型(Downcast)

 

a. Optional 可选值 

 定义变量时,如果指定是可选的,表示该变量可以有一个指定类型的值,也可以是 nil

 定义变量时,在类型后面添加一个 ?,表示该变量是可选的

 变量可选项的默认值是 nil

 1 //n1 = nil  //编译错误
 2 
 3 //let str: String = nil   //编译错误
 4   
 5    
 6  var n2 : Int? = 10
 7  
 8  print("-----n2=\(String(describing: n2))")
 9  
10  n2 = nil
11  
12  print("-----n2=\(String(describing: n2))")
13 
14 
15  let str: String! = nil
16 
17  print("-----str=\(str)")
18  

 

 常量可选项没有默认值,主要用于在构造函数中给常量设置初始数值

声明为Optional只需要在类型后面紧跟一个?即可,strValue 是 Optional 的 String。如:

1 var strValue: String?   //?相当于下面这种写法的语法糖
2 var strValue: Optional<Int>

一旦声明为Optional的,如果不显式的赋值就会有个默认值nil。判断一个Optional的值是否有值,可以用if来判断:

if strValue {
    //do sth with strValue
}

 

1.2.2  显示拆包和隐式拆包

 

a.  使用问号(?)声明的可选类型,在拆包时需要使用感叹号(!),这种拆包方式称为“显式拆包”;

 

b. 使用感叹号(!)声明的可选类型,在拆包时可以不使用感叹号(!),这种表示方式称为“隐式拆包”。

 

 1  
 2 
 3 
 4 //  在可选类型的问号(?)或感叹号(!)究竟有
首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Go 时间相关 下一篇尝试在CentOS7.2上编译安装Swift

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目