Why Choose Struct Over Class?

前端 未结 16 2121

Playing around with Swift, coming from a Java background, why would you want to choose a Struct instead of a Class? Seems like they are the same thing, with a Struct offeri

16条回答
  •  遥遥无期
    2020-11-22 06:18

    Structure is much more faster than Class. Also, if you need inheritance then you must use Class. Most important point is that Class is reference type whereas Structure is value type. for example,

    class Flight {
        var id:Int?
        var description:String?
        var destination:String?
        var airlines:String?
        init(){
            id = 100
            description = "first ever flight of Virgin Airlines"
            destination = "london"
            airlines = "Virgin Airlines"
        } 
    }
    
    struct Flight2 {
        var id:Int
        var description:String
        var destination:String
        var airlines:String  
    }
    

    now lets create instance of both.

    var flightA = Flight()
    
    var flightB = Flight2.init(id: 100, description:"first ever flight of Virgin Airlines", destination:"london" , airlines:"Virgin Airlines" )
    

    now lets pass these instance to two functions which modify the id, description, destination etc..

    func modifyFlight(flight:Flight) -> Void {
        flight.id = 200
        flight.description = "second flight of Virgin Airlines"
        flight.destination = "new york"
        flight.airlines = "Virgin Airlines"
    }
    

    also,

    func modifyFlight2(flight2: Flight2) -> Void {
        var passedFlight = flight2
        passedFlight.id = 200
        passedFlight.description = "second flight from virgin airlines" 
    }
    

    so,

    modifyFlight(flight: flightA)
    modifyFlight2(flight2: flightB)
    

    now if we print the flightA's id and description, we get

    id = 200
    description = "second flight of Virgin Airlines"
    

    Here, we can see the id and description of FlightA is changed because the parameter passed to the modify method actually points to the memory address of flightA object(reference type).

    now if we print the id and description of FLightB instance we get,

    id = 100
    description = "first ever flight of Virgin Airlines"
    

    Here we can see that the FlightB instance is not changed because in modifyFlight2 method, actual instance of Flight2 is passes rather than reference ( value type).

提交回复
热议问题