On 22.04.2016 22:06, Adrian Zubarev via swift-evolution wrote:
I’d like to throw an idea in the room and see where this will go.

What if Swift would allow us to create custom infix functions?
Does Swift need to ability of infix functions?
How powerful can such a feature be?
Pros and cons?

There is a discussion about the `with` statement which we could develop
with infix functions like so:

IMO Such construction will looks like a language construction and will confuse.

And the function you suggest as replacement for "with" feature will *not* correctly handle struct instances (Swift 3.0 mar 24):

struct B { var x = 10 }

func with<T: AnyObject>(lhs: T, rhs: @noescape (T) -> Void) {  rhs(lhs)  }

var b2 = B()
with(b2) { print($0.x) }

It will produce this error :
--------------
Error running code:
l-value expression does not have l-value access kind set
...
-------------

This is why I propose to introduce standard "with" feature(language feature or built-in method(s)/free function(s)) in Swift out-of-box i.e. tested and well-working solution in any situation. Not some hack/workaround that each one will write for himself and that will not work in some situation.

I can implement "with" method in some way for struct that will work like this:

struct B {
        var x = 10

        mutating func withInPlace(user: @noescape (inout B)->Void) -> B {
                var copy = self
                user(&copy)
                self = copy
                return self
        }

        func with(user: @noescape (inout B)->Void) -> B {
                var copy = self
                user(&copy)
                return copy
        }
}

var b1 = B().with {
    $0.x = 100
}

print("created b1.x = ", b1.x)

b1.withInPlace { $0.x = 1000 }

let c1 = b1.with {
    print("b1.x = ", $0.x)
    $0.x = 2000
}

print("b1.x = ", b1.x)
print("c1.x = ", c1.x)

But again, this is custom solution, we need standard and tested way to do this.



infix func with<T: AnyObject>(lhs: T, rhs: @noescape (T) -> Void) {

rhs(lhs)
}

class A {

func foo() {}
}

let instance: A = A() with {

$0.foo()
}

So what does the Swift community think about that idea?

--
Adrian Zubarev


_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to