Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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?

like image 795
Jhonghee Avatar asked Jun 08 '14 15:06

Jhonghee


People also ask

What is the difference between static method and class method in Swift?

But what's the difference? The main difference is static is for static functions of structs and enums, and class for classes and protocols. From Chris Lattner the father of Swift. We considered unifying the syntax (e.g. using “type” as the keyword), but that doesn't actually simply things.

Can struct be static Swift?

Static Properties and methodsSwift allows us to create property and methods that belong to a struct, rather than an instance of the struct. This means you can access the properties or methods even if the instance of struct is not created. These shared properties in swift are called static properties.

What are static methods in Swift?

A static method is of class type (associated with class rather than object), so we are able to access them using class names. Note: Similarly, we can also create static methods inside a struct. static methods inside a struct are of struct type, so we use the struct name to access them.

Is Swift array class or struct?

Swift said "yes," which means that types like Array and Dictionary and String are structs rather than classes.


2 Answers

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.

like image 101
rickster Avatar answered Oct 06 '22 00:10

rickster


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()
like image 45
Logan Avatar answered Oct 05 '22 23:10

Logan