码迷,mamicode.com
首页 > 移动开发 > 详细

iOS二次发育(swift)枚举

时间:2017-09-11 21:18:33      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:col   can   ace   point   cas   erro   oct   logs   sid   

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

import UIKit


//Raw Value
enum Month: String{
    case January = "Value_January"
    case February = "Value_February"
    case March = "Value_March"
    case April = "Value_April"
    case May = "Value_May"
    case June = "Value_June"
    case July = "Value_July"
    case August = "Value_August"
    case September = "Value_September"
    case October = "Value_October"
    case November = "Value_November"
    case December = "Value_December"
}
func season(month: Month ) -> String{
    switch month {
    case .January:
        return month.rawValue
    default:
        return ""
    }
}

season(month: Month.January)
print(Month.April)

if let july = Month(rawValue: "Value_July"){
   print(july)
}


//Associate Value

//例1
enum ATMStatus{
    case Success(Int)
    case Error(String)
    case Waiting
}

var balance = 1000
func withdraw( amount: Int ) -> ATMStatus{
    if amount <= balance {
        balance -= amount
        return .Success(balance)
    } else {
        return .Error("Not enough money")
    }
}
let result = withdraw(amount: 800)
switch result {
    case let .Success(newBalance):
        print("\(newBalance) Yuan Left in your account.")
    case let .Error(errorMessage):
        print("error:\(errorMessage)")
    case .Waiting:
        print("Waiting")
}

switch result {
    case .Success:
        print("Success")
    case .Error:
        print("Error")
    case .Waiting:
        print("Waiting")
}

//例2
enum Shape{
    case Square(side: Double)
    case Rectangle(width: Double, height: Double)
    case Circle(centerX: Double, centerY: Double, radius: Double)
    case Point
}
let square = Shape.Square(side: 10)
let rectangle = Shape.Rectangle(width: 20, height: 30)
let circle = Shape.Circle(centerX: 0, centerY: 0, radius: 15)
let point = Shape.Point

func area(shape: Shape) -> Double{
    switch shape {
    case let .Square(side):
        return side * side
    case let .Rectangle(width, height):
        return width * height
    case let .Circle(_, _, r):
        return M_PI * r * r
    case .Point:
        return 0
    }
}
area(shape: square)
area(shape: rectangle)
area(shape: circle)
area(shape: point)

 

iOS二次发育(swift)枚举

标签:col   can   ace   point   cas   erro   oct   logs   sid   

原文地址:http://www.cnblogs.com/liuguan/p/7506424.html

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