2015-12-20 59 views
0

从下面的代码:铸造和检查值多种类型

import Foundation 

func checkStatus(statusObj: AnyObject) -> String { 
    if let status = statusObj as? String where status.lowercaseString == "ok" { 
     return "success" 
    } else if let status = statusObj as? Int where status >= 200 && status < 300 { 
     return "success" 
    } else { 
     return "failed" 
    } 
} 

print(checkStatus("ok")) 
print(checkStatus(200)) 
print(checkStatus("error")) 
print(checkStatus(500)) 

有没有办法将两个成功的条件组合成一个单独的语句?

+0

这应该是你这样做的方式。合并可能会引入歧义。 –

回答

0

我最后写这种方式,使用交换机和下通:

func checkStatus(statusObj: AnyObject) -> String { 
    switch statusObj { 
    case let status as Int where 200..<300 ~= status: 
     fallthrough 
    case "ok" as String: 
     return "success" 
    default: 
     return "failed" 
    } 
} 

我不得不扭转测试,下通将无法正常工作了与让利的情况下。

+1

返回值有两种可能的状态,不是吗?为什么不简单地从你的函数返回布尔呢? – user3441734

+0

这很有道理。我会去做。 – Laurent