在Swift 4中使用扩展
我的extension-example包含3个函数:检查一个字符串是否以子字符串开头,将一个字符串结束为一个子字符串和检查一个字符串是否包含一个子字符串。
如果您想忽略字符"A"或"a",则将isCaseSensitive参数设置为false,否则设置为true。
有关它的工作原理的更多信息,请参见代码中的注释。
代码:
import Foundation
extension String {
func hasPrefixCheck(prefix: String, isCaseSensitive: Bool) -> Bool {
if isCaseSensitive == true {
return self.hasPrefix(prefix)
} else {
var thePrefix: String = prefix, theString: String = self
while thePrefix.count != 0 {
if theString.count == 0 { return false }
if theString.lowercased().first != thePrefix.lowercased().first { return false }
theString = String(theString.dropFirst())
thePrefix = String(thePrefix.dropFirst())
}; return true
}
}
func hasSuffixCheck(suffix: String, isCaseSensitive: Bool) -> Bool {
if isCaseSensitive == true {
return self.hasSuffix(suffix)
} else {
var theSuffix: String = suffix, theString: String = self
while theSuffix.count != 0 {
if theString.count == 0 { return false }
if theString.lowercased().last != theSuffix.lowercased().last { return false }
theString = String(theString.dropLast())
theSuffix = String(theSuffix.dropLast())
}; return true
}
}
func containsSubString(theSubString: String, isCaseSensitive: Bool) -> Bool {
if isCaseSensitive == true {
return self.range(of: theSubString) != nil
} else {
return self.range(of: theSubString, options: .caseInsensitive) != nil
}
}
}
使用示例:
检查字符串是否以"TEST"开头:
"testString123".hasPrefixCheck(prefix: "TEST", isCaseSensitive: true) // Returns false
"testString123".hasPrefixCheck(prefix: "TEST", isCaseSensitive: false) // Returns true
检查字符串是否以“test”开头:
"testString123".hasPrefixCheck(prefix: "test", isCaseSensitive: true) // Returns true
"testString123".hasPrefixCheck(prefix: "test", isCaseSensitive: false) // Returns true
检查字符串是否以“G123”结尾:
"testString123".hasSuffixCheck(suffix: "G123", isCaseSensitive: true) // Returns false
"testString123".hasSuffixCheck(suffix: "G123", isCaseSensitive: false) // Returns true
检查字符串是否以"g123"结尾:
"testString123".hasSuffixCheck(suffix: "g123", isCaseSensitive: true) // Returns true
"testString123".hasSuffixCheck(suffix: "g123", isCaseSensitive: false) // Returns true
检查字符串是否包含“RING12”:
"testString123".containsSubString(theSubString: "RING12", isCaseSensitive: true)
"testString123".containsSubString(theSubString: "RING12", isCaseSensitive: false)
检查字符串是否包含"ring12":
"testString123".containsSubString(theSubString: "ring12", isCaseSensitive: true)
"testString123".containsSubString(theSubString: "ring12", isCaseSensitive: false)