Menu
Woocommerce Menu

使用范例,对异常错误的处理

0 Comment
//: Playground - noun: a place where people can playimport UIKitvar str = "Hello, playground"enum Movement { case Left case Right case Top case Bottom}let aMovement = Movement.Leftswitch aMovement {case .Left: printdefault: print}if case .Left = aMovement { print}if .Left == aMovement { print}enum Season: Int { case Spring = 0 case Summer = 1 case Autumn = 2 case Winter = 3}enum House: String { case ZhangSan = "I am zhangsan" case LiSi = "I am lisi"}let zs = House.ZhangSanprint(zs.rawValue)enum Constants: Double { case π = 3.14159 case e = 2.71828 case φ = 1.61803398874 case λ = 1.30357}let pai = Constants.πprint(pai.rawValue)enum CompassPoint: String { case North, South, East, West}let n = CompassPoint.Northprint(n.rawValue)let s = CompassPoint(rawValue: "South");enum VNodeFlags : UInt32 { case Delete = 0x00000001 case Write = 0x00000002 case Extended = 0x00000004 case Attrib = 0x00000008 case Link = 0x00000010 case Rename = 0x00000020 case Revoke = 0x00000040 case None = 0x00000080}enum Character { enum Weapon { case Bow case Sword case Lance case Dagger } enum Helmet { case Wooden case Iron case Diamond } case Thief case Warrior case Knight}let character = Character.Thieflet weapon = Character.Weapon.Bowlet helmet = Character.Helmet.Ironstruct Scharacter { enum CharacterType { case Thief case Warrior case Knight } enum Weapon { case Bow case Sword case Lance case Dagger } let type: CharacterType let weapon: Weapon}let sc = Scharacter(type: .Thief, weapon: .Bow)printenum Trade { case Buy(stock: String, amount: Int) case Sell(stock: String, amount: Int)}let trade = Trade.Buy(stock: "Car", amount: 100)if case let Trade.Buy(stock, amount) = trade { print("buy \ of \}enum Trade0 { case Buy(String, Int) case Sell(String, Int)}let trade0 = Trade0.Buy("Car0", 100)if case let Trade0.Buy(stock, amount) = trade0 { print("buy \ of \}enum Wearable { enum Weight: Int { case Light = 2 } enum Armor: Int { case Light = 2 } case Helmet(weight: Weight, armor: Armor) func attributes() -> (weight: Int, armor: Int) { switch self { case .Helmet(let w, let a): return (weight: w.rawValue * 2, armor: a.rawValue * 4) } }}let test = Wearable.Helmet(weight: .Light, armor: .Light).attributes()printenum Device { case iPad, iPhone, AppleTV, AppleWatch func introduced() -> String { switch self { case .AppleTV: return "\ was introduced 2006" case .iPhone: return "\ was introduced 2007" case .iPad: return "\ was introduced 2010" case .AppleWatch: return "\ was introduced 2014" } }}print (Device.iPhone.introducedenum Device1 { case iPad, iPhone var year: Int { switch self { case .iPad: return 2010 case .iPhone: return 2007 } }}let iPhone = Device1.iPhoneprint(iPhone.year)enum Device2 { case AppleWatch static func fromSlang(term: String) -> Device2? { if term == "iWatch" { return .AppleWatch } return nil }}print(Device2.fromSlang(term: "iWatch") ?? "nil")enum TriStateSwitch { case Off, Low, High mutating func next() { switch self { case .Off: self = .Low case .Low: self = .High case .High: self = .Off } }}var state = TriStateSwitch.Low // 必须使用varstate.next()state.next()protocol CustomStringConvertible { var description: String { get }}enum Trade1: CustomStringConvertible { case Buy, Sell var description: String { switch self { case .Buy: return "We're buying something" case .Sell: return "We're selling something" } }}let t1 = Trade1.Buy.descriptionprotocol AccountCompatible { var remainingFunds: Int { get } mutating func addFunds(amount: Int) throws mutating func removeFunds(amount: Int) throws}enum Account { case Empty case Funds(remaining: Int) enum ErrorInfo: Error { case OverDraft(amount: Int) } var remainingFunds: Int { switch self { case .Empty: return 0 case .Funds(let remaining): return remaining } }}extension Account: AccountCompatible { mutating func addFunds(amount: Int) throws { var newAmount = amount if case let .Funds(remaining) = self { newAmount += remaining } if newAmount < 0 { throw Account.ErrorInfo.OverDraft(amount: newAmount) }else if newAmount == 0 { self = .Empty }else { self = .Funds(remaining: newAmount) } } mutating func removeFunds(amount: Int) throws { try self.addFunds(amount: amount * -1) }}var account = Account.Funds(remaining: 20)try? account.addFunds(amount: 20)print("add: ", account.remainingFunds)try? account.removeFunds(amount: 15)print ("remove 1: ", account.remainingFunds)do { try account.removeFunds(amount: 55)}catch (let errorInfo) { print(errorInfo)}print ("remove 2: ", try? account.removeFunds(amount: 55))

