swift3.0で文字列から任意の文字があるかないか判別する方法の一つ | 30歳から始めたプログラミング

swift3.0で文字列から任意の文字があるかないか判別する方法の一つ

●swift1.1

let string = "12345\n6789"

let index = string.rangeOfString("\n").location  

//結果:[index => 5]

 

●swift3.0

let string = "12345\n6789"

let exists = string.range(of: "\n")?.lowerBound

//結果:range情報が入っているので

if exists != nil { // -> true

      print("\n is exists")

}

 

と出来る。

 

index(位置情報)もexists内に入っていますが取り出し方がわからなかったので取りあえずこれで