How to remove multiple spaces in Strings with Swift 2

后端 未结 6 1007
予麋鹿
予麋鹿 2021-02-07 01:23

Until Swift 2 I used this extension to remove multiple whitespaces:

func condenseWhitespace() -> String {
        let components = self.componentsSeparatedByC         


        
6条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 02:00

    In Swift 2, join has become joinWithSeparator and you call it on the array.

    In filter, isEmpty should be called on the current iteration item $0.

    To replace whitespaces and newline characters with unique space characters as in your question:

    extension String {
        func condenseWhitespace() -> String {
            let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
            return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
        }
    }
    
    let result = "Hello  World.\nHello!".condenseWhitespace()  // "Hello World. Hello!"
    

    Because your function does not take any parameter you could make it a property instead:

    extension String {
        var condensedWhitespace: String {
            let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
            return components.filter { !$0.isEmpty }.joinWithSeparator(" ")
        }
    }
    
    let result = "Hello  World.\nHello!".condensedWhitespace  // "Hello World. Hello!"
    

    In Swift 3 there's even more changes.

    Function:

    extension String {
        func condenseWhitespace() -> String {
            let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
            return components.filter { !$0.isEmpty }.joined(separator: " ")
        }
    }
    
    let result = "Hello  World.\nHello!".condenseWhitespace()
    

    Property:

    extension String {
        var condensedWhitespace: String {
            let components = self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines)
            return components.filter { !$0.isEmpty }.joined(separator: " ")
        }
    }
    
    let result = "Hello  World.\nHello!".condensedWhitespace
    

    In Swift 4.2 NSCharacterSet is now CharacterSet, and you can omit and use dot syntax:

    extension String {
        func condenseWhitespace() -> String {
            let components = self.components(separatedBy: .whitespacesAndNewlines)
            return components.filter { !$0.isEmpty }.joined(separator: " ")
        }
    }
    
    let result = "Hello  World.\nHello!".condenseWhitespace()  // "Hello World. Hello!"
    

提交回复
热议问题