如何在swift 3中编写这部分代码?我正在构建一个笔记应用程序,这部分是关于将在tableView单元格中显示的标题
if countElements(item.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())) > 0
func textViewDidChange(textView: UITextView) {
//separate the body into multiple sections
let components = self.txtBody.text.componentsSeparatedByString("\n")
//reset the title to blank (in case there are no components with valid text)
self.navigationItem.title = ""
//loop through each item in the components array (each item is auto-detected as a String)
for item in components {
//if the number of letters in the item (AFTER getting rid of extra white space) is greater than 0...
if countElements(item.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())) > 0 {
//then set the title to the item itself, and break out of the for loop
self.navigationItem.title = item
break
}
}
}
答案 0 :(得分:1)
这应该适合你:
if item.trimmingCharacters(in: .whitespacesAndNewlines).characters.count > 0 {}
答案 1 :(得分:1)
这是怎么回事?
extension String {
func firstNonEmptyLine() -> String? {
let lines = components(separatedBy: .newlines)
return lines.first(where: {
!$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty })
}
}
func textViewDidChange(textView: UITextView) {
self.navigationItem.title = self.txtBody.text.firstNonEmptyLine() ?? "Default title if there's no non-empty line"
}
答案 2 :(得分:0)
查询是否存在不属于给定字符集的字符:使用适合该作业的工具
// if the number of letters in the item (AFTER getting // rid of extra white space) is greater than 0...
如果您只是想知道String
实例item
中是否有任何字符<{3}}中的不是(一组unicode标量) ,没有理由使用trimmingCharacters(in:)
方法,而是使用短路方法来查找不在此字符集中的第一个可能的unicode标量
if item.unicodeScalars.contains(where:
{ !CharacterSet.whitespacesAndNewlines.contains($0) }) {
// ...
}
或者,使用(也是短路)CharacterSet.whitespacesAndNewlines
来查找是否可以找到任何属于倒置.whitespaceAndNewlines
字符集的字符
if item.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines.inverted) != nil {
// ...
}