简体   繁体   English

Swift:使用与号(&)引用对象的属性会导致编译器错误

[英]Swift: taking reference of object's property with ampersand (&) causing compiler error

This is a rather straightforward issue. 这是一个相当简单的问题。 Consider an array: 考虑一个数组:

var array = [1, 2, 3, 4, 5, 6, 7]

I wish to swap the first and the last element of the array, using the standard swap function: 我希望使用标准swap功能swap数组的第一个和最后一个元素:

swap(&array[0], &array[array.count - 1])

However there exists another way to obtain the first and last elements of an array, which is to use Array 's built-in properties first and last . 但是,存在另一种获取数组的第一个和最后一个元素的方法,即使用Array的内置属性firstlast It follows that this code should also work: 因此,该代码也应起作用:

swap(&array.first!, &array.last!)

However this time the compiler complains that Type of expression is ambiguous without more context . 但是,这一次编译器抱怨Type of expression is ambiguous without more context I wonder how I can modify the expression so that the compiler can parse it correctly. 我不知道如何修改表达式,以便编译器可以正确解析它。

first is a read-only property, therefore you cannot modify the array through array.first . first是一个只读属性,因此您不能通过array.first修改数组。

swap(&array[0], &array[array.count - 1])

works because subscript() of mutable collection types has both setter and getter. 之所以起作用,是因为可变集合类型的subscript()具有setter和getter。

Not that I recommend it, but if you define your own read-write properties 我不建议这样做,但是如果您定义自己的读写属性

extension Array {
    var myFirst: T {
        get { return self[0] }
        set { self[0] = newValue }
    }
    var myLast: T {
        get { return self[count - 1] }
        set { self[count - 1] = newValue }
    }
}

(which assume that the array it not empty) then (假设该数组不为空)然后

swap(&array.myFirst, &array.myLast)

works as expected. 如预期般运作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM