SequenceType in Swift implements _Sequence_Type but these two protocols seem basically the same. Why is it implemented this way?
protocol SequenceType : _Sequence_Type {
typealias Generator : GeneratorType
func generate() -> Generator
}
protocol _SequenceType {
}
protocol _Sequence_Type : _SequenceType {
/// A type whose instances can produce the elements of this
/// sequence, in order.
typealias Generator : GeneratorType
/// Return a generator over the elements of this sequence. The
/// generator's next element is the first element of the sequence.
func generate() -> Generator
}
Protocols with leading underscores are Apple-private. The header for them typically does not include all of their actual methods. You can reverse engineer their actual methods by declaring a class to implement them, and see what the compiler says is missing. (The results are of course completely unsupported, and very likely to change between releases, which is why the particular protocol is likely private.)
In short, the answer is "because we don't actually know what's in those protocols."
Related
Widespread Protocol for Extensions
Swift 4.1, Xcode 9.3
I was wondering, what are some of the most overarching protocols in Swift. I want to make an extension that applies to values that can be set. The purpose of this was to make it easier to write more one-lined code.
My Extension:
Note: for the time being, the "overarching" protocol that I am extending is Equatable.
extension Equatable {
#discardableResult public func set(to variable: inout Self) -> Self {
variable = self
return self
}
}
Caveat: I would like to be able to use .set(to: ) for values that don't conform to Equatable as well.
Usage:
let ten = 10
var twenty = 0
(ten + 10).set(to: &twenty)
print(twenty)
// Prints "20"
This can be helpful when you need to set and return a value, now only one line of code is required to do so.
return value.set(to: &variable)
Final Question
How do I make .set(to: ) more far reaching, without needing multiple instances of it?
For example, if I wrote the same extension for Equatable, CustomStringConvertible, CVarArg, there would be multiple suggestions of the same extensions for many values that conform to all 3 of these protocols.
If this is not possible, what is the best overarching protocol that I can use?
Bonus Question: is there a way in an extension to do something not dissimilar to extension Equatable where !(Element: CustomStringConvertible) or extension Equatable where !(Element == Int) (use the where predicate for exclusion purposes)?
In most cases, I strong discourage this kind of code. "One-line" code is not generally a goal of Swift. Clear and concise is a goal, with clear winning when they're in conflict. Extending Any this way (even if it were legal) is generally a very bad idea since set(to:) could easily collide.
But in limited circumstances this may be useful within a single file or for a special use. In that case, it's easily implemented with operators.
infix operator -->
private func --> <T>(lhs: T, rhs: inout T) -> T {
rhs = lhs
return lhs
}
let ten = 10
var twenty = 0
(ten + 10) --> twenty
print(twenty)
// Prints "20"
The more natural way to do what you're describing is with protocols that you explicitly conform. For example:
protocol Settable {}
extension Settable {
#discardableResult public func set(to variable: inout Self) -> Self {
variable = self
return self
}
}
extension Int: Settable {}
extension String: Settable {}
extension Array: Settable {}
extension Optional: Settable {}
You can attach Settable to any types that are useful for this purpose, and these extensions can be provided anywhere in the project (even in other modules). There is no way to attach a method to every possible type in Swift.
Lets say I have two protocols:
protocol TheirPcol {}
protocol MyPcol {
func extraFunc()
}
What I want to do is to create a protocol extension for 'TheirPcol' which lets extraFunc() work on anything which conforms to 'TheirPcol'. So something like this:
extension TheirPcol : MyPcol { // Error 'Extension of protocol 'TheirPcol' cannot have an inheritance clause.
func extraFunc() { /* do magic */}
}
struct TheirStruct:TheirPcol {}
let inst = TheirStruct()
inst.extraFunc()
The kicker in this is that 'TheirPcol', 'TheirStruct' are all handled by an external API which I do not control. So I'm passed the instance 'inst'.
Can this be done? Or am I going to have to do something like this:
struct TheirStruct:TheirPcol {}
let inst = TheirStruct() as! MyPcol
inst.extraFunc()
It seems there are two use-cases of why you may want to do what you are doing. In the first use-case, Swift will allow you to do what you want, but not very cleanly in the second use-case. I'm guessing you fall into the second category, but I'll go through both.
Extending the functionality of TheirPcol
One reason why you might want to do this is simply to give extra functionality to TheirPcol. Just like the compiler error says, you cannot extend Swift protocols to conform to other protocols. However, you can simply extend TheirPcol.
extension TheirPcol {
func extraFunc() { /* do magic */ }
}
Here, you are giving all objects that conform to TheirPcol the method extraFunc() and giving it a default implementation. This accomplishes the task of extending functionality for the objects conforming to TheirPcol, and if you want it to apply to your own objects as well then you could conform your objects to TheirPcol. In many situations, however, you want to keep MyPcol as your primary protocol and just treat TheirPcol as conforming to MyPcol. Unfortunately, Swift does not currently support protocol extensions declaring conformance to other protocols.
Using TheirPcol objects as if they were MyPcol
In the use case (most likely your use case) where you really do need the separate existence of MyPcol, then as far as I am aware there is no clean way to do what you want yet. Here's a few working but non-ideal solutions:
Wrapper around TheirPcol
One potentially messy approach would be to have a struct or class like the following:
struct TheirPcolWrapper<T: TheirPcol>: MyPcol {
var object: T
func extraFunc() { /* Do magic using object */ }
}
You could theoretically use this struct as an alternative to casting, as in your example, when you need to make an existing object instance conform to MyPcol. Or, if you have functions that accept MyPcol as a generic parameter, you could create equivalent functions that take in TheirPcol, then convert it to TheirPcolWrapper and send it off to the other function taking in MyPcol.
Another thing to note is if you are being passed an object of TheirPcol, then you won't be able to create a TheirPcolWrapper instance without first casting it down to an explicit type. This is due to some generics limitations of Swift. So, an object like this could be an alternative:
struct TheirPcolWrapper: MyPcol {
var object: MyPcol
func extraFunc() { /* Do magic using object */ }
}
This would mean you could create a TheirPcolWrapper instance without knowing the explicit type of the TheirPcol you are given.
For a large project, though, both of these could get messy really fast.
Extending individual objects using a child protocol
Yet another non-ideal solution is to extend each object that you know conforms to TheirPcol and that you know you wish to support. For example, suppose you know that ObjectA and ObjectB conform to TheirPcol. You could create a child protocol of MyPcol and then explicitly declare conformance for both objects, as below:
protocol BridgedToMyPcol: TheirPcol, MyPcol {}
extension BridgedToMyPcol {
func extraFunc() {
// Do magic here, given that the object is guaranteed to conform to TheirPcol
}
}
extension ObjectA: BridgedToMyPcol {}
extension ObjectB: BridgedToMyPcol {}
Unfortunately, this approach breaks down if there are a large number of objects that you wish to support, or if you cannot know ahead of time what the objects will be. It also becomes a problem when you don't know the explicit type of a TheirPcol you are given, although you can use type(of:) to get a metatype.
A note about Swift 4
You should check out Conditional conformances, a proposal accepted for inclusion in Swift 4. Specifically, this proposal outlines the ability to have the following extension:
extension Array: Equatable where Element: Equatable {
static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool { ... }
}
While this is not quite what you are asking, at the bottom you'll find "Alternatives considered", which has a sub-section called "Extending protocols to conform to protocols", which is much more what you're trying to do. It provides the following example:
extension Collection: Equatable where Iterator.Element: Equatable {
static func ==(lhs: Self, rhs: Self) -> Bool {
// ...
}
}
Then states the following:
This protocol extension would make any Collection of Equatable elements Equatable, which is a powerful feature that could be put to good use. Introducing conditional conformances for protocol extensions would exacerbate the problem of overlapping conformances, because it would be unreasonable to say that the existence of the above protocol extension means that no type that conforms to Collection could declare its own conformance to Equatable, conditional or otherwise.
While I realize you're not asking for the ability to have conditional conformances, this is the closest thing I could find regarding discussion of protocols being extended to conform to other protocols.
I'm working on a framework to make it easier to work with Key Value Observing and I've defined a protocol for converting native Swift types to NSObject as follows:
public protocol NSObjectConvertible {
func toNSObject () -> NSObject
}
Extending the builtin types was easy, simply defining the function to convert the given type to the appropriate NSObject:
extension Int8: NSObjectConvertible {
public func toNSObject () -> NSObject {
return NSNumber(char: self)
}
}
When I got to the Array type, I hit a number of snags, which I tried to work out. I didn't want to extend any array type, but only arrays whose element type was itself NSObjectConvertible. And naturally, needed Array to itself conform to the protocol.
After hunting around on SO, it looks like extending the Array type itself is a little harder because it's generic, but extending SequenceType can be done. Except that I can't both constrain the element type and declare its conformance to the protocol in the same declaration.
The following:
extension SequenceType where Generator.Element == NSObjectConvertible : NSObjectConvertible = {
public func toNSObject () -> NSObject {
return self.map() { return $0.toNSObject() }
}
}
Produces a compiler error:
Expected '{' in extension
And the carat points to the ":" where I'm trying to declare the protocol conformance. Removing the protocol conformance compiles without errors, but obviously doesn't help the case.
I'm not sure if this is a bug, or if Swift simply can't (or doesn't want to) support what I'm trying to do. Even if I simply define the extension, then try to take care of the conformance in the body, it produces the risk of passing sequences that don't really conform to what they should.
At best it's a hacky solution to just fail in cases where a sequence with non-conforming members are passed. I'd much rather let the compiler prevent it from happening.
(This is in Swift 2.1, Xcode 7.1.1)
You can't add the protocol conformance, unfortunately.
Dictionaries in Swift don't conform to ExtensibleCollectionType. Since it would be easy to extend it (it somehow doesn't work with Swift 1.2; using Swift 2):
extension Dictionary: ExtensibleCollectionType {
// ignoring this function
mutating public func reserveCapacity(n: Int) {}
mutating public func append(x: Dictionary.Generator.Element) {
self[x.0] = x.1
}
mutating public func extend<S : SequenceType where S.Generator.Element == Dictionary.Generator.Element>(newElements: S) {
for x in newElements {
self.append(x)
}
}
}
If you do so Dictionaries can also be added (see also: Adding SequenceTypes)
Is there any benefit don't implementing this in the standard library?
As of Xcode 7 beta 5 ExtensibleCollectionType was renamed (and restructured) to RangeReplaceableCollectionType. So the intention conforming to this protocol is more clear:
The new protocol only requires this method to fully conform to it:
mutating func replaceRange<C : CollectionType where C.Generator.Element == Generator.Element>(subRange: Range<Self.Index>, with newElements: C)
This wouldn't make much sense for any unordered collections since this operation isn't predictable (except for the element count in some cases). Also the default implementations and other requirements which highly rely on the index aren't that useful for such collections.
In conclusion insertions and replacements of ranges should be predictable and preserve the structure/ordering of the other elements. Therefore Dictionaries and any other unordered collection shouldn't conform to this particular protocol.
How do I say in Swift's type system "an Array<T> conforms to protocol P if the element type T conforms to protocol Q"?
I'm actually interested in a more specific version of this problem, where P and Q are the same protocol: you're saying "if the elements of the array are P-conforming, then the array is P-conforming". Here's what I have so far. (I'm trying for a simple QuickCheck library, starting from http://chris.eidhof.nl/posts/quickcheck-in-swift.html: Arbitrary marks types that can be randomly generated.)
protocol Arbitrary {
class func arbitrary() -> Self
}
extension Array {
static func arbitrary<T where T : Arbitrary>() -> [T] {
// code to create a random-length list of T objects
// using T.arbitrary() for each one
}
}
extension Array<T where T : Arbitrary> : Arbitrary {}
This fails with the error
extension of generic type 'Array' cannot add requirements
extension Array<T where T : Arbitrary> : Arbitrary {}
You can't do this in Swift, since you can't further constrain a generic type. For example, you can't add methods to Array<T> that only work when T is Comparable - that's why there are so many global functions for dealing with generic types (map, filter, sort, etc.).
From a recent Chris Lattner posts in the dev forums, it sounds like the Swift developers are headed in this direction, but it's nowhere near this yet. See if you can implement what you're trying to do as global functions that constrain T to Arbitrary:
func arbitrary<T: Arbitrary>() -> [T] {
// ..
}