Swift 學習之二十一:?和 !(詳解)

來源:互聯網
上載者:User

標籤:

http://blog.csdn.net/woaifen3344/article/details/30244201

Swift語言使用var定義變數,但和別的語言不同,Swift裡不會自動給變數賦初始值,

也就是說變數不會有預設值,所以要求使用變數之前必須要對其初始化

。如果在使用變數之前不進行初始化就會報錯:

 

[plain] view plaincopyprint? 
  1. var stringValue : String   
  2. //error: variable ‘stringValue‘ used before being initialized  
  3. //let hashValue = stringValue.hashValue  
  4. //                            ^  
  5. let hashValue = stringValue.hashValue  


出錯的原因就是在使用stringValue這個變數之前,沒有初始化這個變數,也就是這個變數根本就沒有得到記憶體,

 

這時就會出錯。

那麼我們可以使用optional類型,後面跟一個?就是了。

 

[plain] view plaincopyprint? 
  1. // 這就是optional, strValue自動得到預設值:nil   
  2. // 這個nil跟Objective-C中的nil不同,不是指標,而是表示值不存在。  
  3. var strValue: String?   
  4.   
  5. // 判斷optional是否有值  
  6. if strValue {  
  7.  // do what you need to do here  
  8. }  

 

 

文檔中有提到說,在使用Optional值的時候需要在具體的操作,比如調用方法、屬性、下標索引等前面需要加上一個?,如果是nil值(不存在值),也就是Optional.None,會跳過後面的操作不執行,如果有值,就是Optional.Some可能就會拆包(unwrap),然後對拆包後的值執行後面的操作,來保證執行這個操作的安全性,比如Optional binding:

 

[plain] view plaincopyprint? 
  1. // optional binding  
  2. // 如果strValue == nil, 那麼結果就是nil,不會調用String的hasValue  
  3. // 如果strValue != nil, 就返回strValue對應的hashValue值並賦值給常量hashValue  
  4. if let hashValue = strValue?.hashValue {  
  5.   // do something if neccessary  
  6. }  


在寫協議(protocol)時,對於可選代理方法,也需要在調用時在函數名後跟著?,如:

 

 

[plain] view plaincopyprint? 
  1. // @objc 是用於處理Swift與OC之間的轉換的,由於@optional是OC中的關鍵字,  
  2. // 所以在protocol之前需要添加上@objc。  
  3. @objc protocol HttpRequestDelegate {  
  4.   // @optional 說明這個代理方法是可選方法,  
  5.   // 那麼在調用的時候,需要這樣調用:delegate?.requestFinished?(self, downloadData)  
  6.   // 其中delegate?是因為delegate也是optional的  
  7.   @optional func requestFinished(request: HttpRequest!, downloadData: NSMutableData!)  
  8.     
  9.   // other funcs ...  
  10. }  
  11.   
  12. var delegate: HttpRequestDelegate?  
  13. var downloadData = NSMutableData()  
  14. delegate.requestFinished(self, downloadData)  

 

 

當然我們也可以使用!來強制拆包,這是我們在保證有值的情況下才會這麼用:

 

[plain] view plaincopyprint? 
  1. var strValue: String?  
  2. strValue = "1234"  
  3.   
  4. let integer = strValue!.toInt()  
  5. // 更安全的寫法是  
  6. if strValue {  
  7.   let integer = strValue!.toInt()  
  8. }  

 


隱式強拆包類型:

使用!來聲明變數,會成為隱式強拆包可選類型,這表示這個類型永遠不會出現nil的情況,但一旦出來,

在調用時就會崩潰。

 

[plain] view plaincopyprint? 
  1. // Implicitly Unwrapped Optionals  
  2. // 使用這種方式聲明的話,在調用時不需要使用?或!來說明。  
  3. var myLabel: UILabel!   
  4.   
  5. myLabel = UILabel(frame: CGRectMake(10, 100, 300, 10))  
  6. myLabel.text = "label"  



總結:

 

通常在什麼情況下才會使用optional類型呢?

(1)當我們需要聲明這樣一個變數,變數在設計初始化函數中沒有進行初始化時,就需要聲明這個變數為optional類型。因為變數在使用前必須先

        聲明,並且在設計初始化函數中進行初始化。比如我們在viewDidLoad函數中才進行初始化的控制項(類成員),就需要聲明為optional且必須是var聲明,

       因為let聲明的常量只能是在初始化函數中進行初始化。

(2)當我們不知道是否會有值的時候,這個變數可以聲明為optional,比如代理,我們並沒有要求必須傳代理過來,那麼就需要聲明為optional。

(3)作為函數參數時,如果這個參數可以沒有值,那麼就使用optional類型,比如傳代理的時候,通常就是可選的,可以設定為nil

......暫時只想到這些,任何人都可以繼續往下補充!

 



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Swift 學習之二十一:?和 !(詳解)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.