İçeriğe geç

Swift ile Associatedtype Protocol kullanımı

swift

Merhabalar bu yazımda Swift 3.0 ile gelen protocol generics özelliğine örnek vereceğim. Generics Swift dili ile gelen çok güzel bir özellik ve çok işlevsel bu özelliği class,struct,enum,extension bir çok yerde kullanıyoruz.

Protocollerde typealias ile yapılan işlem 3.0 versiyonu ile deprected olmuş durumda aşağıda hazırladığım örnekte generics kullanılan bir fonksiyon üzerinde associatedtype kullanmış olduk.

protocol Control {
    
    associatedtype item
    
    mutating func append(d:item)
    mutating func restore()
    var count:Int {get}
    
}


struct Datas:Control {
    
    var dats = [String]()
    
    mutating func restore() {
        
        for i in 0..<dats.count {
            
            if dats[i].hasPrefix("a") {
                dats.removeAtIndex(i)
            }
        }
        
    }
    
    mutating func append(d: String) {
        dats.append(d)
    }
    
    var count: Int {
        
        return dats.count
    }
}

var nesne = Datas(dats: ["kenan","mehmet","ali"])

nesne.restore() // ali silindi
nesne.count // 2
nesne.append("murat") // ["kenan","mehmet","murat"]

 

Kategori:Swift

Bu yazı yorumlara kapalı.

Copyright © 2022 Kenan Atmaca