Skip to content

Instantly share code, notes, and snippets.

@thekarladam
Created November 16, 2015 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thekarladam/c3094769cc8c87bf55e3 to your computer and use it in GitHub Desktop.
Save thekarladam/c3094769cc8c87bf55e3 to your computer and use it in GitHub Desktop.
func admitFromNode<T : NodeDerivable>(node: Node) -> T? {
return T.fromNode(node)
}
protocol NodeDerivable {
static func fromNode(node: Node) -> Self?
}
extension Int : NodeDerivable {
static func fromNode(node: Node) -> Int? {
return Int(node.text)
}
}
extension Double : NodeDerivable {
static func fromNode(node: Node) -> Double? {
return Double(node.text)
}
}
extension String : NodeDerivable {
static func fromNode(node: Node) -> String? {
return String(node.text)
}
}
extension NSURL : NodeDerivable {
static func fromNode(node: Node) -> NSURL? { //error: method 'fromNode' in non-final class 'NSURL' must return `Self` to conform to protocol 'NodeDerivable'
//static func fromNode(node: Node) -> Self? { //error: cannot convert return expression of type 'NSURL?' to return type 'Self?'
return NSURL(string: node.text)
}
}
@thekarladam
Copy link
Author

struct Node {
    var text : String
}

func admitFromNode<T : NodeDerivable>(node: Node) -> T? {
    return T.fromNode(node)
}

protocol NodeDerivable {
    static func fromNode(node: Node) -> Self?
}

extension NodeDerivable {
    static func fromNode(node: Node) -> Self? {
        return dynamicType.init(_: node.text) // initializers may only be declared within a type & expected expression in return statement
    }
}

There seems to be no way around this but it should work

@thekarladam
Copy link
Author

struct Node {
    var text : String
}

func admitFromNode<T : NodeDerivable>(node: Node) -> T? {
    return T.fromNode(node)
}

protocol NodeDerivable {
    static func fromNode(node: Node) -> Self?
    init?(_: String)
}

extension NodeDerivable {
    static func fromNode(node: Node) -> Self? { // error: method 'fromNode' in non-final class 'NSURL' must return `Self` to conform to protocol 'NodeDerivable'
        return self.init(node.text)
    }
}

extension Int : NodeDerivable {} // error: type 'Int' does not conform to protocol 'NodeDerivable'; multiple non-matching inits
extension Double : NodeDerivable {}
extension String : NodeDerivable {}
extension NSURL : NodeDerivable {} // error: type 'NSURL' does not conform to protocol 'NodeDerivable'; multiple matches

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