<HTML><BODY>Thanks. Why generic function don not require memory allocate for inout variable, even if it is protocol type?<br><br><br><blockquote style="border-left:1px solid #0857A6; margin:10px; padding:0 0 0 10px;">
        Пятница, 26 мая 2017, 19:35 +03:00 от Guillaume Lessard <glessard@tffenterprises.com>:<br>
        <br>
        <div id="">
        
<div class="js-helper js-readmsg-msg">
        <style type="text/css"></style>
        <div>
                <base target="_self" href="https://e.mail.ru/">
                
<div id="style_14958165190000000972_BODY">In your example, the compiler needs a parameter of type Position. Car is a type of Position, but they are not interchangeable. See below:<br>
<br>
> On May 26, 2017, at 00:33, Седых Александр via swift-users <<a href="mailto:swift-users@swift.org">swift-users@swift.org</a>> wrote:<br>
> <br>
> protocol Position {<br>
> var x: Double { getset }<br>
> }<br>
> <br>
> struct Car: Position {<br>
> var x: Double<br>
> }<br>
> <br>
> func move(item: inout Position) {<br>
> item.x += 1<br>
> }<br>
> <br>
> var car = Car(x: 50)<br>
<br>
var pos: Position = car<br>
<br>
move(item: &pos) // this works.<br>
assert(pos.x == 51) // works<br>
<br>
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.)<br>
<br>
You may want a generic function instead:<br>
<br>
func move<P: Position>(item: inout P) {<br>
item.x += 1<br>
}<br>
<br>
move(item: &car) // this works, since it’s now calling the generic function.<br>
assert(car.x == 51) // works<br>
<br>
Cheers,<br>
Guillaume Lessard<br>
<br>
</div>
                <base target="_self" href="https://e.mail.ru/">
        </div>
        
</div>
</div>
</blockquote>
<br></BODY></HTML>