0

i have 3 classes

class A {
    var uid: Int64!
    var countryCode: String? // <-- Attention 
}

class B {
    var uid: Int64!
    var countryCode: String! // <-- Attention
}

class C {
    var uid: Int64!
    var countryCode: String = "AA" // <-- Attention
}

witch var for example countryCode as String?, String! , String

and i create protocol, witch var as String? (As the weakest type to which you can bring all the others)

protocol FullCode {
    var uid: Int64! { get }
    var countryCode: String? { get } // <-- How to describe a variable for all (`T`, `T!`, `T?`) types?
}

extension FullCode {
    var fullCode: String? { return "specificCode"}
}

bat if i added it to my classes

extension A : FullCode {}
extension B : FullCode {}
extension C : FullCode {}

i get error for classes B & C.

How can use one protocol for these types?

EvGeniy Ilyin
  • 1,817
  • 1
  • 21
  • 38
  • Related: [Why can't a get-only property requirement in a protocol be satisfied by a property which conforms?](http://stackoverflow.com/q/42561685/2976878). There's no real reason why your code shouldn't work, as both `String!` and `String` are convertible to `String?`. The compiler just doesn't support it yet. – Hamish Mar 21 '17 at 09:36

1 Answers1

1

You can't make either B or C conform to FullCode, because the types for countryCode are incompatible.

You can't make this work by changing the type of FullCode.countryCode, because there is no common supertype for String, String!, and String?.

You'll need to change FullCode to declare some other property. Example:

protocol FullCode {
    var uid: Int64! { get }
    var optionalCountryCode: String? { get }
}

extension A : FullCode {
    var optionalCountryCode: String? { return countryCode }
}

extension B : FullCode {
    var optionalCountryCode: String? { return countryCode }
}

extension C : FullCode {
    var optionalCountryCode: String? { return countryCode }
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848