前端之家收集整理的这篇文章主要介绍了
Swift学习小结之枚举和结构体,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import UIKit
var str = "Hello,playground"
//枚举和结构体
enum Rank: Int{
case Ace = 1
case Two,Thress,Four,Five,Six,Seven,Eight,Nine,Ten
case Jack,Queen,King
func simpleDescription()->String{
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
let aceRawValue = ace.toRaw()
if let convertedRank = Rank.fromRaw(3)
{
let threeDescription = convertedRank.simpleDescription()
}
enum Suit {
case Shades,Hearts,Diamonds,Clubs
func simpleDescription()->String{
switch self{
case .Shades:
return "shades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
let hearts = Suit.Hearts
let heart = hearts.simpleDescription()
struct Card {
var rank : Rank
var suit : Suit
func simpleDescription()->String{
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let thressofSpades = Card(rank: .Three,suit: .Spades)
let threeofSpadesDes = thressofSpades.simpleDescription
enum ServerResponse{
case Result(String,String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am","8:09 pm")
let failure = ServerResponse.Error("out of chees.")
switch success{
case let .Result(sunrise,sunset):
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error)
let serverResponse = "Failure... \(error)"
}