2017-01-03 5 views
1

コードのこの部分を迅速に書く方法3?私はノートアプリを構築していて、この部分は、これがあなたのためにトリックを行う必要がありswiftのcountElements 3

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 
      } 
     } 
    } 
+1

これは**のコードコメントではありません。基本的にはSwiftコードを英語で書き直しました。しかし、我々はスウィフトを読む方法を知っています。私たちは、「コンポーネント内のアイテム」が何を意味するのかを知っています。私たちは、**スウィフトと英語で説明された**方法は必要ありません。我々が必要とするのは**なぜ**です。なぜあなたがしていることをやっているのですか?あなたの意図は?あなたは何を達成しようとしていますか? ** **はコメントのためのものです。 – Alexander

+0

テキストバーの最初の行がナビゲーションバーのタイトルに表示されたかった –

答えて

1

のtableViewのセルに表示されようとしているタイトルについてです:

if item.trimmingCharacters(in: .whitespacesAndNewlines).characters.count > 0 {} 
+1

ありがとう! –

+0

@JovanMilosavljevicあなたの問題を解決した場合、答えとしてマークしてください。 – Tj3n

+3

'!.isEmpty'は' .characters.count> 0'よりも短いです:item!トリミングキャラクター(in:.whitespacesAndNewlines).isEmpty {' – vacawama

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" 
} 
+1

ありがとう、最初の答えは仕事でした:) –

+0

これは短くてシンプルで一般的です。 – Alexander

+0

'return components(separatedBy:.newlines).first {!$ 0.trimmingCharacters(.whitespaces).isEmpty}' –

0

与えられた文字セットの一部ではない文字が存在する可能性の問い合わせ:あなたは、単にしたい場合は仕事

// if the number of letters in the item (AFTER getting 
// rid of extra white space) is greater than 0... 

のための適切なツールを使用しますStringのインスタンスにitemの文字が含まれていれば、であり、CharacterSet.whitespacesAndNewlines(ユニコードスカラーのセット)にはありません。 rangeOfCharacter(from:options:range:)をO理由はtrimmingCharacters(in:)メソッドを使用するのではなく、(また、短絡)を利用し、設定

if item.unicodeScalars.contains(where: 
    { !CharacterSet.whitespacesAndNewlines.contains($0) }) { 
    // ... 
} 

あるいはこの文字でない最初の可能なUnicodeのスカラーを見つけるために、短絡アプローチを使用します.whitespaceAndNewlines文字セットの一部である任意の文字が見つかるかどうかを調べる

if item.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines.inverted) != nil { 
    // ... 
}