NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

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)

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.

Hacking with Swift is sponsored by Instabug

SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.

Start your free trial!

Sponsor Hacking with Swift and reach the world's largest Swift community!

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!

Link copied to your pasteboard.