Generics and protocol conformance in Swift functions - swift

I just read Brent Simmon's post on a problem he is having with Swift and I thought I had the answer: generic protocol conformance.
The problem he's having is that he has a protocol, Value, that conforms to Equatable. He has another protocol, Smashable, that requires the function valueBySmashingOtherValue. He has a struct, Bar, that does in fact conform to Smashable and Value.
In a subsequent function that takes a generic type T, a Bar is returned. The Swift type system complains that 'Bar' is not convertible to 'T'.
Here's what I thought would work:
protocol Value: Equatable { }
protocol Smashable {
func valueBySmashing​OtherValue​<T: Value, Smashable>(value: T) -> T
}
struct Bar: Smashable, Value {
func valueBySmashing​OtherValue​<T: Value, Smashable>(value: T) -> T {
return value;
}
}
func ==(lhs: Bar, rhs: Bar) -> Bool {
return false
}
struct Foo {
func valueBySmashing​OtherValue​<T: Value, Smashable>(value: T) -> T {
return Bar()
}
}
Make the generic type T conform to Value and Smashable. Bar does in fact conform to these, so the type system should be fine with you returning it.
But it isn't. Why?

While it is true that Bar conforms to Value and Smashable it is not the only type that meets those criteria. I could create a new type (using latest Swift syntax):
struct NotBar: Smashable, Value {
func valueBySmashing​OtherValue​<T:Value where T:Smashable>(value: T) -> T {
return value;
}
}
func ==(lhs: NotBar, rhs: NotBar) -> Bool {
return true
}
If I passed an instance of NotBar into Foo.valueBySmashing​OtherValue, then I would expect a NotBar in return. The compiler knows this so it does not allow you to return a Bar.

Related

Constraining a generic initilizer parameter to class generic type

I'm trying to implement a type erasing wrapper for a protocol. I have a protocol with an associatedtype constrainted to CaseIterable and a method using that type.
Given the following definitions:
protocol Foo {
associatedtype A: CaseIterable
func doSomething(input: A)
}
final class AnyFoo<A: CaseIterable>: Foo {
private let _doSomething: (A) -> Void
init<Other: Foo>(wrappedFoo: Other) where Other.A == A {
// "Cannot assign value of type '(Other.A) -> ()' to type '(A) -> Void'"
_doSomething = wrappedFoo.doSomething(input:)
}
func doSomething(input: A) {
_doSomething(input)
}
}
I'm getting the error Cannot assign value of type '(Other.A) -> ()' to type '(A) -> Void' in the initializer of the class. It seems that the compiler interprets A and Other.A as different types, and I can't figure out why, because the initializer has constrained Other.A and A to be the same. If I replace CaseIterable with Hashable, there's no problem.
Can somebody explain why this is happening?
Of course you can't. The _doSomething in class AnyFoo is type of Block which is an Anonymous function. So you can assign wrappedFoo.doSomething(input:) to it. When you call _doSomething(input), it actually call wrappedFoo.doSomething(input: input).
In another way, you can define a Block like:
let completion: (bool) -> void = { finished in
}
but you can't define it like:
let completion: (true) -> void = { finished in
}

Swift protocol conformance when returning a generic

Here's an example:
protocol Feed {
func items<T>() -> [T]? where T: FeedItem
}
protocol FeedItem {}
class FeedModel: Feed, Decodable {
func items<T>() -> [T]? where T : FeedItem {
return [FeedItemModel]() // Error: Cannot convert return expression of type '[FeedItemModel]' to return type '[T]?'
}
}
class FeedItemModel: FeedItem, Decodable {}
Why does it:
A) try to convert to T when T is a generic, not a type?
B) does not recognize FeedItemModel as conforming to FeedItem?
func items<T>() -> [T]? where T : FeedItem
This says that the caller can define T to be whatever they want, as long as T conforms to FeedItemModel, and this function will return an optional array of those.
FeedItemModel is something that conforms to FeedItem, but it is not promised to be the type T that the caller requested.
As an example, consider:
class OtherModel: FeedItem {}
According to your function signature, I can do this:
let ms: [OtherModel]? = FeedModel().items()
But your function won't then return [OtherModel]? to me. I suspect you don't actually mean this to be generic. I expect you mean:
func items() -> [FeedItemModel]?
or possibly
func items() -> [FeedItem]?
(Though I would think very hard before doing the latter one and make sure that the protocol existential is really doing useful work here.)
A)
T is a type, a homogenous concrete type specified at runtime.
Imaging T is class Foo : FeedItem it's obvious that FeedItemModel cannot be converted to Foo
B)
FeedItemModel is recognized as conforming to FeedItem but this is irrelevant.
It's often a mix-up of generics and protocols. Generic types are not covariant. If you need covariant types use an associated type.
Either you can ignore generics because because it only applies to that one function and it isn't needed since directly saying that the return type is [FeedItem]? yields the same result
protocol Feed {
func items() -> [FeedItem]?
}
class FeedModel: Feed, Decodable {
func items() -> [FeedItem]? {
return [OtherModel]()
}
}
If you on the other hand want a generic protocol then you should use a associated type
protocol Feed2 {
associatedtype T: FeedItem
func items() -> [T]?
}
class FeedModel2: Feed2, Decodable {
typealias T = FeedItemModel
func items() -> [T]? {
return [FeedItemModel]()
}
}

SwifT: Generic function that gets generic protocol as parameter not working

