Swift'de genel protokoller nasıl oluşturulur?


85

Genel bir girdi alan ve genel bir değer döndüren bir yöntemle bir protokol oluşturmak istiyorum.

Şimdiye kadar denediğim şey buydu, ancak sözdizimi hatası veriyor.

T belirtilmemiş tanımlayıcı kullanımı.

Neyi yanlış yapıyorum?

protocol ApiMapperProtocol {
    func MapFromSource(T) -> U
}

class UserMapper: NSObject, ApiMapperProtocol {
    func MapFromSource(data: NSDictionary) -> UserModel {
        var user = UserModel() as UserModel
        var accountsData:NSArray = data["Accounts"] as NSArray     
        return user
    } 
}

Lütfen cevabımı kontrol edin: stackoverflow.com/a/54900296/3564632
denis_lor

Yanıtlar:


143

Protokoller için biraz farklı. Apple belgelerinde "İlişkili Türler" e bakın .

Örneğinizde bu şekilde kullanıyorsunuz

protocol ApiMapperProtocol {
    associatedtype T
    associatedtype U
    func MapFromSource(_:T) -> U
}

class UserMapper: NSObject, ApiMapperProtocol {
    typealias T = NSDictionary
    typealias U = UserModel

    func MapFromSource(_ data:NSDictionary) -> UserModel {
        var user = UserModel()
        var accountsData:NSArray = data["Accounts"] as NSArray
        // For Swift 1.2, you need this line instead
        // var accountsData:NSArray = data["Accounts"] as! NSArray
        return user
    }
}

5
ApiMapperProtocol'un tek amacının genel sınırlama için kullanılması olduğunu unutmayın. Let x: ApiMapperProtocol = UserMapper ()
Ben

19
Apple neden her şeyi bu kadar sezgisel hale getirmekte ısrar ediyor?
deusprogrammer

@Ben nasıl elde edilir x: ApiMapperProtocol = UserMapper () bu durumda?
denis_lor

@denis_lor yerelse x, türünü açıkça söylemenize gerek yoktur, bu yüzden let x = UserMapper().
Ben Leggiero

2
@BenLeggiero Az önce şunu öğrendim: let x: ApiMapperProtocol = UserMapper () eğer orta genel sınıfta a kullanıyorsanız: stackoverflow.com/a/54900296/3564632
denis_lor

21

Lou Franco'nun cevabını biraz açıklamak gerekirse , Belirli bir yöntemi kullanan bir yöntem yaratmak ApiMapperProtocolistiyorsanız, bunu şu şekilde yaparsınız:

protocol ApiMapperProtocol {
    associatedtype T
    associatedtype U
    func mapFromSource(T) -> U
}

class UserMapper: NSObject, ApiMapperProtocol {
    // these typealiases aren't required, but I'm including them for clarity
    // Normally, you just allow swift to infer them
    typealias T = NSDictionary 
    typealias U = UserModel

    func mapFromSource(data: NSDictionary) -> UserModel {
        var user = UserModel()
        var accountsData: NSArray = data["Accounts"] as NSArray
        // For Swift 1.2, you need this line instead
        // var accountsData: NSArray = data["Accounts"] as! NSArray
        return user
    }
}

class UsesApiMapperProtocol {
    func usesApiMapperProtocol<
        SourceType,
        MappedType,
        ApiMapperProtocolType: ApiMapperProtocol where
          ApiMapperProtocolType.T == SourceType,
          ApiMapperProtocolType.U == MappedType>(
          apiMapperProtocol: ApiMapperProtocolType, 
          source: SourceType) -> MappedType {
        return apiMapperProtocol.mapFromSource(source)
    }
}

UsesApiMapperProtocolartık yalnızca SourceTypeverilenle uyumlu e-postaları kabul etmesi garanti edilmektedir ApiMapperProtocol:

let dictionary: NSDictionary = ...
let uses = UsesApiMapperProtocol()
let userModel: UserModel = uses.usesApiMapperProtocol(UserMapper()
    source: dictionary)

Bu çok güzel bir yazı. Birkaç aptalca soru: neden as!sadece asSwift 1.2 yerine kullanmaya karar verdiler ? İkincisi: protokole uyan sınıfta neden type aliasyeniden (yani typealias T = NSDictionary typealias U = UserModel) tanımlamamız gerektiğini bana söyleyebilir misiniz ? Şimdiden teşekkürler.
Unheilig

Nereden anahtarlamalı neden bilmiyorum asiçin as!. Devforumları kontrol edin.
Heath Borders

typealias T=NSDictionaryve typealias U=UserModelgerekli değildir. Örneği bunu yansıtacak şekilde güncelledim.
Heath Borders

2
gibi! başarısız olabileceğini belirtmek için. Geliştiriciye daha net hale getirir.
user965972

Cevabın altında.
Heath Sınırları

4

Jeneriklere sahip olmak ve bunun gibi bildirmek let userMapper: ApiMapperProtocol = UserMapper()için, genel bir öğe döndüren protokole uyan bir Genel Sınıfa sahip olmanız gerekir.

protocol ApiMapperProtocol {
    associatedtype I
    associatedType O
    func MapFromSource(data: I) -> O
}

class ApiMapper<I, O>: ApiMapperProtocol {
    func MapFromSource(data: I) -> O {
        fatalError() // Should be always overridden by the class
    }
}

class UserMapper: NSObject, ApiMapper<NSDictionary, UserModel> {
    override func MapFromSource(data: NSDictionary) -> UserModel {
        var user = UserModel() as UserModel
        var accountsData:NSArray = data["Accounts"] as NSArray     
        return user
    } 
}

Şimdi, aşağıdakilere yönelik belirli bir uygulaması olan bir uygulama userMapperolarak da başvurabilirsiniz :ApiMapperUserMapper

let userMapper: ApiMapper = UserMapper()
let userModel: UserModel = userMapper.MapFromSource(data: ...)

1
Bu durumda bir protokole sahip olmanın ne anlamı var? Beyannamesinde kullanılmaz userMapper.
alekop

-1

GENEL PROTOKOL NASIL SUNULUR VE KULLANILIR

protocol Generic {

associatedtype T
associatedtype U

func operation(_ t:T)->U

}

// Genel Protokolü kullan

struct Test: Generic {

typealias T = UserModel
typealias U = Any

func operation(_ t: UserModel)->Any {
    let dict = ["name":"saurabh"]
    return dict
    
} 

}


-3

Tür silme ile şablon yöntemlerini kullanabilirsiniz ...

protocol HeavyDelegate : class {
  func heavy<P, R>(heavy: Heavy<P, R>, shouldReturn: P) -> R
}  

class Heavy<P, R> {
    typealias Param = P
    typealias Return = R
    weak var delegate : HeavyDelegate?  
    func inject(p : P) -> R? {  
        if delegate != nil {
            return delegate?.heavy(self, shouldReturn: p)
        }  
        return nil  
    }
    func callMe(r : Return) {
    }
}
class Delegate : HeavyDelegate {
    typealias H = Heavy<(Int, String), String>

    func heavy<P, R>(heavy: Heavy<P, R>, shouldReturn: P) -> R {
        let h = heavy as! H
        h.callMe("Hello")
        print("Invoked")
        return "Hello" as! R
    }  
}

let heavy = Heavy<(Int, String), String>()
let delegate = Delegate()
heavy.delegate = delegate
heavy.inject((5, "alive"))

2
Bu gönderi açıklama içermiyor. Bunu olduğu gibi stackoverflow.com/questions/28614990/…
adresinde
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.