首页 > 解决方案 > Swift 字符串包含 , 或 . 但不是两者

问题描述

我想以更优雅的方式编写以下内容:

let number = "1,2922.3"

if number.contains(",") || number.contains(".") && !(number.contains(".") && number.contains(",")) {
    // proceed
}

也就是说,如果数字有“。”,我想继续。或“,”,但不能同时使用它们。

一定有更好的方法?

我不想使用扩展,因为它在我的代码中的一个地方。

标签: swift

解决方案


您可以使用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

稍微解释一下:

  • !allowed.isDisjoint(with: string)因为您要排除既不包含.和的字符串,
  • !allowed.isSubset(of: string)因为您要排除同时包含.和的字符串,

推荐阅读