ios 如何在swift中从另一个类调用另一个方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26621148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:24:25  来源:igfitidea点击:

How to call another method from another class in swift?

iosobjective-cclassswift

提问by zbz.lvlv

mainController = (ViewController *)self.presentingViewController;   
mainController.pressureUnit = _pressureSettings.selectedSegmentIndex;

This is how I will do it in Objective C. How do I do this in swift?

这就是我在 Objective C 中的做法。我如何快速做到这一点?

回答by Steve Rosenberg

otherClass().methodFromOtherClass() is the syntax for swift

otherClass().methodFromOtherClass() 是 swift 的语法

If you have to pass a property with an external name it might be:

如果您必须传递具有外部名称的属性,它可能是:

otherClass().methodFromOtherClass(propertyName: stringName) //example of passing a string

otherClass().methodFromOtherClass(propertyName: stringName) //传递字符串的例子

To call the method to do something, if it is returning a result of a method:

调用方法做某事,如果它返回一个方法的结果:

let returnValue = otherClass().methodFromOtherClass(propertyName: stringName)

让 returnValue = otherClass().methodFromOtherClass(propertyName: stringName)

Example of accessing a property or a function

访问属性或函数的示例

class CarFactory { 
   var name = ""
   var color = "" 
   var horsepower = 0 
   var automaticOption = false

   func description() { 
       println("My \(name) is \(color) and has \(horsepower) horsepowers") 
   }
} 

var myCar = CarFactory() 
myFirstCar.name = "Mustang"
myCar.color = "Red"
myCar.horsepower = 200 myCar.automaticOption = true
myFirstCar.description() // $: "My Mustang is Red and has 200 horsepowers and is Automatic"

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.

摘自:Apple Inc. “The Swift Programming Language”。电子书。

Here you just call the method but not a new instance of the class.

在这里,您只调用方法而不是类的新实例。

class SomeClass {
    class func someTypeMethod() {
        // type method implementation goes here
    }
}

SomeClass.someTypeMethod()