iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 28
0
自我挑戰組

Hello Swift系列 第 28

28/30 I服了U-2

(承27/30 I服了U-1)
協定:MoneyTransferProtocol
宣告方法:giveMoney

protocol MoneyTransferProtocol{
    func giveMoney()
}

服從協定的第一個類別,實作自己的giveMoney方法

class RichPeople:MoneyTransferProtocol{
    func giveMoney() {
        print("Give you 100 dollars")
    }
}

服從協定的第二個類別,實作自己的giveMoney方法

class NormalPeople:MoneyTransferProtocol{
    func giveMoney() {
        print("Give you 10 dollars")
    }
}

服從協定的第三個類別,實作自己的needMoney方法

class PoorGuy{
    //protocol可以用來標示常數或變數的型別
    //屬性helper的類別是某個服從MoneyTransferProtocol協定的類別
    //?:此屬性可能有也可能沒有
    var helper:MoneyTransferProtocol?
    //如果helper有值,就執行類別裡的giveMoney方法
    func needMoney(){
        helper?.giveMoney()
    }
}

試用看看

let aPoorGuy = PoorGuy()
//aPoorGuy.needMoney()
let aRichPeople = RichPeople()
let aNormalPeople = NormalPeople()
aPoorGuy.helper = aRichPeople //Print:Give you 100 dollars
aPoorGuy.helper = aNormalPeople //Print:Give you 10 dollars
aPoorGuy.needMoney()

上一篇
27/30 I服了U-1
下一篇
29/30 命裡有時終須有
系列文
Hello Swift30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言