class level or struct level method in swift like static method in Java?

后端 未结 3 2026
[愿得一人]
[愿得一人] 2021-02-02 06:10

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() -> Stri         


        
相关标签:
3条回答
  • 2021-02-02 06:49

    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.

    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2021-02-02 06:57

    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

    0 讨论(0)
提交回复
热议问题