<html><head><meta http-equiv="Content-Type" content="text/html charset=utf-8"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class=""><div class="">This has been proposed before. The current implementation is intentional, as seen on the swift-evolution repo: <a href="https://github.com/apple/swift-evolution/blob/master/commonly_proposed.md#strings-characters-and-collection-types" class="">https://github.com/apple/swift-evolution/blob/master/commonly_proposed.md#strings-characters-and-collection-types</a>. This is why: <a href="https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/002446.html" class="">https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/002446.html</a></div><div class=""><br class=""></div>
> Recently I’ve been considering the lack of safety around array indexes. Swift is designed with safety in mind, so this example would not compile:<br class="">> <br class="">> var myString: String? = “hello”<br class="">> myString.append(“ world!”)<br class="">> <br class="">> The string is optional, not guaranteed to exist, so the last line requires a “!” to force-unwrap it.<br class="">> <br class="">> <br class="">> <br class="">> public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->Int {<br class="">> let section = self.sections[section]<br class="">> <br class="">> return section.items.count<br class="">> }<br class="">> <br class="">> In this example, we could provide a section number that goes beyond the bounds of the self.sections array, without any warning.<br class="">> <br class="">> My suggestion is perhaps arrays should by default return an optional when given an index, and of course they’d support forced-unwrapping too. So you could then do this:<br class="">> <br class="">> let section = self.sections[section]<br class="">> if section == nil {<br class="">> return 0<br class="">> } else {<br class="">> return section!.items.count<br class="">> }<br class="">> <br class="">> Or you could do this:<br class="">> <br class="">> let section = self.sections[section]!<br class="">> <br class="">> return section.items.count<br class="">> <br class="">> <br class="">> <br class="">> Of course this would be less convenient in a lot of cases, but this is the 1 place where apps seem to encounter a crash, crashing for the same reason that’s especially avoided across most of the rest of Swift._______________________________________________<br class="">> swift-evolution mailing list<br class="">> <a href="mailto:swift-evolution@swift.org" class="">swift-evolution@swift.org</a><br class="">> <a href="https://lists.swift.org/mailman/listinfo/swift-evolution" class="">https://lists.swift.org/mailman/listinfo/swift-evolution</a><br class="">> <br class="">> <br class="">><span class="Apple-converted-space"> </span>
</body></html>