import Foundation
/**
* 1.枚举的语法
*/
//与 C 和 Objective-C 不同,Swift 的枚举成员在被创建时不会被赋予一个默认的整型值。这些枚举成员值的类型是CompassPoint。
enum CompassPoint {
case North
case South
case East
case West
}
var direction = CompassPoint.North
print(direction)
direction = .South
if direction == .South
{
print("方向正确")
}
switch direction
{
case .North:
print("北方")
case .South:
print("南方")
case .East:
print("东方")
case .West:
print("西方")
}
/**
* 2.枚举的关联值
可以给枚举成员指定关联值
*/
enum Product
{
case Auto(String/* 产品名称 */, Int /* 轮子数 */ , Float /* 载重量(单位:吨)*/, Float /* 价格(单位:万) */)
case Mobile(String /* 产品名称 */, Float /*屏幕尺寸(单位:英寸)*/,String /* 操作系统 */, Float /*价格 */)
}
let product1 = Product.Auto("八轮载重卡车", 8, 25, 120)
let product2 = Product.Mobile("iPhone6", 5.5, "iOS", 6500)
switch product2
{
case .Auto(let name, let wheelCount, let payload, let price):
print("name: \(name), wheelCount = \(wheelCount), payload=\(payload), price = \(price)")
case .Mobile(let name, let screenSize,let os, let price):
print("name: \(name), screenSize = \(screenSize), os=\(os), price = \(price)")
}
switch product1
{
case let .Auto( name, wheelCount, payload, price):
print("name: \(name), wheelCount = \(wheelCount), payload=\(payload), price = \(price)")
case let .Mobile( name, screenSize, os, price):
print("name: \(name), screenSize = \(screenSize), os=\(os), price = \(price)")
}
/**
* 3.枚举的原始值
原始值可以是字符串,字符,或者任意整型值或浮点型值。每个原始值在枚举声明中必须是唯一的
*/
enum StringEnum: String
{
case Name = "Bill"
case Location = "沈阳"
case Job = "CEO"
}
//获取原始值
print(StringEnum.Name.rawValue)
enum Planet: Int
{
case Mercury = 1, Venus, Earth, Mars, Jupiter=7 , Saturn, Uranus, Neptune
}
print(Planet.Mars.rawValue)//4
print(Planet.Saturn.rawValue)//8
//从原始值初始化枚举实例
let possiblePlanet:Planet? = Planet(rawValue: 7)
if possiblePlanet == nil
{
print("没有找到相关的行星")
}
else if possiblePlanet! == .Earth
{
print("找到了地球")
}
else
{
print("找了了其他行星")
}
/**
* 4.递归枚举
indirect表示该成员可递归
*/
enum ArithmeticExpression {
case Number(Int)
indirect case Addition(ArithmeticExpression, ArithmeticExpression)
indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
}
//开头加上indirect表明它的所有成员都是可递归的:
//indirect enum ArithmeticExpression {
// case Number(Int)
// case Addition(ArithmeticExpression, ArithmeticExpression)
// case Multiplication(ArithmeticExpression, ArithmeticExpression)
//}
func evaluate(expression: ArithmeticExpression) -> Int {
switch expression {
case .Number(let value):
return value
case .Addition(let left, let right):
return evaluate(left) + evaluate(right)
case .Multiplication(let left, let right):
return evaluate(left) * evaluate(right)
}
}
// 计算 (5 + 4) * 2
let five = ArithmeticExpression.Number(5)
let four = ArithmeticExpression.Number(4)
let sum = ArithmeticExpression.Addition(five, four)
let product = ArithmeticExpression.Multiplication(sum, ArithmeticExpression.Number(2))
print(evaluate(product))
// 输出 "18"
Swift 学习记录(5)
最新推荐文章于 2024-03-08 08:57:25 发布