[swift-users] Why inout protocol parameter in function work with strange

Zhao Xin owenzx at gmail.com
Fri May 26 11:37:17 CDT 2017


Try this.

protocol Position {

    var x: Double { get set }

}


struct Car: Position {

    var x: Double

}


func move<T>(item: inout T) where T:Position {

    item.x += 1

}


var car = Car(x: 50)


move(item: &car)


car.x // 51


Zhaoxin

On Sat, May 27, 2017 at 12:35 AM, Guillaume Lessard via swift-users <
swift-users at swift.org> wrote:

> In your example, the compiler needs a parameter of type Position. Car is a
> type of Position, but they are not interchangeable. See below:
>
> > On May 26, 2017, at 00:33, Седых Александр via swift-users <
> swift-users at swift.org> wrote:
> >
> > protocol Position {
> >     var x: Double { getset }
> > }
> >
> > struct Car: Position {
> >     var x: Double
> > }
> >
> > func move(item: inout Position) {
> >     item.x += 1
> > }
> >
> > var car = Car(x: 50)
>
> var pos: Position = car
>
> move(item: &pos)    // this works.
> assert(pos.x == 51) // works
>
> The move function as you wrote it requires the memory representation of a
> Position variable, which Car does not have; when you assign it to a
> Position variable, the Car struct gets accessed through an indirection
> layer. (There was a WWDC talk about this last year or the year before.)
>
> You may want a generic function instead:
>
> func move<P: Position>(item: inout P) {
>   item.x += 1
> }
>
> move(item: &car)    // this works, since it’s now calling the generic
> function.
> assert(car.x == 51) // works
>
> Cheers,
> Guillaume Lessard
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170527/28fbe585/attachment.html>


More information about the swift-users mailing list