Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift Error Handling
//
// ViewController.swift
// ErrorTest
//
// Created by ZhuJiang on 2017/8/15.
// Copyright © 2017年 Charles. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
try errorTest(num: -10.0)
} catch let error {
print("\(error)")
}
let x = try? errorTest(num: -10.0)
print(type(of: x))
let y = try? errorTest(num: 10.0)
print(type(of: y))
let z = try! errorTest(num: 10.0) //crash if it is -10.0
print(type(of: z))
}
enum ZZNumberError : Error { case negativeError }
private func errorTest(num: Double) throws -> Double {
if num < 0 {
throw ZZNumberError.negativeError
}
return num
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment