Skip to content

Instantly share code, notes, and snippets.

@scorpiozj
Created August 15, 2017 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scorpiozj/0c9e6333e0c493ea2912da4d4e8b7066 to your computer and use it in GitHub Desktop.
Save scorpiozj/0c9e6333e0c493ea2912da4d4e8b7066 to your computer and use it in GitHub Desktop.
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