Swift方法声明
class MOCalculate: NSObject {
/// 方法声明
/// name 方法名称 parameters 方法参数 return type 返回值类型 function body 方法内容
/// - Returns: return type
func <#name#>(<#parameters#>) -> <#return type#> {
<#function body#>
}
<-----类方法----->
/// 生成一个1~365的随机数 包括1和365
///
/// - Returns: 随机生成的数
class func getRandomNum() -> NSInteger {
let randomNum = NSInteger(arc4random()%365) + 1;
print("randomNum = ",randomNum,"?");
return randomNum;
}
///static也可以声明类方法 但是static和class只能用一个
static func getRandomNum() -> NSInteger {
let randomNum = NSInteger(arc4random()%365) + 1;
print("randomNum = ",randomNum,"?");
return randomNum;
}
<-----实例方法----->
//保存数字
func saveUsedNum(num : NSInteger) -> Void {
}
//无参数 无返回值
func noParameters(){
}
//无参数 有返回值
func noParameters() -> String {
return "test";
}
//有1个参数 无返回值
func oneParameters(test : String) -> Void {
print(test);
}
//有参数 有返回值
func oneParameters(test : String) -> String {
return test;
}
//多参数
func moreParameters(test : String, with testOne : String) -> String {
return test.appending(testOne);
}
}
Swift方法调用
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//调用实例方法
let calculate = MOCalculate.init()
let num = calculate.getSaveNum();
print(calculate.moreParameters(test: "a", with: "b"));
//调用类方法
let randomNum = MOCalculate.getRandomNum()
print(num,randomNum)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
网友评论
//MARK:- Class Method
class func moNavViewcontroller() -> UINavigationController {
let moMainVc = self.viewController(storyboardName: MoMainUI)
let nav_Main = UINavigationController.init(rootViewController: moMainVc)
return nav_Main
}
static func moNav() -> UINavigationController {
let moMainVc = self.viewController(storyboardName: MoMainUI)
let nav_Main = UINavigationController.init(rootViewController: moMainVc)
return nav_Main
}