BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

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.

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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

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.