我想以更优雅的方式编写以下内容:
let number = "1,2922.3"
if number.contains(",") || number.contains(".") && !(number.contains(".") && number.contains(",")) {
// proceed
}
Run Code Online (Sandbox Code Playgroud)
也就是说,如果号码有“.”,我想继续。或“,”,但不能同时使用它们。
一定有更好的方法?
我不想使用扩展,因为它位于我的代码中的一个位置。
您可以使用SetAlgebra:
func validate(_ string: String) -> Bool {
let allowed = Set(",.")
return !allowed.isDisjoint(with: string) && !allowed.isSubset(of: string)
}
validate("1,2922.3") // false
validate("1,29223") // true
validate("12922.3") // true
validate("129223") // false
Run Code Online (Sandbox Code Playgroud)
解释一下:
!allowed.isDisjoint(with: string)因为您想要排除既不包含.也不包含的字符串,。!allowed.isSubset(of: string)因为您想排除同时包含.和 的字符串,。| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |