简体   繁体   English

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

[英]How to call another method from another class in swift?

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中完成它。我如何在swift中执行此操作?

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) let 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。”iBooks。

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()

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

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