2016-12-07 4 views
0

指定されたインデックスから始まる文字列の最初の出現を探したい。 this answerに基づいて指定されたインデックスから始まる文字列の最初の出現を見つけよう

私は次の関数を作成しました:

func index(of string: String, from startIndex: String.Index? = nil, options: String.CompareOptions = .literal) -> String.Index? { 
    if let startIndex = startIndex { 
     return range(of: string, options: options, range: startIndex ..< string.endIndex, locale: nil)?.lowerBound 
    } else { 
     return range(of: string, options: options, range: nil, locale: nil)?.lowerBound 
    } 
} 

残念ながら、インデックスの一部が動作しません。次のコード例

3の代わりにnilを返します。

let str = "test" 
str.index(of: "t", from: str.index(str.startIndex, offsetBy: 1)) 
+1

あなたは間違った範囲に検索を制限しています。 'string.endIndex'は' self.endIndex'(または単に 'endIndex')でなければなりません。 –

+0

いつものように、あなたは正しい@MartinRです。今、それは動作します、ありがとう! – Daniel

答えて

2

あなたが間違った範囲に検索を制限しています。 string.endIndexself.endIndex(またはちょうどendIndex)にする必要があります。

さらに発言:これらの のパラメータはデフォルト値を持っているので

  • range: nillocale: nilを省略することができます。

  • String.Indexも同様String.CompareOptionsため、String 拡張メソッド内Indexに短縮することができます。それはStringstartIndexプロパティで 混乱の原因となるよう

  • 私はオプションのパラメータstartIndexを呼び出すことはありません。

すべて一緒にそれを置く:

extension String { 
    func index(of string: String, from startPos: Index? = nil, options: CompareOptions = .literal) -> Index? { 
     if let startPos = startPos { 
      return range(of: string, options: options, range: startPos ..< endIndex)?.lowerBound 
     } else { 
      return range(of: string, options: options)?.lowerBound 
     } 
    } 
} 

または代わり

extension String { 
    func index(of string: String, from startPos: Index? = nil, options: CompareOptions = .literal) -> Index? { 
     let startPos = startPos ?? startIndex 
     return range(of: string, options: options, range: startPos ..< endIndex)?.lowerBound 
    } 
} 
関連する問題