Swift第六课枚举,枚举中定义方法,结构体

来源:互联网 发布:java 退出递归 返回值 编辑:程序博客网 时间:2024/06/04 19:26

1: 枚举
枚举定义了一种包含一组相关值的公共类型。枚举是Swift中的一种与类类似的类型。

Swift 语言的枚举类型的定义语法:
enum point { //可以指定枚举的类型 enum CompassPoint :Int { case North}
case North
case South
case East
case West
case Two = 1, Three, Four, Five, Six, Seven, Eight, Nine, Ten //枚举可以定义到一行中,枚举类型可以自动加1、

func simpleDescription() -> String { //枚举中可以定义方法    return "这是枚举方法"}

}

point.North.hashValue //返回枚举对应的原始值。

使用 enum 来创建一个枚举。就像类和其他所有命名类型一样,枚举可以包含方法,用case关键字来指示一个新的枚举成员值,每个新定义的枚举都属于一种新的独立的类型。

1.2:枚举的使用
var direc = point.North
direc = .East //可以省略枚举类型名称
switch direc { //direc 为枚举类值变量

    case .North:        println("North")    case .South:        println("South")    case .East:        println("East")    case .West:        println("West")    }

枚举能为每个成员定义不同类型的值

enum changeEnum { //定义一个名为changeEnum的枚举,str的值类型为String,count的值类型为Int
case str(String)
case count(Int)
}
为每一个不同类型枚举成员赋值
var changeValue = changeEnum.str(“23233”)
var changeCountValue = changeEnum.count(1212)

enum network { //枚举中定义方法

case errorprivate func description() ->String {    return "枚举方法"}static func getName(type:String) -> String{    return type}

}

network.getName(“abc”) //相当于类的静态方法,用枚举名称调用。
network.error.description() //相当于对象方法,用对象调用。

2:结构体

使用 struct 来创建一个结构体。结构体和类有很多相同的地方,比如方法和构造器。它们结 构体之间最大的一个区别就是 结构体是传值,类是传引用。

struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return “The (rank.simpleDescription()) of \ (sui t.sim pleD escri ption ())”
}
}

let threeOfSpades = Card(rank: .Thre e, suit: . Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()

0 0