寒城攻略:Listo 教你 25 天学会 Swift 语言 - 21 Nested Types

前端之家收集整理的这篇文章主要介绍了寒城攻略:Listo 教你 25 天学会 Swift 语言 - 21 Nested Types前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

//***********************************************************************************************

//1.Nested Types(类型嵌套)

//_______________________________________________________________________________________________

//介绍

//枚举类型常被用于实现特定类或者结构体的功能。我们可以在多种变量环境中方便的定义通用的结构体或者类,Swift 支持枚举,类,结构体为支持嵌套类型

//***********************************************************************************************

//2.Nested Types in Action(类型嵌套实例)

struct BlackjackCard {

// nested Suit enumeration

enum Suit: Character {

case Spades = "♠",Hearts = "♡",Diamonds = "♢",Clubs = "♣"

}

// nested Rank enumeration

enum Rank: Int {

case Two = 2,Three,Four,Five,Six,Seven,Eight,Nine,Ten

case Jack,Queen,King,Ace

struct Values {

let first: Int,second: Int?

}

var values: Values {

switch self {

case .Ace:

return Values(first: 1,second: 11)

case .Jack,.Queen,.King:

return Values(first: 10,second: nil)

default:

return Values(first: self.rawValue,second: nil)

}

}

}

// BlackjackCard properties and methods

let rank: Rank,suit: Suit

var description: String {

var output = "suit is \(suit.rawValue),"

output += " value is \(rank.values.first)"

if let second = rank.values.second {

output += " or \(second)"

}

return output

}

}


let theAceOfSpades = BlackjackCard(rank: .Ace,suit: .Spades)

println("the AceOfSpades: \(theAceOfSpades.description)") //尽管 Rank Suit 嵌套在 BlackjackCard ,但仍可被引用,所以在初始化实例时能够通过枚举类型中的成员名称(.Ace .Spades)单独引用


//3.Referring to Nested Types(类型嵌套的引用)

//_______________________________________________________________________________________________

//实例代码演示类型嵌套的引用

//在外部对嵌套类型的引用,是以被嵌套类型的名字为前缀,加上所要引用的属性

let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue

println(heartsSymbol)


转载:http://blog.csdn.net/u013096857/article/details/37872173
原文链接:https://www.f2er.com/swift/327569.html

猜你在找的Swift相关文章