Swift generics complex inheritance - swift

The following Swift code does not compile:
class Entity {
}
class EntityConverter<T: Entity> {
}
class GetEntityServerAction<T: Entity, C: EntityConverter<T>> {
}
class GetEntityListServerAction<T: Entity, C: EntityConverter<T>>: GetEntityServerAction<T, C> {
}
with the error:
Type 'C' does not inherit from 'EntityConverter<T>'
for the GetEntityListServerAction class definition.
For some reasons the compiler doesn't see that C parameter is defined like inheriting exactly the same type it wants.
The code should look rather simple for those who are used to complicated generic hierarchies in Java or C# but the Swift compiler doesn't like something indeed.

You might find that using protocols and associated types is the more Swift-like way of doing things:
class Entity { }
protocol EntityConversionType {
// guessing when you say conversion, you mean from something?
typealias FromEntity: Entity
}
class EntityConverter<FromType: Entity>: EntityConversionType {
typealias FromEntity = FromType
}
class GetEntityServerAction<T: Entity, C: EntityConversionType where C.FromEntity == T> { }
class GetEntityListServerAction<T: Entity, C: EntityConversionType where C.FromEntity == T>: GetEntityServerAction<T, C> { }
let x = GetEntityListServerAction<Entity, EntityConverter<Entity>>()
Possibly GetEntityServerAction can also be represented by just a protocol, and that you could convert Entity, EntityConverter and GetEntityListServerAction to structs, also.

Related

Swift. How is it possible to get the name of an instance of a class within another class

Could the Swift Jedi help me, I'm new to Swift.
There is class A and class B.
Is it possible to get the name (var name = Class A() ) of an instance of class A in the code of class B, which would then be added to the array.
You can get the class of an object, using type(of: ...). Example:
class A {
func test() {
print (type(of: self))
}
}
class B : A{
}
let a = A()
a.test()
let b = B()
b.test()
However, this information is available only at runtime and not at compile time. You may for example display the name of the class. But you cannot dynamically create an array or a variable of that class.
If you need this, you need to design your classes using some kind of polymorphism. If all the classes have a base class in common, you can just define an array of the base class. If not, you may consider letting the classes of your design share some common protocol:
protocol MySpecs {
func test()
}
class AA : MySpecs {
...
}
class BB : MySpecs {
...
}
var mylist = [ MySpecs ]()
mylist.append(AA())
mylist.append(BB())
for x in mylist {
x.test()
}
There are other possibilities. But unless you provide more details it'll be difficult to be more specific in the recommendations.

Why can't I assign this protocol conforming class to a variable of the protocol type?

