Question: countElements in Swift 3

Question

countElements in Swift 3

Answers 2
Added at 2017-01-03 04:01
Tags
Question

How to write this part of the code in swift 3? I am building a notes app, and this part is about a title that is going to be displayed in tableView cell

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 
          } 
        } 
    } 
Answers
nr: #1 dodano: 2017-01-03 04:01

This should do the trick for you:

if item.trimmingCharacters(in: .whitespacesAndNewlines).characters.count > 0 {}
nr: #2 dodano: 2017-01-03 04:01

How's this?

extension String {
    func firstNonEmptyLine() -> String? {
        let lines = self.componentsSeparatedByString("\n")
        return lines.first(where: { 
               $0.trimmingCharacters(in: .whitespacesAndNewlines) 
               .characters.count > 0  })
    }
}

func textViewDidChange(textView: UITextView) {
    self.navigationItem.title = self.txtBody.text.firstNonEmptyLine() ?? "Default title if there's no non-empty line"
}
Source Show
◀ Wstecz