Swift - Structures (Struct)

Aus Wikizone
Wechseln zu: Navigation, Suche

Links[Bearbeiten]

Swift (Programmiersprache)
Swift - Classes

Beispiele[Bearbeiten]

import UIKit

/**
 Structures allow you to create custom data types
 See them as a blueprint for how a actual struct instance will be. What they are and how they behave
 Struct names should start with capital letter
 Struct instances should start with lowercase letter just like any other types
 Structs can have properties and methods (which are functions in a struct)
 */

struct Town {
    // struct properties
    let name = "Steventon"
    var citizens = ["Stephan", "Yvonne", "Finn"]
    var resources = ["Grain": 100, "Ore": 42, "Wool": 75]
    // struct methods
    func fortify(){
        print("Defences increased!")
    }
}

var myTown = Town() // Initialize a Town instance
myTown.citizens.append("Damon")

print(myTown.citizens)
print("\(myTown.name) has \(myTown.resources["Grain"]!) items of Grain")

myTown.fortify()

/**
 In practice you normally would define more generic properties
 an use a initializer to create a lot of different instances with different properties
 
 */
struct genericTown {
    let name: String
    var citizens: [String]
    var resources: [String:Int]
    
    init(townName:String, citizens:[String], resources:[String:Int]){
        /**
         Its's good practice to use same name for input and internal property
         But you have to use self to differenciate between them
         Self means the member property of the struct
         */
        name = townName // works but not good practice
        self.citizens = citizens // that's how it should look likew
        self.resources = resources
    }
    
    func fortify(){
        print("Defences increased!")
    }
    
    func printTownInfo(){
        print(self.citizens)
        print("\(self.name) has \(self.resources["Grain"]!) items of Grain")
    }
}

var anotherTown = genericTown(townName: "Berlin", citizens: ["Garfield","Jon"], resources: ["Grain":2,"Coconuts":50])
var ghosttown = genericTown(townName: "Foggy City", citizens: [], resources: ["Tumbleweed":32])

anotherTown.printTownInfo()