I've got a toy example here that I can't find any solutions for online.
protocol Tree {
associatedtype Element
// some nice tree functions
}
class BinaryTree<T> : Tree {
typealias Element = T
}
class RedBlackTree<T> : Tree {
typealias Element = T
}
enum TreeType {
case binaryTree
case redBlackTree
}
// Use a generic `F` because Tree has an associated type and it can no
// longer be referenced directly as a type. This is probably the source
// of the confusion.
class TreeManager<E, F:Tree> where F.Element == E {
let tree: F
init(use type: TreeType){
// Error, cannot assign value of type 'BinaryTree<E>' to type 'F'
switch(type){
case .binaryTree:
tree = BinaryTree<E>()
case .redBlackTree:
tree = RedBlackTree<E>()
}
}
}
I'm not sure what the problem here is or what I should be searching for in order to figure it out. I'm still thinking of protocols as I would interfaces in another language, and I view a BinaryTree as a valid implementation of a Tree, and the only constraint on F is that it must be a Tree. To confuse things even more, I'm not sure why the following snippet compiles given that the one above does not.
func weird<F:Tree>(_ f: F){ }
func test(){
// No error, BinaryTree can be assigned to an F:Tree
weird(BinaryTree<String>())
}
Any pointers or explanations would be greatly appreciated.
I don't understand the context of the situation this would be in. However, I have provided two solutions though:
1:
class Bar<F:Foo> {
let foo: FooClass.F
init(){
foo = FooClass.F()
}
}
2:
class Bar<F:Foo> {
let foo: FooClass
init(){
foo = FooClass()
}
}
What you are currently doing doesn't make logical sense, to whatever you are trying to achieve
I don't know what are you trying for, but of course it's not possible to do that. from your example, you attempt to create Bar class with generic. and that not the appropriate way to create a generic object, because the creation of generic object is to make the object to accept with any type.
Here's some brief explanation of the generic taken from Wikipedia.
On the first paragraph that says, "Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters."
it's very clear about what are the meaning of to-be-specified-later, right :)
Back to your example :
class Bar<F: Foo> {
let foo: F
init() {
// Error, cannot assign value of type 'FooClass' to type 'F'
foo = FooClass()
}
}
From the above code, it is type parameter F which has a constraint to a type Foo. and, you try to create an instance for foo variable with a concrete implementation, that is FooClass. and that's not possible since the foo variable is a F type(which is abstract). of course we can downcast it, like this foo = FooClass() as! F, but then the foo is only limited to FooClass, so why even bother with generic then ?
Hope it help :)
Your approach to this is wrong. In your original example, you would have to specify the type of both the element (E) and the container (BinaryTree or RedBlackTree), in addition to the enum value. That make no sense.
Instead, you should construct the manager to take a tree as the constructor argument, allowing Swift to infer the generic arguments, i.e.
class TreeManager<E, F: Tree> where F.Element == E {
var tree: F
init(with tree: F) {
self.tree = tree
}
}
let manager = TreeManager(with: BinaryTree<String>())
Alternatively, you should look into using opaque return types in Swift 5.1 depending on what the final goal is (the example here is obviously not a real world scenario)
Something like this seems reasonable. The point was to try and have some piece of logic that would determine when the TreeManager uses one type of Tree vs another.
protocol TreePicker {
associatedtype TreeType : Tree
func createTree() -> TreeType
}
struct SomeUseCaseA<T>: TreePicker {
typealias TreeType = RedBlackTree<T>
func createTree() -> TreeType {
return RedBlackTree<T>()
}
}
struct SomeUseCaseB<T>: TreePicker {
typealias TreeType = BinaryTree<T>
func createTree() -> TreeType {
return BinaryTree<T>()
}
}
class TreeManager<T, Picker: TreePicker> where Picker.TreeType == T {
let tree: T
init(use picker: Picker){
tree = picker.createTree()
}
This introduces another protocol that cares about picking the tree implementation and the where clause specifies that the Picker will return a tree of type T.
I think all of this was just the result of not being able to declare the tree of type Tree<T>. Its a bit more verbose but its basically what it would have had to look like with a generic interface instead. I think I also asked the question poorly. I should have just posted the version that didn't compile and asked for a solution instead of going one step further and confusing everyone.
protocol Foo {
associatedtype F
}
class FooClass : Foo {
typealias F = String
}
class Bar<M:Foo> {
let foo: M
init(){
foo = FooClass() as! M
}
}

Cast T to generic superclass with unknown type

Let's say I have an array of type Foo with FooBar objects in it.
Bar <T> class is a generic class that inherits from Foo.
Then I have multiple FooBar classes, that inherits from Bar<T>, each with different generic type. (Bar<Int>, Bar<String>).
The problem is that I need to walk through the array of type Foo, check if na object is of type Bar<T>, cast it to Bar and set it's property.
Buty Swift won't allow me to cast to unknown type <T> and Bar<Any> doesn't match Bar<Int> or another...
I came up with two possible solutions - add new class to the hierarchy that inherits from Foo and is parent of Bar, but is not generic, and cast to this one or implement a protocol (which seems as much better solution).
What I'm really not sure about is if protocols are meant for this kind of stuff. In C-like lang, I would use an interface probably.
//Edit: Sample code
class Foo {
}
class Bar<T> : Foo {
var delegate : SomeDelegate
}
class FooBar: Bar<Int> {
}
class FooBar2: Bar<String> {
}
let arr : [Foo] = [ FooBar(), FooBar2(), Foo() ]
for item in arr {
// this is the problem - I need to match both String,Int or whathever the type is
if let b = item as? Bar<Any> {
b.delegate = self
}
}

"subclassing" generic structs

Is it possible to subclass a generic struct in swift ?
assume we have a struct:
struct Foo<T> {}
and I wana "subclass" it to add some functionality:
struct Something {}
struct Bar<F>: Foo<Something> { /*<<<= ERROR: Inheritance from non-protocol type 'Foo<Something>' */
let store: Something
let someF: F
}
If you replace struct with class this example works.
class Foo<T> {}
//struct Bar1<T>: Foo<T> { /* Inheritance from non-protocol type 'Foo<T>' */
// let name = "Bar"
//}
class Something {}
class Bar<F>: Foo<Something> { /* Inheritance from non-protocol type 'Foo<Something>' */
let store: F?
init(value: F?) {
self.store = value
}
}
Any idea how to make this work for structs ?
I'm trying to stick to value types but swift is making it hard.
It's my understanding that inheritance is a central difference between classes and non-class objects like structs and enums in swift. Classes have inheritance, other objects types do not.
Thus I think the answer is "No, not now, and not ever, by design."
EDIT:
As pointed out by Ammo in his comment below, another crucial difference is the fact that class objects are passed by reference while non-class objects like structs are passed by value.

Can I cast a metaclass object to a protocol type in Swift?

Swift inherited Objective-C's metaclass concept: classes themselves are also considered objects. A class Foo's object's class is Foo.self, and it is of type Foo.Type. If Foo inherits from Bar, then Foo.self can be assigned to a variable of type Bar.Type, too. This has at least two benefits:
it allows to override "static methods";
it's easy to create an instance of an unknown class in a type-safe way and without using reflection.
I'm particularly looking at the second one right now. Just to be sure that everybody understands what I'm after, here's an example:
class BaseFoo {
var description: String { return "BaseFoo" }
}
class DerivedFoo: BaseFoo {
override var description: String { return "DerivedFoo" }
}
let fooTypes: [BaseFoo.Type] = [BaseFoo.self, DerivedFoo.self] // metaclass magic!
for type in fooTypes {
let object: BaseFoo = type() // metaclass magic!
println(object)
}
Now, I have an array of AnyClass objects (any metaclass instance can be assigned to AnyClass, just like any object can be assigned to AnyObject), and I want to find which ones implement a given protocol. The protocol would declare an initializer, and I would instantiate the class just like I do in the example above. For instance:
protocol Foo {
init(foo: String)
}
class Bar: Foo {
required init(foo: String) { println("Bar initialized with \(foo)") }
}
class Baz {
required init() { println("I'm not a Foo!") }
}
let types: [AnyClass] = [Bar.self, Baz.self]
So far so good. Now, the problem is determining if the class implements the protocol. Since metaclass instances are polymorphic, I'd expect to be able to cast them. However, I'm apparently missing something, because Swift won't let me write this:
for type in types {
if let fooType = type as? Foo.Type {
let obj = fooType(foo: "special snowflake string")
}
}
The compiler error I get is:
error: 'Foo' is not identical to 'AnyObject'
Is there any way to determine if a metaclass instance represents a class that implements a protocol, and is there any way to cast that instance into a protocol type?
I tried to declare Foo as a class protocol, but it's apparently not enough.
EDIT: I just tried with the Any type, and while it doesn't cause a syntax error, it crashes the Swift compiler.
As of Xcode 7 beta 2 and Swift 2 it has been fixed. You can now write:
for type in types {
if let fooType = type as? Foo.Type {
// in Swift 2 you have to explicitly call the initializer of metatypes
let obj = fooType.init(foo: "special snowflake string")
}
}
Or if you only want type as type Foo.Type you can use for case
for case let type as Foo.Type in types {
let obj = type.init(foo: "special snowflake string")
}