Swiftで遊ぼう! - 716 - Collection型のインデックスの扱い
WWDC2016のビデオに「Protocol and Value Oriented Programming in UIKit Apps」という表題があります。実はWWDC2015でProtocol-Oriented Programmingというプログラミング手法が紹介されました(私は見てません(^_^;)が、どうもそれを拡張しているようなので、そろそろProtocol-Oriented Programmingの勉強をしていきます。
Protocol-Oriented Programmingという名前から、中心的な役割を担っているのが、ProtocolとExtensionです。そして、身軽なstructure型でプログラミングしていくやり方のようですが、こういう抽象的なプログラミング作法の勉強を始めると、結構Swiftのスタンダードライブラリを使って説明することが多いです。
しかし、このスタンダードライブラリですが、結構知らないことが多いんです。ということでSwiftで変更になったCollection型のインデックスを扱うメソッドに関して勉強しました。
Swift理解のために、Collection型の理解は必須です。Swift 3から扱いが変わります。
myIndex.successor() => myCollection.index(after: myIndex) myIndex.predecessor() => myCollection.index(before: myIndex) myIndex.advance(by: …) => myCollection.index(myIndex, offsetBy: …)
playgroundで確かめて見ると次のように何のことやら。
var testDictionary = ["One": 1, "Twon": 2 ,"Three": 3 ,"Four": 4 ,"Five": 5 ,"Six": 6] var myIndex = testDictionary.startIndex myIndex = testDictionary.index(after: myIndex) myIndex = testDictionary.index(myIndex, offsetBy: 3) print("\(myIndex)")
コンソールに次のラインが表示されました。
DictionaryIndex
何のことやら。ちなみに「index(before: myIndex)」は動きません。
今日はこれだけ。