在swift中处理错误 - 没有参数或错误参数

问题描述:

这里有一个简单的代码。如果出现问题,我该如何设置默认值?在swift中处理错误 - 没有参数或错误参数

enum direction { 
    case north, west, east, south 
} 

let defaultDirection = direction.north 

func printDirection(parameters: [Any]) { 

    let dir = parameters[0] as! direction 
    //if error then dir = defaultDirection 

    switch dir { 
     case .north: print("north") 
     case .east: print("east") 
     case .west: print("west") 
     case .south: print("south") 
    } 
} 

printDirection(parameters: [direction.east]) 

例如,如果我打电话不带参数printDirection(parameters: [])或者如果我存储不是一个方向的类型值printDirection(parameters: [7])

+0

您在功能printDirection有什么期望?只打印方向? –

+0

为什么参数是“Any”数组而不是“direction”数组? – Michael

+0

它是任何因为我想传递不同类型的另一个参数。这里只是一个例子。 – Anton

在夫特,如果该方法不与throws标记不能捕获任何错误。因此,你应该用if语句检查每一个(数组长度,强制类型)。

let dir: direction 
if let firstParameter = parameter.first? as? direction { 
    dir = firstParameter 
} else { 
    dir = defaultDirection 
} 

那么如果你是力铸造为Direction元素不一个Direction,那么你一定会得到在某个时候发生错误。

代码:

let dir = parameters[0] as! Direction 

绝对不是在这里是个好主意。

你可以做什么而不是强制施法,是使用rawValue建立你的对象,并处理你的元素不存在的情况下,以便它不返回nil这是默认行为)。

假设你有水果的枚举:

enum Fruit: String { 

    case apple = "apple" 
    case banana = "banana" 
    case mango = "mango" 
    case cherry = "cherry" 

    init(rawValue: String) { 

     switch rawValue { 
     case "apple" : self = .apple 
     case "banana" : self = .banana 
     case "mango" : self = .mango 
     case "cherry" : self = .cherry 
     default: self = .apple 
     } 

    } 

} 

,你可以在这里我用的是我的枚举的init重返“苹果”反正只要值不是我想要的东西。

现在你可以这样做:

let fruit = Fruit(rawValue: "pear") 

print(fruit) // Prints "apple" because "pear" is not one of the fruits that I defined in my enum. 

let otherFruit = Fruit(rawValue: "banana") 

print(otherFruit) // Prints "banana" 

当然,你可以用类似的方式:)

注意用它在你的函数:请注意,您仍然要处理的情况下当你的水果名称为nil(或任何其他类型的不是一个字符串),因为rawValue确实需要是一个String。在尝试使用rawValue制作水果之前,您可以使用if或guard警告来检查它是否为String

我觉得最好的是:

let dir = (parameters.count >= 1 && parameters[0] as? direction != nil) ? parameters[0] as! direction : defaultDirection