我不确定swift 2中的API是否已更改,但我无法使用过滤器来处理Swift 2中的字符串。以下内容应将“abc123 $$$ ff”更改为“abcff”。
// Removes all special characters and whitespaces
func compressString(aString: String) -> String{
let charSet = NSCharacterSet.letterCharacterSet()
// The following don't work:
// return aString.filter{charSet.contains($0)}
// return String(filter(aString).{charSet.contains($0)})
}
答案 0 :(得分:1)
int val = (int)Char.GetNumericValue(Console.Read())
您还可以创建扩展程序以简化代码:
func compressString(aString: String) -> String {
let letterSet = NSCharacterSet.letterCharacterSet()
return String(aString.characters.filter{letterSet.characterIsMember(String($0).utf16.first!)})
}
let str = "abc123$$$ ff"
compressString(str) // abcff
答案 1 :(得分:1)
如果要使用过滤器,则需要在字符视图上运行它:
// Removes all special characters and whitespaces
func compressString(aString: String) -> String{
let charSet: [Character] = ["$", " ", "1", "2", "3"]
// The following don't work:
return String(aString.characters.filter { !charSet.contains($0) })
}
let before = "abc123$$$ ff"
let after = compressString(before) // "abcff"