iOS_函數的學習_閉包(Closurs)的學習及概念
函數的使用方式
======================================================================
//
// ViewController.swift
// ios_Optional_
//
// Created by stu_11 on 2017/4/14.
// Copyright © 2017年 mcu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Optional 的 錯誤 不能指定 nil
//var message: String = "Swift is awesome!!"
//message = nil
SayHi()
SayHello(name: "Samuel")
say(name: "Simon", greeting: "Mary")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//無參數輸入的函數
func SayHi(){
print("Hi everyone!!!")
}
//有參數輸入的函數(單一個)
func SayHello(name: String)
{
print("Hello \(name)")
}
//多個參數輸入的函數
func say(name:String , greeting: String){
print("\(greeting) send gift to \(name)")
}
}
======================================================================
//
// ViewController.swift
// ios_Optional_
//
// Created by stu_11 on 2017/4/14.
// Copyright © 2017年 mcu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let stock = findStockCode(company: "Apple"){
if let sharePrice = stock.price {
let totalCost = sharePrice*100
print(totalCost)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 函數 寫在class ViewController: UIViewController
func findStockCode(company: String)-> Stock?{
if (company == "Apple"){
let aapl: Stock = Stock()
aapl.code = "AAPL"
aapl.price = 90.76
return aapl
}
else if(company =="Google")
{
let goog: Stock = Stock()
goog.code = "GOOG"
goog.price = 556.36
return goog
}
return nil
}
}
class Stock{
var code: String?
var price:Double?
}
留言
張貼留言