Swift Advanced-Protocol basic example

  • Protocol

    Definition: protocol— allow you to specify and work with the interface of a type without knowing the type itself.

  • basic example

import Cocoa
protocol TabularDataSource {
    var numberOfRows: Int {get}
    var numberOfColumns: Int {get}
    func labelForRow(row:Int) -> String
    func labelForColumn(column: Int)->String
    func itemForRow (row:Int ,column:Int)->Int
}
func padding(amount:Int) -> String{
    var paddingString = ""
    for _ in 0..<amount{
     paddingString += " "
    }
    return paddingString
}
func printTable(dataSource:TabularDataSource){
    //Create arrays of the row and column labels
    let rowLabels = (0..<dataSource.numberOfRows).map{dataSource.labelForRow($0)}
    let columnLabels = (0..<dataSource.numberOfColumns).map{dataSource.labelForColumn($0)}
    //Create an array of the width of each row
    let rowLabelWidths = rowLabels.map{$0.characters.count}
    //Determine length of longest row
    guard let maxRowLabelWidth = rowLabelWidths.maxElement() else {
        return
    }
    //Create first row containing column headers
    var firstRow:String = padding(maxRowLabelWidth) + " |"
    //keep track of the width of each column
    var columnWidths = [Int]()
    for columnLabel in columnLabels{
        let columnHeader = " \(columnLabel) |"
        firstRow += columnHeader
        columnWidths.append(columnHeader.characters.count)
    }
    print(firstRow)
     for i in 0..<dataSource.numberOfRows{
        //Pad the row label out so they are all the same length
        let paddingAmount = maxRowLabelWidth - rowLabelWidths[i]
        var out = rowLabels[i] + padding(paddingAmount) + " |"
        //Append each item in this row to our string
        for j in 0..<dataSource.numberOfColumns{
            let item = dataSource.itemForRow(i, column: j)
            let itemString = "\(item) |"
            let paddingAmount = columnWidths[j] - itemString.characters.count
            out += padding(paddingAmount) + itemString
        }
        print(out)
    }
}
struct Person {
    let name: String
    let age:Int
    let yearsOfExperience : Int
    
}
struct Department:TabularDataSource{
    let name: String
    var people = [Person]()
    init(name: String){
        self.name = name
    }
    mutating func addPerson(person:Person){
        people.append(person)
    }
    var numberOfRows: Int{
        return people.count
    }
    var numberOfColumns: Int{
        return 2
    }
    func labelForColumn(column: Int) -> String {
        switch column {
        case 0 : return "Age"
        case 1 : return "Years of Experience"
        default: fatalError("Invalid column!")
        }
    }
    func labelForRow(row: Int) -> String {
        return people[row].name
    }
    func itemForRow(row: Int, column: Int) -> Int {
        let person = people[row]
        switch column {
        case 0 : return person.age
        case 1 : return person.yearsOfExperience
        default: fatalError("Invalid column!")
        }
    }    
}
var department =  Department(name: "Engineering")
department.addPerson(Person(name:"Joe",age: 30,yearsOfExperience: 6))
department.addPerson(Person(name:"Karen",age: 40,yearsOfExperience: 18))
department.addPerson(Person(name:"Fred",age: 50,yearsOfExperience: 20))
printTable(department) 
  • usage summation

<small> In order to give a method the right data to process ,we let the data to confirm to a designed protocol.When the data come out from the protocol, it can fit for the method and then the method process is well-functioned as before </small>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末卷玉,一起剝皮案震驚了整個濱河市磁奖,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖写烤,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件谊却,死亡現(xiàn)場離奇詭異,居然都是意外死亡锹漱,警方通過查閱死者的電腦和手機(jī)胆屿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進(jìn)店門奥喻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來偶宫,“玉大人非迹,你說我怎么就攤上這事〈壳鳎” “怎么了憎兽?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長吵冒。 經(jīng)常有香客問我纯命,道長,這世上最難降的妖魔是什么痹栖? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任亿汞,我火速辦了婚禮,結(jié)果婚禮上揪阿,老公的妹妹穿的比我還像新娘疗我。我一直安慰自己,他們只是感情好南捂,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布吴裤。 她就那樣靜靜地躺著,像睡著了一般溺健。 火紅的嫁衣襯著肌膚如雪麦牺。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天鞭缭,我揣著相機(jī)與錄音剖膳,去河邊找鬼。 笑死岭辣,一個胖子當(dāng)著我的面吹牛吱晒,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播易结,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼枕荞,長吁一口氣:“原來是場噩夢啊……” “哼柜候!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起躏精,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤渣刷,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后矗烛,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體辅柴,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年瞭吃,在試婚紗的時候發(fā)現(xiàn)自己被綠了碌嘀。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡歪架,死狀恐怖股冗,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情和蚪,我是刑警寧澤止状,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站攒霹,受9級特大地震影響怯疤,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜催束,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一集峦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧抠刺,春花似錦塔淤、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至买优,卻和暖如春妨马,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背杀赢。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工烘跺, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人脂崔。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓滤淳,卻偏偏與公主長得像,于是被迫代替她去往敵國和親砌左。 傳聞我的和親對象是個殘疾皇子脖咐,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容