繁体   English   中英

不同模块中的 class 名称相同

[英]same class name in different modules

我需要在 swift 5 中使用两个同名的类。为此,我在两个不同的模块中创建了这两个类,但我对如何在UIViewController中使用这两个类感到困惑

我的Person之一是models > student模块中的Person ,另一个 class 是models模块中的人

我试过导入 class 之类的

import class models.student.Person

class BookViewController: UIViewController {
     var students:[Person] = [] //it should call models.student.Person
     var people: [Person] = [] //it should call models.Person
     ...

但上面的 Person class 仅指向models.Person ,它不指向models.student.Person

型号中的人 class > Person.swift 是

import Foundation

// MARK: - Person
public struct Person: Codable {
    public let firstName: String?
    public let lastName: String?
    public let address: String?
    public let phone: String?

    enum CodingKeys: String, CodingKey {
        case firstName = "first_name"
        case lastName = "last_name"
        case address = "address"
        case phone = "phone"
    }

    public init(firstName: String?, lastName: String?, address: String?, phone: String?) {
        self.firstName = firstName
        self.lastName = lastName
        self.address = address
        self.phone = phone
    }
}

和 models.student.Person.swift 是

import Foundation

// MARK: - Person
public struct Person: Codable {
    public let fullName: String?
    public let educationalQualification: String?
    public let college: String?

    enum CodingKeys: String, CodingKey {
        case fullName = "full_name"
        case educationalQualification = "educational_qualification"
        case college = "college"
    }

    public init(fullName: String?, educationalQualification: String?, college: String?) {
        self.fullName = fullName
        self.educationalQualification = educationalQualification
        self.college = college
    }
}

我的 BookViewController 中同时需要BookViewController

我无法将 class 的名称更改为其他名称,我应该使用相同的 class 名称。

你可以试试 typealias:

typealias StudentPerson = yourStudentFramework.Person

然后像这样使用它:

import yourStudentFramework

class BookViewController: UIViewController {
     var students:[StudentPerson] = [] //it should call yourStudentFramework.Person
     var people: [Person] = [] //it should call models.Person
...

对于这种情况,您应该使用 from Protocol Oriented
访问https://medium.com/nsistanbul/protocol-oriented-programming-in-swift-ad4a647daae2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM