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

Option可选值(一)

时间:2015-07-01 18:31:26      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:可选值   option   

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


import Cocoa


class Person {

   var residence: Residence?//供选连接

}

class Residence {

   var rooms = [Room]()

   var numberOfRooms:Int {

       return rooms.count

    }

    subscript(i:Int) ->Room {

       return rooms[i]

    }

    

   func printNumberOfRooms() {

        println("The number of rooms is\(numberOfRooms)")

    }

    

   var address: Address?

}


class Room {

   let name: String

   init(name: String) {

       self.name = name

    }

}

class Address {

   var buildingName:String?

   var buildingNubmer:String?

   var street: String?

    

   func buildingIdentifier() ->String? {

       if (buildingName !=nil) {

           return buildingName

        }else if (buildingNubmer != nil) {

            returnbuildingNubmer

        }else {

           return nil

        }

    }

}

let john =Person()

//let johnsHouse = Residence()

//johnsHouse.rooms[0] = Room(name: "Living Room")

//john.residence = johnsHouse

/*

你可以将多层供选链接连接在一起,可以掘取模型内更下层的属性方法和角标。然而多层供选链接不能再添加比已经返回的供选值更多的层。 也就是说:

如果你试图获得类型不是供选类型,由于供选链接它将变成供选类型。如果你试图获得的类型已经是供选类型,由于供选链接它也不会提高供选性。因此:

如果你试图通过供选链接获得 Int ,不论使用了多少层链接返回的总是 Int?相似的,如果你试图通过供选链接获得 Int?,不论使用了多少层链接返回的总是 Int?

*/

let johnsAddress =Address()

johnsAddress.buildingName ="The"

johnsAddress.street ="Laurel"

john.residence!.address =johnsAddress

//链接供选返回值的方法

//if let buildingIdentifier = john.residence?.address?.buildingIdentifier()?.uppercaseString {

//    println("John‘s building identifier is \(buildingIdentifier).")

//}


//连接多层链接

//if let johnsStreet = john.residence?.address?.street {

//    println("John‘s street name is \(johnsStreet).")

//} else {

//    println("Unable to retrieve the address.")

//}

//使用供选链接调用角标

//if let firstRoomName = john.residence?[0].name {

//    println("The first room name is \(firstRoomName).")

//} else {

//    println("Unable to retrieve the first room name.")

//}























版权声明:本文为博主原创文章,未经博主允许不得转载。

Option可选值(一)

标签:可选值   option   

原文地址:http://blog.csdn.net/wa1065908163/article/details/46710951

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