Protocol extension doesn't seem to enforce variable in consumer? - ios

Say you
protocol Able: class {
var v:UIView? { get set }
var x:CGFloat { get set }
}
then of course, when you use Able,
if you forget "v" or "x"...
it is an error. That's good.
So do this:
class ScreenThing: UIViewController, Able {
#IBOutlet var v: UIView?
var x: CGFloat = 0.0
}
All's well. That's great.
It is enforced that you specify "v" and "x" and indeed initialize them.
But. Try this...
var _H: UInt8 = 0
protocol Able: class {
}
extension Able where Self:UIViewController {
var p:P {
get {
return objc_getAssociatedObject(self, &_H) as! P
}
set {
objc_setAssociatedObject(self, &_H, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
__setter()
}
}
}
Able now has a property p.
You can use p perfectly either in functions in Able, or, in functions in ScreenThing. That's great.
However.....
When you do this.....
class ScreenThing: UIViewController, Able {
}
you do not get an error.
You can forget to initialize "p" (it will crash).
Indeed you don't have to specify "p" as a variable (as you must with "v" and "x").
Why is it so?
This seems like a huge problem.
Is there something different I have to do, to, make the compiler enforce "p", just as it of course normally enforces variables in protocols?
Another way to look at this question:
Given exactly my code above:
is there a way to enforce the compiler to need an initializer for "p" in the consumer class?
For example.
I tried this...
class ScreenThing: UIViewController, Able {
var p:P
}
But that doesn't work.
(Strangely, that compiles - actually I don't know what the hell it's doing! It seems to be a "different" p from the p in the Extension. But in any event it doesn't enforce the need for an initializer.)
In short, again, is there something I could do or add, above, that would make the compiler enforce me initializing the pseudo-property-thing, just as of course it normally does when I put a property in the protocol such as "x" or "v".
?
maybe I have to add some ordinary property in the protocol (like "pp"), and somehow make p related to that in some way?? Just a thought.
(Footnote -- see this to understand the ": class" needed in the protocol above.)
Answering my own question:
My confusion above is that there is nothing to initialize. The var p:P in the extension (with the get and set code blocks) is simply two functions.
There's nothing to initialize.
So for example: in my extra question, I ask "how to force conforming classes initailize it on wake up?" That is meaningless. If anything, one could ask: "how to force conforming classes be sure to 'use those functions' on wake up?" - which has nothing to do with initialization.
Note too that my specific example code in the computed variable, happens to (unrelatedly) use a variable that doesn't get initialized - leading to confusion.

You don't have to implement p in the protocol's adopter, because the protocol extension has supplied an implementation. That is what a protocol extension is.
Simpler example:
protocol P {}
extension P {
func greet() {print("hello")}
}
class C : P {}
C().greet()
Note that (1) that compiles even though C does not declare greet and (2) it runs even though C does not contain an implementation of greet. That's because that's the job of the protocol extension.

Related

Associatedtype depends on protocol [duplicate]

Why doesn't this Swift code compile?
protocol P { }
struct S: P { }
let arr:[P] = [ S() ]
extension Array where Element : P {
func test<T>() -> [T] {
return []
}
}
let result : [S] = arr.test()
The compiler says: "Type P does not conform to protocol P" (or, in later versions of Swift, "Using 'P' as a concrete type conforming to protocol 'P' is not supported.").
Why not? This feels like a hole in the language, somehow. I realize that the problem stems from declaring the array arr as an array of a protocol type, but is that an unreasonable thing to do? I thought protocols were there exactly to help supply structs with something like a type hierarchy?
Why don't protocols conform to themselves?
Allowing protocols to conform to themselves in the general case is unsound. The problem lies with static protocol requirements.
These include:
static methods and properties
Initialisers
Associated types (although these currently prevent the use of a protocol as an actual type)
We can access these requirements on a generic placeholder T where T : P – however we cannot access them on the protocol type itself, as there's no concrete conforming type to forward onto. Therefore we cannot allow T to be P.
Consider what would happen in the following example if we allowed the Array extension to be applicable to [P]:
protocol P {
init()
}
struct S : P {}
struct S1 : P {}
extension Array where Element : P {
mutating func appendNew() {
// If Element is P, we cannot possibly construct a new instance of it, as you cannot
// construct an instance of a protocol.
append(Element())
}
}
var arr: [P] = [S(), S1()]
// error: Using 'P' as a concrete type conforming to protocol 'P' is not supported
arr.appendNew()
We cannot possibly call appendNew() on a [P], because P (the Element) is not a concrete type and therefore cannot be instantiated. It must be called on an array with concrete-typed elements, where that type conforms to P.
It's a similar story with static method and property requirements:
protocol P {
static func foo()
static var bar: Int { get }
}
struct SomeGeneric<T : P> {
func baz() {
// If T is P, what's the value of bar? There isn't one – because there's no
// implementation of bar's getter defined on P itself.
print(T.bar)
T.foo() // If T is P, what method are we calling here?
}
}
// error: Using 'P' as a concrete type conforming to protocol 'P' is not supported
SomeGeneric<P>().baz()
We cannot talk in terms of SomeGeneric<P>. We need concrete implementations of the static protocol requirements (notice how there are no implementations of foo() or bar defined in the above example). Although we can define implementations of these requirements in a P extension, these are defined only for the concrete types that conform to P – you still cannot call them on P itself.
Because of this, Swift just completely disallows us from using a protocol as a type that conforms to itself – because when that protocol has static requirements, it doesn't.
Instance protocol requirements aren't problematic, as you must call them on an actual instance that conforms to the protocol (and therefore must have implemented the requirements). So when calling a requirement on an instance typed as P, we can just forward that call onto the underlying concrete type's implementation of that requirement.
However making special exceptions for the rule in this case could lead to surprising inconsistencies in how protocols are treated by generic code. Although that being said, the situation isn't too dissimilar to associatedtype requirements – which (currently) prevent you from using a protocol as a type. Having a restriction that prevents you from using a protocol as a type that conforms to itself when it has static requirements could be an option for a future version of the language
Edit: And as explored below, this does look like what the Swift team are aiming for.
#objc protocols
And in fact, actually that's exactly how the language treats #objc protocols. When they don't have static requirements, they conform to themselves.
The following compiles just fine:
import Foundation
#objc protocol P {
func foo()
}
class C : P {
func foo() {
print("C's foo called!")
}
}
func baz<T : P>(_ t: T) {
t.foo()
}
let c: P = C()
baz(c)
baz requires that T conforms to P; but we can substitute in P for T because P doesn't have static requirements. If we add a static requirement to P, the example no longer compiles:
import Foundation
#objc protocol P {
static func bar()
func foo()
}
class C : P {
static func bar() {
print("C's bar called")
}
func foo() {
print("C's foo called!")
}
}
func baz<T : P>(_ t: T) {
t.foo()
}
let c: P = C()
baz(c) // error: Cannot invoke 'baz' with an argument list of type '(P)'
So one workaround to to this problem is to make your protocol #objc. Granted, this isn't an ideal workaround in many cases, as it forces your conforming types to be classes, as well as requiring the Obj-C runtime, therefore not making it viable on non-Apple platforms such as Linux.
But I suspect that this limitation is (one of) the primary reasons why the language already implements 'protocol without static requirements conforms to itself' for #objc protocols. Generic code written around them can be significantly simplified by the compiler.
Why? Because #objc protocol-typed values are effectively just class references whose requirements are dispatched using objc_msgSend. On the flip side, non-#objc protocol-typed values are more complicated, as they carry around both value and witness tables in order to both manage the memory of their (potentially indirectly stored) wrapped value and to determine what implementations to call for the different requirements, respectively.
Because of this simplified representation for #objc protocols, a value of such a protocol type P can share the same memory representation as a 'generic value' of type some generic placeholder T : P, presumably making it easy for the Swift team to allow the self-conformance. The same isn't true for non-#objc protocols however as such generic values don't currently carry value or protocol witness tables.
However this feature is intentional and is hopefully to be rolled out to non-#objc protocols, as confirmed by Swift team member Slava Pestov in the comments of SR-55 in response to your query about it (prompted by this question):
Matt Neuburg added a comment - 7 Sep 2017 1:33 PM
This does compile:
#objc protocol P {}
class C: P {}
func process<T: P>(item: T) -> T { return item }
func f(image: P) { let processed: P = process(item:image) }
Adding #objc makes it compile; removing it makes it not compile again.
Some of us over on Stack Overflow find this surprising and would like
to know whether that's deliberate or a buggy edge-case.
Slava Pestov added a comment - 7 Sep 2017 1:53 PM
It's deliberate – lifting this restriction is what this bug is about.
Like I said it's tricky and we don't have any concrete plans yet.
So hopefully it's something that language will one day support for non-#objc protocols as well.
But what current solutions are there for non-#objc protocols?
Implementing extensions with protocol constraints
In Swift 3.1, if you want an extension with a constraint that a given generic placeholder or associated type must be a given protocol type (not just a concrete type that conforms to that protocol) – you can simply define this with an == constraint.
For example, we could write your array extension as:
extension Array where Element == P {
func test<T>() -> [T] {
return []
}
}
let arr: [P] = [S()]
let result: [S] = arr.test()
Of course, this now prevents us from calling it on an array with concrete type elements that conform to P. We could solve this by just defining an additional extension for when Element : P, and just forward onto the == P extension:
extension Array where Element : P {
func test<T>() -> [T] {
return (self as [P]).test()
}
}
let arr = [S()]
let result: [S] = arr.test()
However it's worth noting that this will perform an O(n) conversion of the array to a [P], as each element will have to be boxed in an existential container. If performance is an issue, you can simply solve this by re-implementing the extension method. This isn't an entirely satisfactory solution – hopefully a future version of the language will include a way to express a 'protocol type or conforms to protocol type' constraint.
Prior to Swift 3.1, the most general way of achieving this, as Rob shows in his answer, is to simply build a wrapper type for a [P], which you can then define your extension method(s) on.
Passing a protocol-typed instance to a constrained generic placeholder
Consider the following (contrived, but not uncommon) situation:
protocol P {
var bar: Int { get set }
func foo(str: String)
}
struct S : P {
var bar: Int
func foo(str: String) {/* ... */}
}
func takesConcreteP<T : P>(_ t: T) {/* ... */}
let p: P = S(bar: 5)
// error: Cannot invoke 'takesConcreteP' with an argument list of type '(P)'
takesConcreteP(p)
We cannot pass p to takesConcreteP(_:), as we cannot currently substitute P for a generic placeholder T : P. Let's take a look at a couple of ways in which we can solve this problem.
1. Opening existentials
Rather than attempting to substitute P for T : P, what if we could dig into the underlying concrete type that the P typed value was wrapping and substitute that instead? Unfortunately, this requires a language feature called opening existentials, which currently isn't directly available to users.
However, Swift does implicitly open existentials (protocol-typed values) when accessing members on them (i.e it digs out the runtime type and makes it accessible in the form of a generic placeholder). We can exploit this fact in a protocol extension on P:
extension P {
func callTakesConcreteP/*<Self : P>*/(/*self: Self*/) {
takesConcreteP(self)
}
}
Note the implicit generic Self placeholder that the extension method takes, which is used to type the implicit self parameter – this happens behind the scenes with all protocol extension members. When calling such a method on a protocol typed value P, Swift digs out the underlying concrete type, and uses this to satisfy the Self generic placeholder. This is why we're able to call takesConcreteP(_:) with self – we're satisfying T with Self.
This means that we can now say:
p.callTakesConcreteP()
And takesConcreteP(_:) gets called with its generic placeholder T being satisfied by the underlying concrete type (in this case S). Note that this isn't "protocols conforming to themselves", as we're substituting a concrete type rather than P – try adding a static requirement to the protocol and seeing what happens when you call it from within takesConcreteP(_:).
If Swift continues to disallow protocols from conforming to themselves, the next best alternative would be implicitly opening existentials when attempting to pass them as arguments to parameters of generic type – effectively doing exactly what our protocol extension trampoline did, just without the boilerplate.
However note that opening existentials isn't a general solution to the problem of protocols not conforming to themselves. It doesn't deal with heterogenous collections of protocol-typed values, which may all have different underlying concrete types. For example, consider:
struct Q : P {
var bar: Int
func foo(str: String) {}
}
// The placeholder `T` must be satisfied by a single type
func takesConcreteArrayOfP<T : P>(_ t: [T]) {}
// ...but an array of `P` could have elements of different underlying concrete types.
let array: [P] = [S(bar: 1), Q(bar: 2)]
// So there's no sensible concrete type we can substitute for `T`.
takesConcreteArrayOfP(array)
For the same reasons, a function with multiple T parameters would also be problematic, as the parameters must take arguments of the same type – however if we have two P values, there's no way we can guarantee at compile time that they both have the same underlying concrete type.
In order to solve this problem, we can use a type eraser.
2. Build a type eraser
As Rob says, a type eraser, is the most general solution to the problem of protocols not conforming to themselves. They allow us to wrap a protocol-typed instance in a concrete type that conforms to that protocol, by forwarding the instance requirements to the underlying instance.
So, let's build a type erasing box that forwards P's instance requirements onto an underlying arbitrary instance that conforms to P:
struct AnyP : P {
private var base: P
init(_ base: P) {
self.base = base
}
var bar: Int {
get { return base.bar }
set { base.bar = newValue }
}
func foo(str: String) { base.foo(str: str) }
}
Now we can just talk in terms of AnyP instead of P:
let p = AnyP(S(bar: 5))
takesConcreteP(p)
// example from #1...
let array = [AnyP(S(bar: 1)), AnyP(Q(bar: 2))]
takesConcreteArrayOfP(array)
Now, consider for a moment just why we had to build that box. As we discussed early, Swift needs a concrete type for cases where the protocol has static requirements. Consider if P had a static requirement – we would have needed to implement that in AnyP. But what should it have been implemented as? We're dealing with arbitrary instances that conform to P here – we don't know about how their underlying concrete types implement the static requirements, therefore we cannot meaningfully express this in AnyP.
Therefore, the solution in this case is only really useful in the case of instance protocol requirements. In the general case, we still cannot treat P as a concrete type that conforms to P.
EDIT: Eighteen more months of working w/ Swift, another major release (that provides a new diagnostic), and a comment from #AyBayBay makes me want to rewrite this answer. The new diagnostic is:
"Using 'P' as a concrete type conforming to protocol 'P' is not supported."
That actually makes this whole thing a lot clearer. This extension:
extension Array where Element : P {
doesn't apply when Element == P since P is not considered a concrete conformance of P. (The "put it in a box" solution below is still the most general solution.)
Old Answer:
It's yet another case of metatypes. Swift really wants you to get to a concrete type for most non-trivial things. [P] isn't a concrete type (you can't allocate a block of memory of known size for P). (I don't think that's actually true; you can absolutely create something of size P because it's done via indirection.) I don't think there's any evidence that this is a case of "shouldn't" work. This looks very much like one of their "doesn't work yet" cases. (Unfortunately it's almost impossible to get Apple to confirm the difference between those cases.) The fact that Array<P> can be a variable type (where Array cannot) indicates that they've already done some work in this direction, but Swift metatypes have lots of sharp edges and unimplemented cases. I don't think you're going to get a better "why" answer than that. "Because the compiler doesn't allow it." (Unsatisfying, I know. My whole Swift life…)
The solution is almost always to put things in a box. We build a type-eraser.
protocol P { }
struct S: P { }
struct AnyPArray {
var array: [P]
init(_ array:[P]) { self.array = array }
}
extension AnyPArray {
func test<T>() -> [T] {
return []
}
}
let arr = AnyPArray([S()])
let result: [S] = arr.test()
When Swift allows you to do this directly (which I do expect eventually), it will likely just be by creating this box for you automatically. Recursive enums had exactly this history. You had to box them and it was incredibly annoying and restricting, and then finally the compiler added indirect to do the same thing more automatically.
If you extend CollectionType protocol instead of Array and constraint by protocol as a concrete type, you can rewrite the previous code as follows.
protocol P { }
struct S: P { }
let arr:[P] = [ S() ]
extension CollectionType where Generator.Element == P {
func test<T>() -> [T] {
return []
}
}
let result : [S] = arr.test()

Get only property defined in protocol causes compilation error when modifying inner property of object

Consider code like this:
protocol SomeProtocol {
var something: Bool { get set }
}
class SomeProtocolImplementation: SomeProtocol {
var something: Bool = false {
didSet {
print("something changed!")
}
}
}
protocol MyProtocol {
var myProperty: SomeProtocol { get }
}
class MyClass: MyProtocol {
var myProperty: SomeProtocol = SomeProtocolImplementation() {
didSet {
print("myProperty has changed")
}
}
}
var o: MyProtocol = MyClass()
o.myProperty.something = true
This code doesn't compile with error:
error: cannot assign to property: 'myProperty' is a get-only property
o.myProperty.something = true
~~~~~~~~~~~~ ^
Why? My property is of type of SomeProtocolImplementation, which is class type so it should be possible to modify it's inner property using reference to myProperty.
Going further, after modifying myProperty definition so that it looks like that:
var myProperty: SomeProtocol { get set }
something weird happens. Now the code compile (not a surprise), but the output is:
something changed!
myProperty has changed
So at this point SomeProtocolImplementation starts behaving like a value type - modyifing it's internal state causes that the "didSet" callback for myProperty is triggered. Just as SomeProtocolImplementation would be struct...
I actually find the solution, but I want also understand what's going on. The solution is to modify SomeProtocol definition to:
protocol SomeProtocol: class {
var something: Bool { get set }
}
It works fine, but I'm trying to understand why it behaves like this. Anybody able to explain?
First read what Class Only Protocol is. Concentrate on the note section that says:
Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics.
Above quote should get you the idea.
You are trying to get the behavior of reference type for your SomeProtocol's conforming class (i.e. SomeProtocolImplementation). You want to be able to change the value of something in future. So basically you are directing to the above quoted sentence.
If you need more clarification please consider the following more meaningful design where I changed the naming for convenience:
protocol Base: class {
var referenceTypeProperty: Bool { get set }
// By now you are assuming: this property should be modifiable from any reference.
// So, instantly make the protocol `Class-only`
}
class BaseImplementation: Base {
var referenceTypeProperty: Bool = false {
didSet {
print("referenceTypeProperty did set")
}
}
}
protocol Child {
var valueTypeProperty: Base { get }
// This property shouldn't be modifiable from anywhere.
// So, you don't need to declare the protocol as Class-only
}
class ChildImplementation: Child {
var valueTypeProperty: Base = BaseImplementation() {
didSet {
print("valueTypeProperty did set")
}
}
}
let object: Child = ChildImplementation()
object.valueTypeProperty.referenceTypeProperty = true
Any class that can provide behavior useful to other classes may declare a programmatic interface for vending that behavior anonymously. Any other class may choose to adopt the protocol and implement one or more of its methods, thereby making use of the behavior. The class that declares a protocol is expected to call the methods in the protocol if they are implemented by the protocol adopter.
Protocol Apple Documentation
When you try to 'set' value to a variable that is read-only - you are trying to change the protocol's implementation. Conforming classes can only consume information from protocol. In Swift we can write protocol extensions where we can have alternative methods for the protocol.
In short think of computed variables as functions. You are technically trying to change a function in this case.
I actually find the solution, but I want also understand what's going on.
I was just about to tell you to make SomeProtocol a class protocol, but you already figured that out. — So I'm a little confused as to what you don't understand.
You understand about reference types and value types, and you understand about class protocols and nonclass protocols.
Well, as long as SomeProtocol might be adopted by a struct (it's a nonclass protocol), then if you are typing something as a SomeProtocol, it is a value type. The runtime isn't going to switch on reference type behavior just because the adopter turns out to be a class instance; all the decisions must be made at compile time. And at compile time, all the compiler knows is that this thing is a SomeProtocol, whose adopter might be a struct.

Hide logic that class conforms to protocol

Are there any ways to hide that class conforms to some protocol? Like in Objective-C - just used to add Protocol in .m file and other classes (from another files) didn't see it.
For example. I have a test cell which has a textfield. I want to hide, that this cell conforms to protocol. Something like that:
class TestCell: UITableViewCell {
}
fileprivate extension TestCell : UITextFieldDelegate {
}
But compiler swears me. Any elegant solution?
This capability has been stated by the Swift team as "unlikely" to be implemented. Here is the original thread about it: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160229/011666.html
The specific statement about this particular scenario was:
Private conformances
Right now, a protocol conformance can be no less visible than the
minimum of the conforming type’s access and the protocol’s access.
Therefore, a public type conforming to a public protocol must provide
the conformance publicly. One could imagine removing that restriction,
so that one could introduce a private conformance:
public protocol P { }
public struct X { }
extension X : internal P { … } // X conforms to P, but only within this module
The main problem with private conformances is the interaction with
dynamic casting. If I have this code:
func foo(value: Any) {
if let x = value as? P { print(“P”) }
}
foo(X())
Under what circumstances should it print “P”? If foo() is defined
within the same module as the conformance of X to P? If the call is
defined within the same module as the conformance of X to P? Never?
Either of the first two answers requires significant complications in
the dynamic casting infrastructure to take into account the module in
which a particular dynamic cast occurred (the first option) or where
an existential was formed (the second option), while the third answer
breaks the link between the static and dynamic type systems—none of
which is an acceptable result.

Equatable Testing in Swift

I'm looking for suggestions on good practices to test the equality of swift objects
If I have a complex object with many properties it's easy to miss the equality implementation.
What are the good practices to enforce the equality implementation?
More details:
Of course, you can write tests to check that two value are equal when they should, but the problem here is that this can break easily.
You have a struct in your project, after six months another developer adds a property to that struct.
Assume that he forgets to add the property to the equality. The equality still works, the tests pass but your app will break when only that property changes. My question is, there is a way to avoid this problem?
In a non trivial app is really easy to end up having model objects with 10 values, and use nested model objects. So how can I keep under control the equality of my model objects? How can I reduce the human error risk in the equality implementation?
Possible solution:
One solution I have in mind is to write a script that looks at compile time for classes and struct that conform to a certain protocol
Diffable : Equatable {}
For all the classes/structs that adopt Diffable I'll check for the existance of a test file, i.e.:
For the class Foo I'll look for a test class Foo_Tests_Diffable
than for all the properties inside Foo I'll check for the existance of a test function that conform to the following name pattern
test<property name>Diffable
i.e.:
class Foo : Diffable {
var title: String
var color: UIColor
var tag: Tag
}
I'll check for the following tests inside Foo_Tests_Diffable
func testTitleDiffable {
// Test
}
func testColorDiffable {
// Test
}
func testTagDiffable {
// Test
}
If all the script finds all the expected tests than the compile step pass, otherwise it fails
But this solution it's time consuming and I don't know if I'll be able to implement it, so any suggestion is welcome
I would create unit tests specifically for this purpose.
class YourObjectEquatableTests: XCTestCase
{
func testPropertyOne()
{
var object1 = /* ... */
var object2 = /* ... */
object1.propertyOne = nil
object2.propertyOne = nil
XCTAssertEqual(object1, object2)
object1.propertyOne = "different value"
XCTAssertNotEqual(object1, object2)
/* etcetera */
}
func testPropertyTwo()
{
/* ... */
}
}
Note: if you write your test cases before implementing the Equatable details, you're actually doing TDD which is very cool!
I didn't try it a lot but Swift has Reflection capabilities.
https://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/
So in your case, you can mirror a class and then put some conditions in your test.
for example, you can set a fix number or attribute or methods for a class in your test.
let nbAttributes = 6
and then check it:
aMirror.children.count
I wrote a simple example in the playground and if I add a method variable, the children count increases. I don't know if it's possible to check the methods though.
class toto{
var io = 9
var tutu = "yo"
func test(){
}
}
let toto1 = toto()
let aMirror = Mirror(reflecting: toto1)
aMirror.children.count
another link:
Reflection in swift 2
Hope that helps :)
Yes, expanding on #Mikael's answer, you should probably use Reflection.
An example would be:
String(reflecting: obj1) == String(reflecting: obj2)

Type Method in swift?

I am trying a bit of type (aka class) method but am confused on the real world application of such methods. e.g. In the following code from tutorialspoint.com -
class Math
{
class func abs(number: Int) -> Int
{
if number < 0
{
return (-number)
}
else
{
return number
}
}
}
let no = Math.abs(-35)
println(no)
So my question is that what is happening here when I am writing a type method. At what point of my programming may I need this. Can any one explain with a bit clear and simple example.
these kinds of functions are useful when you dont actually need an instance of the type to be made to be able to call it, eg helper methods. take the example you posted, if you call the abs function, you dont really need to make a Math object instantiated to do that (you could be seems unnecessary).
if your abs function wasnt a type method, you would have to go like this
var mathObject = Math()
mathObject.abs(-35)
as apposed to the way you have it in you example
Math.abs(-35)
both statements achieve the same goal, but the 2nd is more elegant (and memory efficient).
there are other reasons as well for using type methods, but this is just the simplest example of one (look up what a singleton is, for another example)
class C {
class func foo(){}
// Type method is always static !!!
static func boo() {}
}
class D: C {
override class func foo() {}
// this is not possible for 'Type method'
override static func boo() {} // error !!!!
}

Resources