Created
December 5, 2014 23:14
-
-
Save acrosa/fd1e5aeeccafeb1d1a6b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| protocol ClassProtocol | |
| { | |
| var property: SomePropertyProtocol? { get set } | |
| } | |
| protocol SomePropertyProtocol | |
| { | |
| } | |
| class SomeClass : ClassProtocol | |
| { | |
| var property: SomePropertyProtocol? | |
| } |
Author
Remember my example:
class SomeClassA: ParentClass, ClassProtocol {}
class SomeClassB: ParentClass, ClassProtocol {}I can make ClassA and ClassB inherit from the more specific CustomClassAndProtocol, but I want to avoid that. Maybe ClassB will inherit from ParentClassSubclass (a subclass of ParentClass, for example.
Of course I can solve this by restricting each of the classes, but I want to avoid solving this with inheritance.
Another example in UIInputViewController.h
@property (nonatomic, readonly) NSObject <UITextDocumentProxy> *textDocumentProxy;
is compiled to Swift as
var textDocumentProxy: NSObject { get }
If the complier can't do it, I don't think we can
Best I can do:
protocol TestProtocol {
}
class ParentClass {
}
class TestClassA : ParentClass, TestProtocol {
}
class TestClassB : ParentClass, TestProtocol {
}
class TestClassC : ParentClass {
}
class TestClassD : TestProtocol {
}
struct Test<T where T: ParentClass, T: TestProtocol> {
var a: T.Type {
get {
return T.self
}
}
}
let t1 = Test<TestClassA>()
let t2 = Test<TestClassB>()
let t3 = Test<TestClassC>() // Type 'TestClassC' does not conform to protocol 'TestProtocol'
let t4 = Test<TestClassD>() // Type 'TestClassD' does not inherit from 'ParentClass'If you can, I will use a little protocol helper and call it a day:
protocol ParentClassProtocol {
}
class ParentClass: ParentClassProtocol {
}
struct Test2 {
var b: protocol<ParentClassProtocol, TestProtocol>.Protocol {
get {
return TestClassA.self
}
}
}You can add this protocol (a tag) in an extension for classes like UIView if you need.
The truth is that protocol<> should actually be type<> and work for real types...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I still don't understand, if you want a property to conform to a particular type (that is a subclass and a protocol at the same time), why not this: