Swift:如何解析数字字符串时捕获异常? [英] Swift: How to catch exception when parsing a numeric string?
本文介绍了Swift:如何解析数字字符串时捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#或Java中,通常分析数字字符串会引发格式异常。但是,以下代码未捕获此错误。
In C# or Java, usually parsing a numeric string throws a format exception. However, the following code did not catch the error. What is wrong?
func getInt(_ data:String)->Int
{
do
{
return try Int(data)!
}
catch
{
return -1;
}
}
var a = "x123"
var b:Int = getInt(a)
print("Result: " + b)
推荐答案
在Swift中,只能使用扔
可以接住
。 Int
初始值设定项不会抛出
In Swift only methods which can throw
can catch
. The Int
initializer does not throw
Swift模式是可选的
The Swift pattern are optionals
func getInt(_ data:String) -> Int?
{
return Int(data)
}
let a = "x123"
if let b = getInt(a) {
print("Result: \(b)")
} else {
print("No result")
}
或者您可以返回非可选值,并使用nil合并运算符处理可选的 error
Or you can return a non-optional and handle the optional error with the nil coalescing operator
func getInt(_ data:String) -> Int
{
return Int(data) ?? -1
}
let a = "x123"
let b = getInt(a)
print("Result: \(b)")
或使您的方法可以抛出
enum MyError : Error {
case conversionError
}
func getInt(_ data:String) throws -> Int
{
guard let result = Int(data) else { throw MyError.conversionError }
return result
}
let a = "x123"
do {
let b = try getInt(a)
print("Result: \(b)")
} catch MyError.conversionError {
print("Could not convert the string '\(a)' to integer")
}
请阅读快速语言指南
这篇关于Swift:如何解析数字字符串时捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文