Menu
Coddy logo textTech

Le struct

Fa parte della sezione Programmazione orientata agli oggetti del percorso Swift di Coddy. Lezione 7 di 57.

Una struct raggruppa dati e metodi come una classe. Swift scrive un inizializzatore membro per membro per ogni struct, con un parametro per proprietà, quindi una struct non ha bisogno di un proprio init:

struct Point {
    var x: Int
    var y: Int

    func distanceFromOrigin() -> Int {
        abs(x) + abs(y)
    }
}

let p = Point(x: 3, y: -4)
print(p.x)
print(p.distanceFromOrigin())

Output:

3
7

Le proprietà con valori predefiniti possono essere omesse dall’inizializzatore membro per membro:

struct Settings {
    var volume = 5
    var muted = false
}

let quiet = Settings(volume: 1)
print(quiet.volume)
print(quiet.muted)

Output:

1
false

Una struct memorizzata in una costante let non può cambiare in alcun modo, nemmeno le sue proprietà var. Memorizzala in una var per modificarla:

let fixed = Point(x: 1, y: 2)
// fixed.x = 5    // errore: impossibile assegnare un valore, fixed è una costante let

var moving = Point(x: 1, y: 2)
moving.x = 5       // va bene

Molti dei tipi di Swift sono struct: Int, Double, String, Array e Dictionary. Le tue struct si comportano allo stesso modo di questi tipi: sono semplici valori.

struct Money {
    var cents: Int
    func formatted() -> String {
        "\(cents / 100).\(cents % 100 < 10 ? "0" : "")\(cents % 100)"
    }
}

print(Money(cents: 1250).formatted())
print(Money(cents: 305).formatted())

Output:

12.50
3.05
challenge icon

Sfida

Facile

Dichiara una struct Item con le proprietà name (String), price (Int, in centesimi) e quantity (Int). Aggiungi un metodo total() che restituisce il prezzo moltiplicato per la quantità e un metodo line() che restituisce 2 x tea = 350.

Il codice fornito legge un elemento per riga nel formato name,price,quantity, crea ciascun Item con l'inizializzatore membro per membro e stampa line(). Poi stampa sum: e la somma di tutti i totali.

Scrivi il tuo codice in Item.swift. main.swift contiene il codice di input/output fornito e non può essere modificato.

Provalo tu

// Código de entrada/salida proporcionado: mantenlo tal como está
var input: [String] = []
while let line = readLine() { input.append(line) }
var sum = 0
for row in input {
    let p = row.split(separator: ",").map(String.init)
    let item = Item(name: p[0], price: Int(p[1])!, quantity: Int(p[2])!)
    print(item.line())
    sum += item.total()
}
print("sum: \(sum)")
quiz iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Programmazione orientata agli oggetti

Esercitati da solo: Playground Swift