互联网科技iOS Developer首页投稿(暂停使用,暂停投稿)

Swift中的可选类型(Optional Type)

2017-03-06  本文已影响130人  鱼与愚七

Optional Type总览

var string1: String = "This is string1" // OK
string1 = nil  // Nil cannot be assigned to type 'String'
class MyClass { 
    var name: String = "Lv"
    var age: String  // Class 'MyClass' has no initializers
}
NSString *string1 = @"This is string1";
string1 = nil;

class MyClass { 
    NSString *name = @"Lv"
    NSString *age;
}
class MyClass {
    var name: String?  // OK
    var age: String?  // OK
}

为什么引入可选类型?

- (NSString *)findStockCode:(NSString *)company {
    if ([company isEqualToString:@"Apple"]) {
        return @"AAPL";
    } else if ([company isEqualToString:@"Google"]) {
        return @"GOOG";
    }
    return nil;
}
NSString *stockCode = [self findStockCode:@"Facebook"]; // nil is returned
NSString *text = @"Stock Code - ";
NSString *message = [text stringByAppendingString:stockCode]; // runtime error
NSLog(@"%@", message);
func findStockCode(company: String) -> String? {
   if (company == "Apple") {
      return "AAPL"
   } else if (company == "Google") {
      return "GOOG"
   }
   return nil
}

var stockCode:String? = findStockCode("Facebook")
let text = "Stock Code - "
let message = text + stockCode  // compile-time error
print(message)

解包可选类型(Unwrapping Optionals)

var stockCode:String? = findStockCode("Facebook")
let text = "Stock Code - "
if stockCode {
    let message = text + stockCode!
    print(message)
}
var stockCode:String? = findStockCode("Facebook")
let text = "Stock Code - "
let message = text + stockCode!  // runtime error

可选绑定(Optional Binding)

var stockCode:String? = findStockCode("Facebook")
let text = "Stock Code - "
if let tempStockCode = stockCode {
    let message = text + tempStockCode
    print(message)
}
let text = "Stock Code - "
if var stockCode = findStockCode("Apple") {
    let message = text + stockCode
    print(message)
}

可选链式调用(Optional Chaining)

class Stock {
    var code: String? 
    var price: Double? 
}

func findStockCode(company: String) -> Stock? {
    if (company == "Apple") {
        let aapl: Stock = Stock()
        aapl.code = "AAPL"
        aapl.price = 90.32
        return aapl
            
    } else if (company == "Google") {
        let goog: Stock = Stock()
        goog.code = "GOOG"
        goog.price = 556.36
        return goog
    }
    return nil
}
if let stock = findStockCode("Apple") {
    if let sharePrice = stock.price {
        let totalCost = sharePrice * 100
        print(totalCost)
    }
}
if let sharePrice = findStockCode("Apple")?.price {
    let totalCost = sharePrice * 100
    print(totalCost)
}

Swift和Objective-C的互通性

func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
   // Return the number of sections.
   return 1
}

func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
   // Return the number of rows in the section.
   return recipes.count
}
    

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
   let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
   
   cell.textLabel.text = recipes[indexPath.row]
   
   return cell
}

总结

上一篇下一篇

猜你喜欢

热点阅读