swift - Swift 字符串包含 , 或 . 但不是两者
问题描述
我想以更优雅的方式编写以下内容:
let number = "1,2922.3"
if number.contains(",") || number.contains(".") && !(number.contains(".") && number.contains(",")) {
// proceed
}
也就是说,如果数字有“。”,我想继续。或“,”,但不能同时使用它们。
一定有更好的方法?
我不想使用扩展,因为它在我的代码中的一个地方。
解决方案
您可以使用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)
因为您要排除同时包含.
和的字符串,
。
推荐阅读
- android-studio - android studio中的代码模糊
- regex - 如何使用 htaccess 删除 URL 中的目录名称?
- laravel - Laravel Eloquent - 与数据透视表的模型关系
- html - 使用引导程序的 div 之间的 Html css 空间
- sonarqube - 在 SonarQube 问题页面上,如何过滤出违反特定规则的行为?
- javascript - 如果我在两列中进行编辑,图像应该保持不变
- apache-spark - 将 spark 数据帧写入 hdfs 时的额外分隔符
- mysql - 尝试将列加入 key_column_usage
- c++ - 获取makefile以更改输出可执行文件名称
- android - 如何将 Mapbox 遥测添加到 android?