UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.