2017-09-26 110 views
0

這裏有一個簡單的代碼。如果出現問題,我該如何設置默認值?在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

回答

1

在夫特,如果該方法不與throws標記不能捕獲任何錯誤。因此,你應該用if語句檢查每一個(數組長度,強制類型)。

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

那麼如果你是力鑄造爲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

0

我覺得最好的是:

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