目录

Tested on GitHub Actions

Swift 5 swift package manager 5.2 is supported Supports macOS, iOS, tvOS, watchOS, Linux, & Windows

Swift Safe Collection Access

Ever wonder why Swift crashes if you access a collection the wrong way? Especially an array? Me too here’s some extensions. 🎉

collection[orNil:]

This subscript fails gracefully on invalid input by returning nil or refusing to mutate the collection. With valid input, it behaves precisely like Swift’s builtin subscripts!


import SafeCollectionAccess



var first5Fibonacci = [1, 1, 2, 3, 5]

first5Fibonacci[orNil: 0]                       // Optional(1)
first5Fibonacci[orNil: 3] == first5Fibonacci[3] // true
first5Fibonacci[orNil: 999]                     // `nil`
first5Fibonacci[orNil: -1]                      // `nil`

first5Fibonacci[orNil: 2...4]  // Optional([2, 4])
first5Fibonacci[orNil: -2...2] // `nil`
first5Fibonacci[orNil: ..<42]  // `nil`


first5Fibonacci[orNil: 1]   = 42  // [1, 42, 2, 3, 5]
first5Fibonacci[orNil: 999] = -1  // [1, 42, 2, 3, 5]
first5Fibonacci[orNil: -1]  = 777 // [1, 42, 2, 3, 5]

first5Fibonacci[orNil: 0...2]  = [9, 5]    // [9, 5, 3, 5]
first5Fibonacci[orNil: -2...2] = [42]      // [9, 5, 3, 5]
first5Fibonacci[orNil: ..<42]  = [7, 7, 7] // [9, 5, 3, 5]

collection[clamping:]

This subscript fails gracefully on invalid input by returning or mutating the closest valid element (or, with empty collections, returning nil or refusing to mutate). With valid input, it behaves precisely like Swift’s builtin subscripts!


import SafeCollectionAccess



var first5Fibonacci = [1, 1, 2, 3, 5]

first5Fibonacci[clamping: 0]                       // 1
first5Fibonacci[clamping: 3] == first5Fibonacci[3] // true
first5Fibonacci[clamping: 999]                     // 5
first5Fibonacci[clamping: -1]                      // 1


first5Fibonacci[clamping: 1]   = 42  // [1, 42, 2, 3, 5]
first5Fibonacci[clamping: 999] = -1  // [1, 42, 2, 3, -1]
first5Fibonacci[clamping: -1]  = 777 // [777, 42, 2, 3, -1]
关于
84.0 KB
邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9 京公网安备 11010802032778号