直到
Swift 2我使用这个扩展来删除多个空格:
func condenseWhitespace() -> String { let components = self.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter({!Swift.isEmpty($0)}) return " ".join(components) }
但是与Swift 2现在我得到错误
Cannot invoke ‘isEmpty’ with an argument list of type ‘(String)’
我现在可以用Swift 2删除多个空格吗?
日Thnx!
在Swift 2中,join已成为joinWithSeparator,并将其称为数组.
在过滤器中,应该在当前的迭代项$0上调用isEmpty.
用您的问题替换具有独特空格字符的空格和换行符:
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!"
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!"
在Swift 3中,还有更多的变化.
功能:
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()
属性:
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