神刀安全网

Erica Sadun : Safely invoking removeAtIndex

Michelle Elliot saw my post onsafe indexing and asks: Is there a similar easy syntax for safely invoking removeAtIndex(index: Int) -> Element?

Here’s what I came up with. You need to call it with safe and it returns an optional. Improvements, issues, and suggestions are as always welcome.

public extension RangeReplaceableCollectionType where Index: Comparable {     public subscript (safe index: Index) -> Generator.Element? {         get {             guard indices ~= index else { return nil }             return self[index]         }         set {             guard indices ~= index else { return }             if let newValue = newValue {                 self.removeAtIndex(index)                 self.insert(newValue, atIndex: index)             }         }     }          public mutating func removeAtIndex(safe index: Self.Index) -> Self.Generator.Element? {         guard indices ~= index else { return nil}         return self.removeAtIndex(index)     } }

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Erica Sadun : Safely invoking removeAtIndex

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