技术文章分类(180)

技术随笔(11)

swift的语法小demo3(枚举)

 

//
//  main.swift
//  SwiftGrammarStudy
//
//  Created by dongway on 14-6-6.
//  Copyright (c) 2014年 dongway. All rights reserved.
//

import Foundation
/*
    枚举
*/
enum Rank: Int {
    case Ace = 1
    case Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King
    func simpleDescrition() -> String {
        //注意枚举这里的switch语法
        switch self {
        case .Ace:
            return "ace"
        case .Jack:
            return "jack"
        case .Queen:
            return "queen"
        case .King:
            return "king"
        default:
            return String(self.toRaw())
        }
    }
}
let ace = Rank.Ace  //by gashero
let aceRawValue = ace.toRaw()//返回Ace所在的行
let value = Rank.Three.toRaw()
println("1:\(ace)")
println("1:\(aceRawValue)")
println("1:\(value)")
if let convertedRank = Rank.fromRaw(1){
    let threeDesc = convertedRank.simpleDescrition()
    println("1:\(threeDesc)")
}
println("1:\(Rank.Jack.simpleDescrition())")


enum Suit {
    case Spades, Hearts, Diamonds, Clubs
    func simpleDescription() -> String {
        switch self {
        case .Spades:
            return "spades"
        case .Hearts:
            return "hearts"
        case .Diamonds:
            return "dismonds"
        case .Clubs:
            return "clubs"
        }
    }
}

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescrition()) of \(suit.simpleDescription())"
    }
}
let threeOfSpades:Card = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
println("2:\(threeOfSpadesDescription)")

 

posted @ 2014-06-08 11:24  坤哥MartinLi  阅读(143)  评论(0编辑  收藏  举报