Suppose I have this simple generic protocol
protocol FooProtocol {
associatedtype Element: CustomStringConvertible
func echo(element: Element) -> Element
}
And this simple generic struct that implements it
struct FooStruct<Element: CustomStringConvertible>: FooProtocol {
func echo(element: Element) -> Element {
return element
}
}
Lastly, I have the following function:
func callEcho<T: FooProtocol>(container: T) {
container.echo(element: "some string")
}
This results in error: cannot invoke 'echo' with an argument list of type '(element: String)'
The solution is to change the function to
func callEcho<T: FooProtocol>(container: T) where T.Element == String {
container.echo(element: "some string")
}
My question is: why is the where T.Element == String constraint necessary? The compiler knows that T is some entity that implements FooProtocol, and the protocol only demands that Element implements CustomStringConvertible, which my string literal does. So why does it not work without the constraint?
Thanks!
I'm not sure why you say "the protocol only demands that Element implements CustomStringConvertible." The protocol demands that echo accept and return its Element, which may or may not be String. For example, I can implement this conforming type:
struct AnotherFoo: FooProtocol {
func echo(element: Int) -> Int { fatalError() }
}
So what should happen if I then call:
callEcho(container: AnotherFoo())
This would try to pass a string literal to a function that requires an Int.
container has type T, so that container.echo(element:) expects an argument of type T.Element – and that is not necessarily a string.
If the intention is to pass string literals to the method then T.Element must adopt ExpressibleByStringLiteral, not CustomStringConvertible:
protocol FooProtocol {
associatedtype Element: ExpressibleByStringLiteral
func echo(element: Element) -> Element
}
Now this compiles:
func callEcho<T: FooProtocol>(container: T) {
_ = container.echo(element: "some string")
}

Protocol associatedType and <>

what is a difference between using generic with function or using associatedType in swift protocols?
protocol Repository {
associatedtype T
func add(data : T) -> Bool
}
and
protocol Repository {
func add<T>(data : T) -> Bool
}
Defined associated type makes classes which conform protocol strong typed. This provide compile-time error handling.
In other hand, generic type makes classes which conform protocol more flexible.
For example:
protocol AssociatedRepository {
associatedtype T
func add(data : T) -> Bool
}
protocol GenericRepository {
func add<T>(data : T) -> Bool
}
class A: GenericRepository {
func add<T>(data : T) -> Bool {
return true
}
}
class B: AssociatedRepository {
typealias T = UIViewController
func add(data : T) -> Bool {
return true
}
}
class A could put any class into add(data:) function, so you need to makes your sure that function handle all cases.
A().add(data: UIView())
A().add(data: UIViewController())
both would be valid
But for class B you will get compile-time error when you will try to put anything except UIViewController
B().add(data: UIView()) // compile-time error here
B().add(data: UIViewController())
An associatedtype is a static type in struct/class which adopts the protocol either via a typealias declaration or via type inference. The type is always the same for that class.
A generic can be anything, even different types in the same class.
This case
protocol Repository {
func add<T>(data : T) -> Bool
}
Is understood by compiler like: "Any type that is fed to the func add will be acceptable and the result of the function will be Bool"
But this
protocol Repository {
associatedtype T
func add(data : T) -> Bool
}
is understood by compiler like: "func add will accept only the type that is defined in the typealias T = ... and return Bool"
In the second case you restrict generic parameters only to the typealiased types.
Another important feature shows up when you use generic parameters in multiple functions of the protocol. In that case it guarantees that func add<T> and func multiply<T> will have the same type T. In case of generic functions it is not guaranteed.
protocol Calculable {
associatedtype T
func add<T>(a: T, b: T) -> T
func multiply<T>(a: T, b: T) -> T
}
// In this case you know that T is the same for all functions
protocol CalculableDifferent {
func add<T>(a: T, b: T) -> T
func multiply<T>(a: T, b: T) -> T
}
// In this case add can accept One type, when multiply can accept Another

Swift Type Constraints not working as expected

I've been dabbling with Swift recently, and I've hit a weird stumbling block with type constraints not operating as I would expect they should (in comparison to say, Scala).
protocol Foo {
typealias T: Hashable
func somethingWithT() -> T
}
struct Bar: Foo {
typealias T = Int
func somethingWithT() -> T { return 1 }
}
func baz() -> [Foo] {
var myBars = [Foo]()
myBars.append(Bar())
return myBars
}
This throws an error in XCode:
Any ideas what is going on here? I want T to be hashable for use as a key in a dictionary, but from what I've read Hashable has a reference to Self somewhere, so it can only be used as a generic constraint, thus removing my ability to just have a [Foo].
I want to have a list of things that do Foo, but at this rate it seems I'll either have to remove the Hashable constraint or make it less generic..
I've tried cleaning my project and re-making, but no dice :(
The problem here is that the type of T (of the protocol) has to be known at runtime. Due to the lack of generics with type aliases you can work around that by making an AnyFoo type (like in the standard library AnyGenerator and AnySequence):
protocol Foo {
typealias T: Hashable
func somethingWithT() -> T
}
struct AnyFoo<T: Hashable>: Foo {
let function: () -> T
init<F: Foo where F.T == T>(_ foo: F) {
// storing a reference to the function of the original type
function = foo.somethingWithT
}
func somethingWithT() -> T {
return function()
}
}
struct Bar: Foo {
typealias T = Int
func somethingWithT() -> T { return 1 }
}
// instead of returning [Foo] you can return [AnyFoo<Int>]
func baz() -> [AnyFoo<Int>] {
var myBars = [AnyFoo<Int>]()
// converting the type or Bar
myBars.append(AnyFoo(Bar()))
return myBars
}
This is not a generic function but you can convert any Foo type with the same T to the same AnyFoo type
myBars is an array of T: Foo. You could certainly pass in a Bar, because it satisfies the constraint on T. But so could another concrete type. Since T must be a concrete type, you can't arbitrarily put a Bar on there without guaranteeing that the only thing you'll put in there are Bars. And the only way to do that in Swift with this function signature would be to pass in a Bar.
I think maybe what you want is an array of protocol objects, not a generic array.