码迷,mamicode.com
首页 > 其他好文 > 详细

可选链

时间:2016-02-05 18:49:27      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

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

import Foundation

/*
可选链:
1.可选链访问方式:将强制解析的感叹号换成?, 在隐式解析的后面也添加?
2.可选链会自动判断程序访问的关联实例是否为nil, 即使为nil, 也不会报异常
*/

class Person
{
    var name:String?
    var age: Int?
    
    init(name:String)
    {
        self.name = name
    }
    
    func info()
    {
        print("我的名字是:\(self.name!)")
    }
}

class Company
{
    var employees = [
        Person(name: "Rinpe"),
        Person(name: "Lili"),
        Person(name: "Lolo")
    ]
    
    func isEmployee(name:String) -> Person?
    {
        for employee in employees {
            if name == employee.name
            {
                return employee
            }
        }
        return nil
    }
}

var e = Person(name: "Lala")

let company = Company()
company.isEmployee(e.name!)?.age = 10

 

可选链

标签:

原文地址:http://www.cnblogs.com/Rinpe/p/5183138.html

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