修改抽象结构中的值

问题描述 投票:-1回答:1

我在处理结构和协议时遇到了这种情况,并且很想知道如何在这种情况下访问和修改值:

import Foundation

struct Garage {
    var vehicles : [VehicleProtocol]
}

protocol VehicleProtocol {
    var id: String { get }
}

protocol TwoWheelsProtocol: VehicleProtocol {
    var id: String { get }
    var uniqueTwoWheelsAttribut: String { get set     }
}

struct TwoWheels: TwoWheelsProtocol {
    var id: String
    var uniqueTwoWheelsAttribut: String
}

protocol FourWheelsProtocol: VehicleProtocol {
    var uniqueFourWheelsAttribut: String { get set }
}

struct FourWheels: FourWheelsProtocol {
    var id: String
    var uniqueFourWheelsAttribut: String
}

func printVehicules(of garage: Garage) {
    for vehicle in garage.vehicles {
        if vehicle is TwoWheelsProtocol {
            let tw = vehicle as! TwoWheelsProtocol
            print("\(tw.id) | \(tw.uniqueTwoWheelsAttribut)")
        }

        if vehicle is FourWheelsProtocol {
            let tw = vehicle as! FourWheelsProtocol
            print("\(tw.id) | \(tw.uniqueFourWheelsAttribut)")
        }
    }
}

let vehicle0 = TwoWheels(id: "0", uniqueTwoWheelsAttribut: "vehicle0")
let vehicle1 = FourWheels(id: "1", uniqueFourWheelsAttribut: "vehicle1")

var a = Garage(vehicles: [vehicle0, vehicle1])

printVehicules(of: a)

printVehicules(of: a)的结果是:

0 | vehicle0
1 | vehicle1

如何修改vehicle0 uniqueTwoWheelsAttribut

0 | modified
1 | vehicle1

我可以用

if a is TwoWheelsProtocol {
    let tw as! TwoWheelsProtocol
    ......
}

但由于转换结果在另一个变量中,因此修改不会影响原始值。

ios swift swift-protocols
1个回答
0
投票

documentation

类具有结构不具备的其他功能: - 引用计数允许对类实例的多个引用。

所以let tw as! TwoWheelsProtocol总是创建一个新对象,因为TwoWheels是一个结构。为了避免这种情况,你可以将TwoWheels变成一个类:

class TwoWheels: TwoWheelsProtocol {
    var id: String
    var uniqueTwoWheelsAttribut: String

    init(id: String, uniqueTwoWheelsAttribut: String) {
        self.id = id
        self.uniqueTwoWheelsAttribut = uniqueTwoWheelsAttribut
    }
}

现在let tw as! TwoWheelsProtocol不会创建新副本,而只是创建对象的新引用。

What you can improve

要求VehicleProtocol只允许类实现协议。通过这种方式,您可以确保转换和更改实际上确实更改了引用的对象,而不仅仅是它的副本。

protocol VehicleProtocol: class {
    var id: String { get }
}

您可以使用更紧凑的铸造方法。

if var tw = vehicle as? TwoWheelsProtocol {
    // Modify tw.
}

guard var tw = vehicle as? TwoWheelsProtocol else {
    return
}
// Modify tw.
© www.soinside.com 2019 - 2024. All rights reserved.