Skip to content

Instantly share code, notes, and snippets.

@tjw
Last active August 29, 2015 14:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjw/151bdebb6a8eb029a3ba to your computer and use it in GitHub Desktop.
Save tjw/151bdebb6a8eb029a3ba to your computer and use it in GitHub Desktop.
Can't access members of protocol types
public protocol MeasurementUnit {
// If we have one of this unit, how many millimeters is it?
class var asMillimeters: Double { get }
}
public class Inch : MeasurementUnit {
public class var asMillimeters: Double {
get {
return 25.4
}
}
}
let unit: MeasurementUnit.Type = Inch.self
println("unit to mm = \(unit.asMillimeters)")
/* Yields:
protocol-type-member.swift:15:25: error: accessing members of protocol type value 'MeasurementUnit.Type' is unimplemented
*/
@DivineDominion
Copy link

Did you find a solution?

@mdonati
Copy link

mdonati commented Dec 7, 2014

I'm interested to find a solution to this too. Please let us know if you find anything. I'll do the same.

@arpi0003
Copy link

arpi0003 commented Dec 8, 2014

also would like to do this...

@armstrongnate
Copy link

It would seem swift does not yet support protocol type properties or methods yet. In the meantime the next best thing would be to make it an instance variable, I guess?

public protocol MeasurementUnit {
  var asMillimeters: Double { get }
  init()
}

public class Inch: MeasurementUnit {
  public var asMillimeters: Double {
    get { return 25.4 }
  }

  public required init() {}
}

let unit: MeasurementUnit.Type = Inch.self
unit().asMillimeters

It's not great but it will work for me for now.

@andhieka
Copy link

andhieka commented Apr 9, 2015

This is not fixed yet as of April 2015. So annoying. I need to implement the following:

protocol CloudStorable {
   class var classUrlString: String { get }
}

class DownloadTask<T: CloudStorable> {

   func execute() {
      var destinationUrl = "http://localhost:1234/" + T.classUrlString
      // this does not work, and I cannot simply make the property non-static
      // because I do not have an instance of CloudStorable before downloading.
   }
}

@benrudhart
Copy link

I'd also like to know how this works...

@klaas
Copy link

klaas commented May 27, 2015

+1

@jishh
Copy link

jishh commented Jun 22, 2015

"@objc protocol meas {
class var asm: Double{get}
}

class inc : meas {
class var asm: Double {
get {
return 25
}
}

}

let a = inc.self as meas.Type
let b:AnyClass = a as Any as AnyClass
b.asm"

Can you try this .I have made protocol to objc type, and did some downcasting. Please let me know if this worked

@jgongo
Copy link

jgongo commented Aug 5, 2015

It seems you can access the static method as long as you declare the protocol using @objc and then cast the variable to AnyClass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment