簡體   English   中英

注釋支持符合協議的Swift函數聲明?

[英]Annotating Swift function declarations that support conformance to a protocol?

是否有一種標准機制用於在Swift中注釋函數聲明以指示它們是否存在,因為類符合某些協議?

例如,可能存在此聲明,因為類符合NSCoding (用override標記它會導致語法錯誤,所以它不是我正在尋找的那種注釋。)理想情況下,我正在尋找代碼級注釋(例如override而不是/*! ... */ )。

// ... annotation such as "conform to NSCoding", if possible
func encodeWithCoder(encoder: NSCoder) {
   // ...
}

你可以使用extension 例如:

protocol SomeProtocol {
    func doIt() -> Int
}


class ConcreteClass {
    ....
}

extension ConcreteClass: SomeProtocol {
    func doIt() -> Int {
       // ...
       return 1
    }
}

但是您無法在extension定義required初始化extension ,例如:

// THIS DOES NOT WORK!!!

class Foo: NSObject {
}
extension Foo: NSCoding {
    required convenience init(coder aDecoder: NSCoder) {
        self.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // ...
    }
}

發出錯誤:

error: 'required' initializer must be declared directly in class 'Foo' (not in an extension)
    required convenience init(coder aDecoder: NSCoder) {
    ~~~~~~~~             ^

在這種情況下,您應該使用// MARK: comments

class Foo: NSObject {

    // ...


    // MARK: NSCoding

    required init(coder aDecoder: NSCoder) {
        super.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // ... 
    }
}

暫無
暫無

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

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