46

Is there a way to add method at class level or struct level in swift?

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

Now if you wanted to add a method that creates a full deck of cards, what would be the best way to accomplish it?

0

3 Answers 3

91

To add a type-level method in a class, add the class keyword before the func declaration:

class Dealer {
    func deal() -> Card { ... }
    class func sharedDealer() -> Dealer { ... }
}

To add a type-level method in a struct or enum, add the static keyword before the func declaration:

struct Card {
    // ...
    static func fullDeck() -> Card[] { ... }
}

Both are generally equivalent to static methods in Java or class methods (declared with a +) in Objective-C, but the keyword changes based on whether you're in a class or struct or enum. See Type Methods in The Swift Programming Language book.

Sign up to request clarification or add additional context in comments.

2 Comments

This has been updated in 6.3, for what it's worth: adcdownload.apple.com//Developer_Tools/Xcode_6.3_beta/… Cheers
Classes have both "static" and "class" funcs. See following answer for explanation stackoverflow.com/a/29636742/2774520
31

In Struct:

struct MyStruct {
    static func something() {
        println("Something")
    }
}

Called via:

MyStruct.something()

In Class

class MyClass {
    class func someMethod() {
        println("Some Method")
    }
}

called via:

MyClass.someMethod()

3 Comments

@IrshadQureshi - there's many differences, the most important in my mind is that structs are ValueType and classes are ReferenceType
@IrshadQureshi And structs can't be extended like classes
subclasses can override class func's which is not possible with static methods.
8

p 353

class SomeClass {
    class func someTypeMethod() {
        // type method implementation goes here
    }
}
SomeClass.someTypeMethod()

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.