2015-09-25 35 views
-1

我不確定Swift 2中的API是否發生了變化,但我無法使用過濾器來處理Swift 2中的字符串。以下內容應該將「abc123 $$ $ ff「轉換爲」abcff「。在Swift 2中對字符串使用過濾器()

// 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)}) 
} 
+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" 
1
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 

您還可以創建一個擴展,簡化代碼:

extension String { 
    var lettersOnly: String { 
     return String(characters.filter{NSCharacterSet.letterCharacterSet().characterIsMember(String($0).utf16.first!)}) 
    } 
} 
// Removes all special characters and whitespaces 

let str = "abc123$$$ ff" 

let letters = str.lettersOnly // "abcff" 
+0

適合我。但有沒有辦法使用過濾器? – goodcow

+0

@goodcow您可以使用NSCharacterSet characterIsMember方法。看我的編輯。 –