[swift-evolution] [Proposal]Allow constraints on associatedtype and shorten type constraints list in function
Susan Cheng
susan.doggie at gmail.com
Thu Jul 28 21:17:36 CDT 2016
Hello swift community,
I want to introduce a proposal to allow constraints on associatedtype.
I found a bug report(https://bugs.swift.org/browse/SR-1466) and it's due to
without constraints on associatedtype itself.
This force us always have to write the redundant constraints like
Indices.Iterator.Element
== Index or Indices.SubSequence.Iterator.Element == Index on type
constraints in function:
public extension MutableCollection where Self : RandomAccessCollection,
Indices.Index == Index, Indices.SubSequence : RandomAccessCollection,
Indices.SubSequence.Iterator.Element == Index {
/// Shuffle `self` in-place.
mutating func shuffle() {
for i in self.indices.dropLast() {
let j = self.indices.suffix(from: i).random()!
if i != j {
swap(&self[i], &self[j])
}
}
}
}
Besides this, we also can write some odd definitions but allowed by swift
compiler.
struct MyArray : Collection {
typealias Indices = CountableRange<Int32>
var base: [Int]
var startIndex: Int {
return base.startIndex
}
var endIndex: Int {
return base.endIndex
}
func index(after: Int) -> Int {
return after + 1
}
var indices: CountableRange<Int32> {
return CountableRange(uncheckedBounds: (lower: Int32(startIndex),
upper: Int32(endIndex)))
}
subscript(position: Int) -> Int {
get {
return base[position]
}
set {
base[position] = newValue
}
}
}
as a reference:
http://stackoverflow.com/questions/37581234/can-an-associated-type-be-restricted-by-protocol-conformance-and-a-where-clause
it's clearly that we need a syntax like this:
public protocol Collection : Indexable, Sequence {
/// A sequence that represents a contiguous subrange of the collection's
/// elements.
///
/// This associated type appears as a requirement in the `Sequence`
/// protocol, but it is restated here with stricter constraints. In a
/// collection, the subsequence should also conform to `Collection`.
associatedtype SubSequence : IndexableBase, Sequence where
SubSequence.Iterator.Element == Iterator.Element = Slice<Self>
/// A type that can represent the indices that are valid for
subscripting the
/// collection, in ascending order.
associatedtype Indices : IndexableBase, Sequence where
Indices.Iterator.Element == Index = DefaultIndices<Self>
}
This harmless and brings huge benefits to swift.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160729/0d687b85/attachment.html>
More information about the swift-evolution
mailing list