[swift-evolution] Figuring out what you get for free
Michel Fortin
michel.fortin at michelf.ca
Sun Sep 17 18:32:23 CDT 2017
> Le 17 sept. 2017 à 18:00, Félix Cloutier via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> a écrit :
>
> I found that for Sequence, but Sequence is far from the only protocol with default implementations, and not all of them have maintainers willing to write and update documentation to the degree that Apple will.
How I do it is like this:
1. Make a dummy struct (or class) that claim conformance to a protocol:
struct Z: Collection {
}
2. Compiling, then deciphering the errors tells me that type deduction doesn't work for associated type `Index` because there is no subscript. So I add one:
struct Z: Collection {
subscript (index: Int) -> Int {
get { return index }
}
}
3. Compiling again, I now get a suggestion (fixit) telling me to add `startIndex` and `endIndex`. I add the suggested code:
struct Z: Collection {
var startIndex: Int
var endIndex: Int
subscript (index: Int) -> Int {
get { return index }
}
}
4. Compiling again, I get another suggestion (fixit) telling me I'm missing `index(after:)`. I add it and write an implementation inside the braces. And here I am:
struct Z: Collection {
func index(after i: Int) -> Int {
return i + 1
}
var startIndex: Int
var endIndex: Int
subscript (index: Int) -> Int {
get { return index }
}
}
5. And now it compiles. Hurray!
I made a collection type and did not have to read any documentation at all. The hardest step is the first one where you have to figure out how to make deduction work for the associated types based on the error messages.
--
Michel Fortin
https://michelf.ca <https://michelf.ca/>
--
Michel Fortin
https://michelf.ca
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170917/348af4bd/attachment.html>
More information about the swift-evolution
mailing list