Reputation: 9925
I would like to encapsulate a utility functions. I hesitate between the Struct and Class types. Below a source code and a disassembly code.
The differences between the Struct and the Class types which I can mention are: Value vs Reference Type, Stack vs Heap allocation.
What are other differences between the Stack and Class types?
Which type is the best one to encapsulate a utility functions?
Code
struct testStruct {
static func methodStruct() { }
}
class testClass {
static func methodClass() { }
}
Disassembly
test`static testStruct.methodStruct():
0x10c168780 <+0>: pushq %rbp
0x10c168781 <+1>: movq %rsp, %rbp
-> 0x10c168784 <+4>: popq %rbp
0x10c168785 <+5>: retq
test`static testClass.methodClass():
0x10c168790 <+0>: pushq %rbp
0x10c168791 <+1>: movq %rsp, %rbp
0x10c168794 <+4>: movq %r13, -0x8(%rbp)
-> 0x10c168798 <+8>: popq %rbp
0x10c168799 <+9>: retq
Upvotes: 1
Views: 822
Reputation: 797
You can also use a static func on an enum:
enum testEnum {
static func methodEnum() {}
}
Because you can't instantiate an enum without initializers, you have better encapsulation.
Upvotes: 1
Reputation: 937
In a class you can use the class keyword for that kind of functions that you could then override in subclasses. Swift also supports global functions that you cannot use in ObjC though ...
If you can be sure to not have the necessarity to make use of for example class bound protocols or inheritance, then you are fine with a struct. If you are not sure, then use class.
However, this would be more of a concept discussion why you need a utility class. In most cases, you would want to create an extension to existing framework objects instead of creating a insanely huge "Utility.swift".
Upvotes: 0