2014-07-23 91 views
13

我在创建符合协议的Swift中的扩展时遇到问题。符合协议的Swift扩展

在Objective-C,我可以创建符合协议类别:

SomeProtocol.h

@protocol SomeProtocol 
... 
@end 

的UIView +类别名称

#import SomeProtocol.h 
@interface UIView (CategoryName) <SomeProtocol> 
... 
@end 

我想与Swift Extension一样实现

SomeProtocol.swift

protocol SomeProtocol { 
    ... 
} 

的UIView扩展

import UIKit 
extension UIView : SomeProtocol { 
... 
} 

我收到以下编译器错误:

Type 'UIView' does not conform to protocol 'SomeProtocol'

+1

你是否实现了协议中的方法? –

回答

17

请仔细检查您的扩展,您已经实现了def的所有方法在协议中列入。如果没有实现函数a,那么会得到您列出的编译器错误。

protocol SomeProtocol { 
    func a() 
} 

extension UIView : SomeProtocol { 
    func a() { 
     // some code 
    } 
} 
9
//**Create a Protocol:** 

protocol ExampleProtocol { 
    var simpleDescription: String { get } 
    func adjust()-> String 
} 


//**Create a simple Class:** 

class SimpleClass { 

} 

//**Create an extension:** 

extension SimpleClass: ExampleProtocol { 

    var simpleDescription: String { 

    return "The number \(self)" 
    } 

    func adjust()-> String { 

    return "Extension that conforms to a protocol" 

    } 


} 

var obj = SimpleClass() //Create an instance of a class 

println(obj.adjust()) //Access and print the method of extension using class instance(obj) 

结果:扩展符合协议

希望它可以帮助..!

+0

你能否解释一下如何确认var simpleDescription:String {get set}属性。 –

+0

@RajeshKumar'var simpleDescription:String { get {return“The number \(self)”} set(desc){self.simpleDescription = desc} } –