Sur*_*gch 3 string substring swift
我一直在尝试学习新的Swift 4字符串和子字符串的工作方式。
由于您可以对字符串执行的大部分操作也可以对子字符串执行的操作,因此我试图找到一种将以下两种方法组合为一种方法:
static func isConsonant(ipa: String) -> Bool {
return "ptk?f?s?bdg?vðz?mn?lwjhr??".contains(ipa)
}
static func isConsonant(ipa: Substring) -> Bool {
return "ptk?f?s?bdg?vðz?mn?lwjhr??".contains(ipa)
}
Run Code Online (Sandbox Code Playgroud)
我以为我记得读过一些有关StringProtocol成为链接的内容,但这不起作用:
static func isConsonant(ipa: StringProtocol) -> Bool {
return "ptk?f?s?bdg?vðz?mn?lwjhr??".contains(ipa)
}
Run Code Online (Sandbox Code Playgroud)
错误是
协议'StringProtocol'只能用作一般约束,因为它具有Self或关联的类型要求
是否存在可以接受String或的参数类型Substring?
使其通用
func isConsonant<T>(ipa: T) -> Bool where T: StringProtocol {
return "ptk?f?s?bdg?vðz?mn?lwjhr??".contains(ipa)
}
Run Code Online (Sandbox Code Playgroud)
与其他StringProtocol
方法相同,例如
func contains<T>(_ other: T) -> Bool where T : StringProtocol
func appending<T>(_ aString: T) -> String where T : StringProtocol
// ...
Run Code Online (Sandbox Code Playgroud)
您也可以将其设为的扩展方法或属性StringProtocol
extension StringProtocol {
var isConsonant: Bool {
return "ptk?f?s?bdg?vðz?mn?lwjhr??".contains(self)
}
}
Run Code Online (Sandbox Code Playgroud)
但这存在名称与其他框架冲突的危险。
| 归档时间: |
|
| 查看次数: |
273 次 |
| 最近记录: |