繁体   English   中英

Swift - 将自定义对象作为参数传递

[英]Swift - Passing custom objects as a parameter

我今天开始学习 Swift,在我的第一个测试应用程序中,我收到了这个错误:

TestClass不能转换为AnotherClass

以下是TestClass

class TestClass : NSObject {

    var parameter1 : String = ""
    var parameter2 : String = ""

    override init() {        
        super.init()
    }

    func createJob(parameter1: String, parameter2: String) -> TestClass {
        self.parameter1 = parameter1
        self.parameter2 = parameter2
        return self;
    }  
}

这是另一个类

class AnotherClass: NSObject {

    private struct internalConstants {
        static let test1 = "testData"
        static let test2 = "testData2"
    }

    var current : String

    override init() {
        self.current = internalConstants.test1
        super.init()
    }

    func executeTask(testClass : TestClass) {

        if testClass.parameter1 == "abc" {
            return;
        }
    }
}

这是我收到编译器错误的ViewController

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let obj = TestClass()
        AnotherClass.executeTask(obj)
    }

}

AnotherClass.executeTask行给出了编译器错误。

在此行上作为参数发送的obj变量由 Xcode 突出显示,并显示错误

TestClass不能转换为AnotherClass ”。

在 C# 或 Objective C 中,允许将自定义对象作为参数传递给其他方法。 我怎样才能在 Swift 中做到这一点?

让我们首先更正TestClass 这是您应该如何初始化这样的类:

class TestClass : NSObject {

    ....

    init(parameter1: String, parameter2: String) {
        ....
    }
}

简单多了。 现在,回到你的问题,

“TestClass 不能转换为 AnotherClass”。

再看一看。 您在问题中提到的那条线。 您正在尝试这样做:

let obj = TestClass()
AnotherClass.executeTask(obj)

这行AnotherClass.executeTask(obj)给你一个错误,因为executeTask()确实是一个实例方法。 你可以做三种方法。

  1. 添加static关键字到func executeTask...所以它变成这样: static func executeTask(testClass : TestClass) {

  2. 您可以添加class ,而不是static关键字。 它变成这样: class func executeTask(....

  3. 或者,如果您只是实例化AnotherClass 创建一个AnotherClass的新对象。 如何实例化? 你告诉我。 但在这里:

let anotherClass = AnotherClass()

要么将 executeTask 实现为类函数

class func executeTask(testClass : TestClass) {
    if testClass.parameter1 == "abc" {
        return;
    }
}

或在vieweDidLoad实例化AnotherClass vieweDidLoad

let obj = TestClass()
let another = AnotherClass()
another.executeTask(testClass: obj)

请注意使用参数名称对executeTask调用略有不同。

在我看来,您真的没有理由将 NSObject 子类化。

我认为最好保持简单。 ViewController创建另一个AnotherClass的实例。

class ViewController: UIViewController {

    // Create an instance of AnotherClass which lives with ViewController.
    var anotherClass = AnotherClass()

    override func viewDidLoad() {
        super.viewDidLoad()

        let obj = TestClass()

        // Use the instance of AnotherClass to call the method.
        anotherClass.executeTask(testClass: obj)
    }

}

暂无
暂无

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

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