不错的参考: Enum进阶
使用enum
创建枚举,像类和其他所有类型那样,枚举可以有方法,供访问。
// ViewController.swift
// Swift枚举和结构体
//
// Created by Hunter on 20/01/2017.
// Copyright © 2017 Hunter. All rights reserved.
//
import UIKit
private enum Suit {
case spades, hearts, diamonds, clubs
func simpleDescription() -> String {
switch self {
case .spades:
return "spades,简单描述--simpleDescription"
case .hearts:
return "hearts--simpleDescription"
case .diamonds:
return "diamonds--simpleDescription"
case .clubs:
return "clubs--simpleDescription"
}
}
func color() -> UIColor {
switch self {
case .spades, .clubs:
return UIColor.black
case .diamonds, .hearts:
return UIColor.red
}
}
}
private let hearts = Suit.hearts
private let heartsDescription = hearts.simpleDescription()
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print(hearts,heartsDescription)
view.backgroundColor = Suit.clubs.color()
/*
输出:hearts hearts--simpleDescription
视图的背景颜色为黑色
*/
}
}
再看一个枚举的简单使用
//
// ViewController.swift
// Swift枚举和结构体
//
// Created by Hunter on 20/01/2017.
// Copyright © 2017 Hunter. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
enum serverResponse {
case result(String?, String?)
case failure(String)
func raw() -> AnyObject {
switch self {
case .result:
return ("1", "2") as AnyObject
case .failure:
return ("3" as AnyObject)
}
}
}
let succes = serverResponse.result("日出时间: 8:00 AM", "日落时间: 19: 00 PM")
let failure = serverResponse.failure("失败")
override func viewDidLoad() {
super.viewDidLoad()
serverResponseTest()
print(serverResponse.result(nil,nil).raw())
/*
输出:
日出时间: 8:00 AM 日落时间: 19: 00 PM
("1", "2")
*/
}
func serverResponseTest() {
switch succes {
case let .result(sunrise, sunset):
if let rise: String = sunrise, let set: String = sunset{
print(rise, set)
}
case let .failure(message):
print(message)
}
}
}
结构体同类很相似,它们最大的区别就是一个结构体传值,类传引用.
// ViewController.swift
// Swift枚举和结构体
//
// Created by Hunter on 20/01/2017.
// Copyright © 2017 Hunter. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
struct Person {
var wife: String?
var name: String
var age: Int
func who() -> String {
return ("name:\(name),age:\(age)")
}
}
let xiaoMing = Person.init(wife: nil, name: "小明", age: 28)
override func viewDidLoad() {
super.viewDidLoad()
print(xiaoMing,xiaoMing.who())
}
}