簡體   English   中英

如何使不同的類符合具有不同功能的同一協議?

[英]How to make different classes conform to the same protocol with different functionality?

如果標題不清楚,我會先道歉,但是我想先了解一下代碼片段是如何實現的:

第一類:

@objc protocol FetchProtocol
{
    var someVar: Bool
    {
        get set
    }

    var someUIView: FetchProtocol
    {
        get set
    }

    func someFuncOne()
}

class ClassOne: UIViewController, FetchProtocol
{
    ...

    @IBOutlet var someUIView: FetchProtocol!

    ....

}

第二類:

@objc protocol FetchProtocol
{
    var someVar: Bool
    {
        get set
    }

    var someTableView: FetchProtocol
    {
        get set
    }

    var someUIView: FetchProtocol
    {
        get set
    }

    func someFuncOne()
    func someFuncTwo()
}

class ClassTwo: UIViewController, FetchProtocol
{
    ...

    @IBOutlet var someTableView: FetchProtocol!
    @IBOutlet var someUIView: FetchProtocol!

    ....

}

ClassOneClassTwo遵循相同的FetchProtocol並且兩個類都使用相同的someVarsomeFuncOne ,但是ClassTwo也使用someTableView someFuncTwo唯一的someTableViewClassTwo

如何在兩個類之間使用相同的協議,但是另一個類具有“其他”不同的骨架實現?

例如,如下所示:

if let vc = currentVC as? FetchProtocol
{
    if vc.someVar == true
    {
        // Check if vc is of class type ClassOne, call someFuncOne

        // Otherwise if vc is of class type ClassTwo, call someFuncOne and someFuncTwo

    }
}

是否可以使用協議來實現上述類似功能?如果可以,如何正確實現呢?還是有另一種選擇?

您的代碼無法編譯,我認為您過於復雜,為了使用它們使用協議。 如果您要做的只是以下操作,則根本不需要使用任何協議:

if let vc = currentVC as? FetchProtocol
{
    if vc.someVar == true
    {
        // Check if vc is of class type ClassOne, call someFuncOne

        // Otherwise if vc is of class type ClassTwo, call someFuncOne and someFuncTwo

    }
}

為什么不刪除所有協議,只做:

if currentVC.someVar {
    if let class1 = currentVC as? ClassOne {
        class1.someFuncOne()
    } else if let class2 = currentVC as? ClassTwo {
        class2.someFuncOne()
        class2.someFuncTwo()
    }
}

您實際上並不需要協議,因為無論是否存在協議,您仍然必須檢查currentVCClassOne還是ClassTwo

協議就像“黑匣子”。 考慮以下方法:

func foo(fetchObj: FetchProtocol) {
    fetchObj.someFuncOne()
}

foo並不關心fetchObj 什么。 它只是說:“我不在乎你是什么,只要做一些someFuncOne !”

您在這里嘗試做的是完全相反的:“我確實在乎您是什么。如果您是ClassOne ,請執行此操作。如果您是ClassTwo ,請執行此操作。”

您的問題很抽象,很難遵循,但這確實滿足您的要求。 話雖如此,我懷疑您根本不需要在這里使用協議。

protocol P1 {
    var someVar1: String { get }

    func func1();
}

protocol P2: P1 {
    var someVar2: String { get }
    func func2();
}


class C1: P1 {
    var someVar1 = "String 1 in C1"

    func func1() {
        print(someVar1)
    }
}

class C2: P2 {
    var someVar1 = "String 1 in C2"
    var someVar2 = "String 2 in C2"

    func func1() {
        print(someVar1)
    }

    func func2() {
        print(someVar2)
    }
}


func foo(with object: P1) {
    object.func1()

    if let object = object as? P2 {
        object.func2()
    }
}

print("Test case 1:")
foo(with: C1())
print("Test case 1:\n")
foo(with: C2())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM