Subclass a Struct or Similar - swift

I understand how structs and classes (and protocols) work on the basic level. I have a rather common situation:
I need to have generic value types with operators which really must copy on assignment.
These types have complex structure and I would like to be able to specialise by subclassing otherwise there will be copied code everywhere and it will be poor programming.
I have tried protocols and extensions but then because the protocol wasn't generic I was unable to define the (generic) operators I wanted.
If I use classes I will not copy on assignment.
Today's example is I have Matrix, and SquareMatrix under that with specific square matrix functions. There are operators and the matrices can be populated by anything conforming to my ring protocol. I tried defining almost all the functionality in a protocol with associated type, and an extension.
Edit: I am really wondering what I should be coding. In the matrix situation I need to be able to pass a square matrix as any other, so subclassing is the only option? Maybe I'm wrong. The main issue is when I have to write a function which talks about internal values, I have to know the generic type argument to do anything useful. For example when defining addition, I have to create a new matrix and declare its generic type, but where do I get that from when I only know something is a (nongeneric) protocol - it's real type is generic but despite the protocol having this associated type, I have no way of getting it out.
Solution thanks to alexander momchliov. Essentially more work was needed to move code into the protocol extension fully and use 'Self' for all the relevant types. In the extension the compiler was happy with what the generic types were.
The code was private, I am sorry I was unable to paste any during this question. Thanks for your patience and help.

Struct inheritance/polymorphism wouldn't be possible for at least 2 reasons (that I can think of).
Structs are stored and moved around by value. This requires the compiler to know, at compile time, the exact size of the struct, in order to know how many bytes to copy after the start of a struct instance.
Suppose there was a struct A, and a struct B that inherits from A. Whenever the compiler sees a variable of type A, it has no way to be sure if the runtime type will really be an A, or if B was used instead. If B added on new stored properties that A didn't have, then B's size would be different (bigger) than A. The compiler would be unable to determine the runtime type, and the size of these structs.
Polymorphism would require a function table. A function table would be stored as a static member of the struct type. But to access this static member, every struct instance would need an instance member which encodes the type of the instance. This is usually called the "isa" pointer (as in, this instance is a A type). This would be 8 bytes of overhead (on 64 bit systems) for every instance. Considering Int, Bool, Double, and many other common types are all implemented as structs, this would be an unacceptable amount of overhead. Just think, a Bool is a one byte value, which would need 8 bytes of overhead. That's 11% efficiency!
For these reasons, protocols play a huge part in Swift, because they allow you introduce inheritance-like behaviour, without these issues.

First of all, in swift the protocol can be generic if you will use associatedtype.
On the over hand, you need the Value Semantics, so you can use Copy on Write methodology. This will give the value semantic to your classes (so they will be as safe as structs).
This both ways can be used to solve your problem.

Related

Is there a standard protocol for Swift class/struct with an empty initializer

I'm curious, is there a pre-existing protocol whose only requirement is that there be an init with no arguments? I'm creating a generic that needs to be able to initialize an associated type without worrying about any arguments. This seems to call for a protocol like this:
protocol HasEmptyInitializer {
init()
}
It seems like a pretty basic protocol that might be needed in many contexts. Before I go polluting my protocol space with the above, I was wondering if there is anything like that already in Foundation or other 1st party library. Does anyone know of such a thing?
This is a very famous non-protocol because it lacks semantics. For the background on why this is intentionally not a protocol in Swift, see Ole Begemann's writeup Protocols are more than Bags of Syntax. If you have a semantically meaningful protocol that only has this requirement, then there is no problem creating it, but it is quite rare.
The fundamental point of Ole's writeup (which gathers together many other conversations) is that a protocol is more than just "it has this method" (i.e. syntax). It's about what kinds of algorithms it facilitates. "Plusable" wouldn't be a good protocol to cover "things you can apply + to." What + means for Ints is not really the same as what + means for Collections (the latter isn't even commutative). Similarly, "makable by calling init()" tells you nothing about what the resulting object means. Is is "empty?" Some unspecified "default" value? Invalid? The semantics of protocols matter more than the syntax.

What is the benefit of defining enumerators as a DUT?

The main goal of defining enumerators is to assign a variable to some numbers and their equal strings as I understand.
We can define var a as an enum everywhere in the initializing section of our Program or Function Block like this:
a:(start,stop,operate);
tough I don't know why we can't see that in tabular view but there there is a big question that:
What is the benefit of defining enumerators as a DUT?
There are 3 main benefits for me:
You can use the same enum in multiples function blocks
You can use TO_STRING on enums declared as DUTs (After enabling it with {attribute 'to_string'} Infosys
You can use refactoring on names of each component, which is impossible with local enums
When defining an enum as a DUT it is available everywhere in your code (global scope).
This is helpful in many cases, but in general it is not good programming practice to have a lot of stuff available in the global scope.
Here is a bit elaboration on the topic.
In addition to the above, one benefit is that if you are using an enumeration for something like FB states, you will be able to see the descriptive status name when the program is running (READING, WRITING, WAITING, ERROR, etc.).
You can see it in the variable declarations section, in-line with your code, or in the watch window. You don’t have to remember what status number was defined in your state machine.
This benefit comes with local enumerations or DUT (global) enumerations.
In addition to other good points already made, there is another big advantage to enumerations : you can use the enumeration as the type of a variable, and when you do that, the compiler will (if {attribute 'strict'} is used in the enumeration declaration, which it probably should) refuse an assignment to that variable of a value that is not allowed by the enumeration.
In other words, you get rid of a whole class of failure modes where the variable ends up having an invalid value due to some coding mistake the compiler cannot catch.
It takes a trivial amount of time to create an enumeration, and it has benefits on many levels. I would say the real question is why not use them whenever a fixed list of meaningful values needs to be expressed.

Swift structs: Protocol (w/asoc. types) v/s Composition

I’m refactoring a Linear Algebra library. It includes a Vector, Matrix and Tensor structs. So far so good, but since the three of them are conceptually Tensors, they share a lot of properties and underlying behavior. Therefore, I’m trying a refactor to be able to share more code and tests between them.
But I’m fairly new to Swift, and I’m not sure if I should do it with Protocols:
TensorProtocol with Associated Type (“T”).
Extension over TensorProtocol which implements all the common behavior as the “default” for the protocol.
Tensor, Matrix and Vector which conform to TensorProtocol.
The advantage of this approach is that common behavior is shared in one place, and can be overriden for customization.
The disadvantages are:
TensorProtocol doesn’t let me specify internal logic. I can only have public variables if I want to make the protocol public.
I can’t aggregate the structs for Testing, I think? Because Protocols with AT can’t be used as variable types.
Because of this I thought of a second option:
TensorSkeleton struct, with all the behavior of a Tensor inside of a struct.
TensorProtocol, which only defines the API of a Tensor.
Tensor, Matrix and Vector, all of which contain a TensorSkeleton and use it to conform to the TensorProtocol.
This approach allows me to:
Reuse all of the Tensor logic for the three structs.
TensorSkeleton can have a finer design than a protocol. Since it’s a struct, it can have internal and private fields and functions.
Testing the TensorSkeleton is (at least for me) easier than it would be to test a Protocol. And by testing it, I’m giving guarantees over all of the structs that use it.
But it has two disadvantages:
It still doesn’t allow me to aggregate for Testing (same as the first approach), and...
This model clashes with me. I come from C#, where this would’ve been solved with abstract classes and class inheritance (Matrix : Tensor, and such). Is my concern justified? I have never used a model where inherited traits were passed down with composition instead of class inheritance.
I know Linear Algebra objects are much better suited as structs, but I still have doubts about this design.
Thank you very much, and I’m sorry for the wall of text. Have a great day.

Where to define typecast to struct in MATLAB OOP?

In the MATLAB OOP framework, it can be useful to cast an object to a struct, i.e., define a function that takes an object and returns a struct with equivalent fields.
What is the appropriate place to do this? I can think of several options:
Build a separate converter object that takes care of conversions between various classes
Add a function struct to the class that does the conversion to struct, and make the constructor accept structs
Neither option seems to be very elegant: the first means that logic about the class itself is moved to another class. On the other hand, in the second case, it provokes users to use the struct function for any object, which will in general give a warning (structOnObject).
Are there altenatives?
Personally I'd go with the second option, and not worry about provoking users to call struct on other classes; you can only worry about your own code, not that of a third-party, even if the third party is MathWorks. In any case, if they do start to call struct on an arbitrary class, it's only a warning; nothing actually dangerous is likely to happen, it's just not a good practice.
But if you're concerned about that, you can always call your converter method toStruct rather than struct. Or perhaps the best (although slightly more complex) way might be to overload cast for your class, accepting and handling the option 'struct', and passing any other option through to builtin('cast',....
PS The title of your question refers to typecasting, but what your after here is casting. In MATLAB, typecasting is a different operation, involving taking the exact bits of one type and reinterpreting them as bits of another type (possibly an array of the output type). See doc cast and doc typecast for more information on the distinction.
The second option sounds much better to me.
A quick and dirty way to get rid of the warning would be disabling it by calling
warning('off', 'MATLAB:structOnObject')
at the start of your program.
The solutions provided in Sam Roberts' answer are however much cleaner. I personally would go for the toStruct() method.

What is the role of the "interface {}" syntax in Go?

I've read through the Effective Go and Go Tutorials as well as some source, but the exact mechanism behind the interface {} syntax is Go is somewhat mysterious to me. I first saw it when trying to implement heap.Interface and it seems to be a container of some kind (reminds me of a monad a little) from which I can extract values of arbitrary type.
Why is Go written to use this? Is it some kind of workaround for generics? Is there a more elegant way to get values from a heap.Interface than having to dereference them with heap.Pop(&h).(*Foo) (in the case of a heap pointers to type Foo)?
interface{} is a generic box that can hold everything. Interfaces in go define a set of methods, and any type which implements these methods conforms to the interface. interface{} defines no methods, and so by definition, every single type conforms to this interface and therefore can be held in a value of type interface{}.
It's not really like generics at all. Instead, it's a way to relax the type system and say "any value at all can be passed here". The equivalent in C for this functionality is a void * pointer, except in Go you can query the type of the value that's being held.
Here is an excellent blog post that explains what is going on under the hood.