NEW: Join my free 100 Days of SwiftUI challenge today! >>

Atributos y métodos estáticos

Swift te permite crear atributos y métodos que pertenecen a un tipo, en lugar de a las instancias de ese tipo. Esto es muy útil para organizar los datos de manera significativa al almacenar datos compartidos.

Swift llama a estos atributos compartidos "atributos estáticos", y se pueden crear usando solamente el modificador static. Una vez que lo has hecho, puedes acceder al atributo utilizando el nombre completo del tipo. Por ejemplo:

struct TaylorFan {
    static var cancionFavorita = "Look What You Made Me Do"

    var nombre: String
    var edad: Int
}

let fan = TaylorFan(nombre: "James", edad: 25)
print(TaylorFan.cancionFavorita)

Luego, un fan de Taylor Swift tiene un nombre y edad que pertenecen únicamente a él, pero todos los fans tienen la misma canción favorita.

Debido a que los métodos estáticos pertenecen a la propia estructura, en lugar de a la instancia, no puedes usarlos para acceder a atributos no estáticos de la estructura.

SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!