// 1.swift 中if 的用法

// 1> if 前面包车型地铁()能够归纳

// 2>
推断句不再有非0/nil即真,推断句必需有拨云见日的真伪(Bool–>true/false)

在OC中,单元测量试验时我们会利用断言,断言中规格满意时会发生非常,并打字与印刷出相应的预感错误。而在Swift对特别的管理和抛出也足以像任何语言同样管理。

let a = 10

//简单的异常使用枚举定义,但是枚举要继承Error协议,这里写两个异常, 没油, 超重enum CarError: Error{case lackOilcase overload}//定义汽车是否能驾驶enum Driver {case start//能否启动case loading//能否载重}//货车类,两个属性,//最少的油量,少于10%货车就不能启动。//最大载重量,大于2000就不能工作class Car {var minOil: Double = 0.1var maxCargo: Double = 2000.0// kg//throws 表示该方法会出现异常,不然不能被放在do里面func drivering(driver: Driver)throws {//开车 switch driver { case .start: //guard else 语句类似于if else 语句, guard 后面的条件通过执行后面的语句, 不通过执行 else 里面的语句 guard self.minOil > 1.0 else { throw CarError.lackOil // 抛出异常 返回上一调用方法,在catch里面找异常处理 } print("the car begin move") case .loading: guard self.maxCargo < 2000 else { throw CarError.overload } print("the car begin working") }}//现在我们写一个处理异常的方法,func workingCarthrows { //defer 关键字是在这个方法调用结束后一定会调用的方法。也是最后走的方法 defer { print(" always run") } // do catch 在do闭包里面执行会抛出异常的代码,在catch 分支里面匹配异常处理异常, 在do 里面的调用都是throws 标记后的方法,意思是这个方法可能会出现异常 // try! 使用try! 是我们确定这个调用不会发生异常 如果有异常,就会崩溃。一般不这么用 //try 使用try 表示调用的方法会出现异常, 还有 try?调用了一个会出现异常的方法,并且结果转换为一个Optional, 异常返回nil do { //下面的调用是只要上一个出现异常,就不会继续调用下面的方法哦 try car.drivering(driver: .loading) try car.drivering(driver: .start) } catch let CarError.lackOil { //对异常的处理 print(" lack of oil ") } catch let CarError.overload { print(" overLoad ") }}//最后我们调用一下let car = Car.init(oil: 0.5, cargo: 3000)do {try workingCar} catch {}

if a > 0 {

就能够打字与印刷:the car begin move** overLoad **** will will**

print

//再调用一下let car = Car.init(oil: 0.05, cargo: 1500)do {try workingCar} catch {}

}else{

打印:** lack of oil**** will
will**因为缺油所以再抛出油量远远不够的老大后,前边的是或不是超载方法不在推行,不过will
will
依旧会举办实际OC里面包车型客车要命管理自个儿时机没有主动处理过,实在是难驾驭,一般都直接打印一下就随意了,况兼一般看见error传个nil。如若你想看关于OC的极其管理,能够看那么些NSError:

print

}

// 2.swift中else if的用法

// 用法和if用法一致

let score = 92

if score < 0 || score>100 {

print

}else if score < 60{

print

}

// 3.三目运算符

let m1 = 20

let n1 = 30

*/**

var result2 = 0

if m1 > n1 {

result2 = m1

}else{

result2 = n1

}\/*

let result2 = m1 > n1 ? m1 : n1

// 4.guard 的使用

//1)guard是斯威夫特2.0 新扩充的语法

let age = 20

*/**

func online(age : Int){

if age >= 18{

print

}else{

print

}

}

\/*

func online(age : Int, dai : Bool, money : Bool){

// guard 前面包车型大巴决断为true,那么实践后边的语句块

// 假诺为false,那么执行else后边的{}

标签:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

相关文章

网站地图xml地图