NEW: Got a question? Get help on our new forums! >>

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.

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred by integrating Instabug's SDK in one minute. You will automatically receive device data, network logs, and reproduction steps with every bug and crash report.

Learn more and get started for free

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

Cascable unleashes the power of your camera and unlocks powerful workflows for shooting, managing, and geotagging your photos.

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!