2017-03-01 14 views
-3
func removing (item: Int, fromArray: [Int]) -> [Int] { 

    for i in 0...fromArray.count-1 { 
     if fromArray[i] == item { 
      let index = i 
      fromArray.remove(at: index) // Error : cannot use mutating member on immutable value : 'fromArray' is a 'let' constant 
     } 
    } 
    return fromArray 
} 

var anarray : [Int] = [1, 2,3, 4 ,3] 
var x = 3 
removing(item: x, fromArray: anarray) 

回答

1

那麼,你也有一個從數組中刪除元素,然後超出其界限的問題。試試這樣:

func removeInPlace(item: Int, fromArray: inout [Int]) -> Void { 

    for i in stride(from: fromArray.count - 1, to: 0, by: -1) 
    { 
     if fromArray[i] == item { 
      fromArray.remove(at: i) 
     } 
    } 

} 

var anarray : [Int] = [1, 2,3, 4 ,3] 

var x = 3 

print(anarray) // prints [1, 2, 3, 4, 3] 

removeInPlace(item: x, fromArray: &anarray) 

print(anarray) // prints [1, 2, 4] 

你會想要額外的錯誤處理,但希望這有助於你的方式。

+0

向上投票。我收到了關於超越界限的評論,而與OP不同的問題,我會指出他的答案。 – dfd

0

如果你想修改的方法中的方法參數,你可以使用inout關鍵字聲明(見the docs):

func removing(item: Int, fromArray: inout [Int]) -> [Int] 
{ 
    ... 
} 

沒有inout關鍵字,所有的方法參數是恆定的值。

0

默認情況下,swift中的參數是常量,但是如果你想在函數中對它進行變異,那麼它需要在inout變量中。您可以通過指定的參數作爲INOUT作爲

func removing (item: Int, fromArray : inout [Int]) -> [Int] 
0

您所看到的錯誤是遵循在試圖從只讀數組刪除一個數組值實現它。也就是說,fromArray是隻讀的,因此是不可變的。你有兩個選擇。

選項#1:

func removing (item: Int, fromArray: inout [Int]) { 

    for i in 0...fromArray.count-1 { 
     if fromArray[i] == item { 
      let index = i 
      fromArray.remove(at: index) // Error : cannot use mutating member on immutable value : 'fromArray' is a 'let' constant 
     } 
    } 
} 

選項#2:爲的就是使用功能,而是照搬通過添加inout給它,並傳回什麼使輸入陣列讀寫陣列成一個新的:

func removing (item: Int, fromArray: inout [Int]) { 

    var newArray = fromArray 
    for i in 0...newArray.count-1 { 
     if newArray[i] == item { 
      let index = i 
      newArray.remove(at: index) 
     } 
    } 
    return newArray 
} 

除非inout所示,傳遞到功能在夫特總是隻讀的任何參數。

+0

VAR anarray:[INT] = [1,2,3,4,3] 變種X = 3 打印( 「\(除去(項目:X,fromArray:&anarray))」) //當我添加了'inout',並且我得到了致命錯誤「索引超出範圍」 –

+0

這是一個非常不同的錯誤。讓我檢查一下,然後編輯我的答案。 – dfd

+0

選項3:只需用'anArray = anArray.filter {$ 0!= x}'替換整個東西':) –

相關問題