【问题标题】:same class name in different modules不同模块中的相同类名
【发布时间】:2020-02-22 08:56:19
【问题描述】:

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

我的一个班级是Person,它位于models > student 模块中,另一个班级是Person,它位于models 模块中

我尝试过导入类

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 类只指向models.Person,它没有指向models.student.Person

模型中的 Person 类 > 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 中的两个类都需要

我不能将班级名称更改为其他班级名称,我应该使用相同的班级名称。

【问题讨论】:

  • 我是第二个投票结束的。这不是通常需要的东西——例如,框架应该尽最大努力确保不会发生这种情况。引用 only 在您的问题中重要的事情... “我需要使用两个具有相同名称的类...” 如果子类化或创建两个实例一个类不起作用,然后是其他问题,并且您的示例代码确实无助于复制它。它可能是一个 Swift 问题,但是您发布的 (a) 听起来比这更多(OOP?)但 (b) 根本不可复制。你能提供更多代码吗?这会有所帮助。
  • @dfd 我已经更具体地更新了我的问题
  • 我的意思是尽可能以最友好的方式进行,但这种设置根本行不通。这是使用命名空间的base 原因——避免这样的冲突。 “学生”应该始终是“人”,但“人”可能是学生。您至少可以让 Student 从 Person 继承(或扩展)吗?
  • @dfd,不,我只是发送一个示例,我的实际要求是最大类中的所有参数彼此不同

标签: ios swift swift5


【解决方案1】:

你可以试试 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
...

【讨论】:

    猜你喜欢
    • 2020-03-08
    • 1970-01-01
    • 2013-01-26
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多