Skip to content

Instantly share code, notes, and snippets.

@thekarladam
Created Nov 16, 2015
Embed
What would you like to do?
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

thekarladam commented Nov 16, 2015

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

Loading

@thekarladam
Copy link
Author

thekarladam commented Nov 17, 2015

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

Loading

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