Swift (objc から来ている) に慣れるために、本当に単純なことをしています。guard
ステートメントとステートメントを使用して、リンクされたリストで目的のノードを返したいと考えていますswitch
。guard
私の句が巨大であるため、明らかにステートメントを誤用していelse
ます(switchステートメントが保持されている場所です)。おそらく私はswitch
声明を必要としないかもしれませんが、それは物事を少し整理するだけです.
私の古いコードは次のとおりです。
func getValue (atIndex index: Int) -> T {
if count < index || index < 0 {
print ("index is outside of possible range")
}
var root = self.head
// if var root = self.head {
if index == 0 {
return (self.head?.value)!
}
if index == count-1 {
return (self.tail?.value)!
}
else {
for _ in 0...index-1 {
root = root!.next!
}
}
return root!.value
}
ステートメントに置き換えられguard
ます(ただし、ガード本体が失敗しない可能性があるというコンパイラエラーが発生します)-関数の戻り値の型が<T>
(任意の型)であるため、問題は何を返すかです。
func getValue (atIndex index: Int) -> T {
guard (count < index || index < 0) else {
switch true {
case index == 0:
if let head = self.head {
return head.value
}
case index == count-1:
if let tail = self.tail {
return tail.value
}
default:
if var currentNode = head {
for _ in 0...index-1 {
currentNode = currentNode.next!
}
return currentNode.value
}
}
}
}
目的のインデックスが範囲外であることを示すprint
ステートメントをステートメントの外側に追加したいのですが、 type の関数の最後に何かを返す必要もあります。問題は、and switch ステートメントの外では、返すものが何もないことです。guard
T
guard