Swift 中同一结构的多个实例

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

在我的应用程序中,我有航班预订应用程序的详细信息。它有到达和出发数据。我为同一对象创建了两个模型。因此,为了将数据传递到我的视图模型中的 ui,我创建了同一模型的两个实例,一个用于到达,另一个用于出发。我在到达和出发时使用了相同的实例吗?这会是一个好的做法吗?我想为它们两个使用一个实例。我该怎么办,请大家帮忙。

型号

// MARK: - Arrival

struct FTTDepatureDetailsModel: Codable {
    let cityName, cityCode, country, airportName, terminal, scheduledTime, actualTime, aircraft, dateTime: String?

}

// Mock data for flight Depature details

struct MockDepatureData {
    static let sampleDepature = FTTDepatureDetailsModel(cityName: "Riyad", cityCode: "RUH", country: "Saudi Arabia", airportName: "King Khiladi International", terminal: "3", scheduledTime: "19:50", actualTime: "19:59", aircraft: "Airbus A320", dateTime: "7 Sept 2023 10.00 am")
}

// Mock data for flight arrival details
struct MockArrivalData {
    static let sampleArrival = FTTDepatureDetailsModel(cityName: "London", cityCode: "LHR", country: "United Kingdom", airportName: "London Heathrow Airport", terminal: "2", scheduledTime: "01:45", actualTime: "-", aircraft: "Airbus A320", dateTime: "7 Sept 2023 08.00 pm")
}

视图模型

final class FTTRoundTripLocationViewModel: ObservableObject {

    @Published var roundTripDepatureLocation: FTTDepatureDetailsModel?
    @Published var roundTripArrivalLocation: FTTDepatureDetailsModel?
    
    
    init(roundTripDepatureLocation: FTTDepatureDetailsModel, roundTripArrivalLocation: FTTDepatureDetailsModel) {
        self.roundTripDepatureLocation = roundTripDepatureLocation
        self.roundTripArrivalLocation = roundTripArrivalLocation
    }

查看

 struct FTTFlightRoundTripDetailsView: View {
    @Environment(\.presentationMode) var presentationMode
    @State var flightRoundTripDetailsVM: FTTRoundTripDetailsViewModel
    @State var flightRoundTripLocationVM: FTTRoundTripLocationViewModel
    @State var flightRoundAmenitiesViewModel: AircraftDetailsInfoViewViewModel

    }
swift struct viewmodel
1个回答
0
投票

当然,您的模型可以包含结构的两个实例。为什么不可以?

一个建议:您在出发和到达时都使用

FTTDepatureDetailsModel
。使用
FTTDepatureDetailsModel
结构来描述到达的航班是令人困惑的,并且会让所有在其余时间查看此代码的人感到困惑。 (包括从现在起 6 个月后的您。)重命名它
FTTFlightDetailsModel

© www.soinside.com 2019 - 2024. All rights reserved.