I cannot explain why this did work in former versions of Xcode, but don't you think your two subscript(safe:)
is ambiguous enough when Collection.Index == Int
?
And, with your second subscript(safe:)
, the word safe
does not seem to be appropriate as it may easily crash your app when int
is out of bounds of the collection.
extension Collection {
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
subscript (safe int: Int) -> Element? {
let index = self.index(self.startIndex, offsetBy: int)
return self[index]
}
}
var arr: [String] = ["a"]
print(arr[safe: 1])
Causes Thread 1: Fatal error: Index out of range
on the line return self[index]
.
(Tested with Xcode 10.1.)
You should better use another word than safe
for your second subscript
, and the two subscript
may never be ambiguous in any versions of Xcode.
extension Collection {
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
subscript (offsetBy int: Int) -> Element? {
let index = self.index(self.startIndex, offsetBy: int)
return self[index]
}
}
Maybe I need to clarify my intention. (Thanks to Nate.)
You can make your second subscript sort of safe
:
extension Collection {
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
subscript (offsetBy int: Int) -> Element? {
let index = self.index(self.startIndex, offsetBy: int)
return self[safe: index]
}
}
Even in such cases, you should better use different labels for your two subscript
declarations to avoid ambiguity.