【问题标题】:Why isn't this [Int]-Element of type 'Int'? [duplicate]为什么这个 [Int] 元素不是“Int”类型的? [复制]
【发布时间】:2014-12-22 20:51:25
【问题描述】:

我试着只写一个简单的冒泡排序函数:

func bubbleSort(array: [Int]) -> [Int] {
    while !isSorted(array) {
        for index in 1..<array.count {
            if array[index - 1] > array[index] {                
                let temp: Int = array[index]
                array[index] = array[index - 1]
                array[index - 1] = temp
            }
        }
    }

    return array
}

检查,当数组被排序时,它使用:

func isSorted(array: [Int]) -> Bool {
    for index in 1..<array.count {
        if array[index - 1] > array[index] {
            return false
        }
    }

    return true
}

我使用http://swiftstub.com/ 编译代码,但它给了我以下错误消息:

<stdin>:17:17: error: '@lvalue $T11' is not identical to 'Int'
array[index] = array[index - 1]
^
<stdin>:18:17: error: '@lvalue $T8' is not identical to 'Int'
array[index - 1] = temp
^

(如果您想在网站上查看:http://swiftstub.com/385904096/


array[index]array[index - 1] 怎么不能都属于Int 类型,它们怎么可能属于不同类型?

【问题讨论】:

    标签: swift


    【解决方案1】:

    那是因为传递给函数的数组是不可变的。为了使其可变,您必须使用 inout 修饰符通过引用传递它:

    func bubbleSort(inout array: [Int]) -> [Int] {
    

    注意,当使用inout时,你必须在调用函数时使用&amp;操作符将相应的参数作为引用传递:

    let res = bubbleSort(&myArray)
    

    另请注意,要交换 2 个变量,您只需使用:

    swap(&array[index], &array[index - 1])
    

    推荐阅读:In-Out Parameters

    【讨论】:

    • 那不是通过引用传递数组,这意味着它会改变数组的原始版本吗?
    • 您必须使用 &amp; 运算符 - 阅读更新后的答案,同时阅读链接文档
    • 嗯,完全正确...假设我不想通过引用传递数组,这样原始版本就不会改变。我该怎么做?
    • @445646: func bubbleSort(var array: [Int]) -&gt; [Int]
    • 感谢@MartinR。 var 使参数可变,但当然这只是一个副本。因此传递给函数的原始数组不受 func 主体内部的任何更改的影响。
    猜你喜欢
    • 1970-01-01
    • 2016-06-08
    • 2020-06-05
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    相关资源
    最近更新 更多