[英]How to check if a string contains multiple characters in Swift 5
I have a failure initializer that takes a string, if this string contains incorrect characters (T, A, C, G) I want to return nil: 我有一个失败初始化器,它接受一个字符串,如果该字符串包含不正确的字符(T,A,C,G),我想返回nil:
I tried something like this, unsuccessful: 我尝试过类似的尝试,但未成功:
init?(strand: String) {
let success = strand.contains(where: { !"TACG".contains($0) })
if !success {
return nil
}
self.strand = strand
}
I somehow got confused by the two contains
calls, so I am not sure if my check is correct. 我对这两个contains
调用感到困惑,所以我不确定我的检查是否正确。
Any help is appreciated. 任何帮助表示赞赏。
In this case I'd prefer the API rangeOfCharacter(from
which checks the string against a character set 在这种情况下,我希望使用API rangeOfCharacter(from
该API根据字符集检查字符串
init?(strand: String) {
guard strand.rangeOfCharacter(from: CharacterSet(charactersIn: "TACG")) == nil else { return nil }
self.strand = strand
}
If you don't want to import Foundation you can also use Collection method allSatisfy 如果您不想导入Foundation,也可以使用Collection方法allSatisfy
func allSatisfy(_ predicate: (Character) throws -> Bool) rethrows -> Bool
And make sure your string contains all characters 并确保您的字符串包含所有字符
let allSatisfy = "CGAT".allSatisfy("TACG".contains)
print(allSatisfy) // true
Just move the !
只需移动!
placement, check out the code below . 放置,请查看下面的代码。
init?(strand: String) {
let success = !strand.contains(where: { "TACG".contains($0) })
if !success {
return nil
}
self.strand = strand
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.