How to remove special characters from string in Swift 2?

前端 未结 5 2083
青春惊慌失措
青春惊慌失措 2020-12-02 20:07

The answer in How to strip special characters out of string? is not working.

Here is what I got and it gives me an error

func removeSpecialCharsFr         


        
5条回答
  •  一生所求
    2020-12-02 20:50

    In Swift 1.2,

    let chars = Set("abcde...")
    

    created a set containing all characters from the given string. In Swift 2.0 this has to be done as

    let chars = Set("abcde...".characters)
    

    The reason is that a string itself does no longer conform to SequenceType, you have to use the characters view explicitly.

    With that change, your method compiles and works as expected:

    func removeSpecialCharsFromString(str: String) -> String {
        let chars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_".characters)
        return String(str.characters.filter { chars.contains($0) })
    }
    
    let cleaned = removeSpecialCharsFromString("ab€xy")
    print(cleaned) // abxy
    

    Remark: @Kametrixom suggested to create the set only once. So if there is performance issue with the above method you can either move the declaration of the set outside of the function, or make it a local static:

    func removeSpecialCharsFromString(str: String) -> String {
        struct Constants {
            static let validChars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890+-*=(),.:!_".characters)
        }
        return String(str.characters.filter { Constants.validChars.contains($0) })
    }
    

提交回复
热议问题