Created
January 9, 2018 11:05
-
-
Save lamlv2305/31bb915ee2bcdc4de173c4a82f6446f0 to your computer and use it in GitHub Desktop.
[SWIFT 4.0] fatalError with clean way from https://github.com/JohnSundell/Require/blob/master/Sources/Require.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Require | |
* Copyright (c) John Sundell 2017 | |
* Licensed under the MIT license. See LICENSE file. | |
*/ | |
import Foundation | |
public extension Optional { | |
/** | |
* Require this optional to contain a non-nil value | |
* | |
* This method will either return the value that this optional contains, or trigger | |
* a `preconditionFailure` with an error message containing debug information. | |
* | |
* - parameter hint: Optionally pass a hint that will get included in any error | |
* message generated in case nil was found. | |
* | |
* - return: The value this optional contains. | |
*/ | |
func require(hint hintExpression: @autoclosure () -> String? = nil, | |
file: StaticString = #file, | |
line: UInt = #line) -> Wrapped { | |
guard let unwrapped = self else { | |
var message = "Required value was nil in \(file), at line \(line)" | |
if let hint = hintExpression() { | |
message.append(". Debugging hint: \(hint)") | |
} | |
#if !os(Linux) | |
let exception = NSException( | |
name: .invalidArgumentException, | |
reason: message, | |
userInfo: nil | |
) | |
exception.raise() | |
#endif | |
preconditionFailure(message) | |
} | |
return unwrapped | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment