2017-03-09 74 views
0

我一直在仿製藥和擴展玩弄於現有各類在斯威夫特3.我寫了兩個通用陣列功能與擴展陣列查找和替換方法,分別是()取代和替換( )。 replace()函數按預期工作,但replace()函數有編譯時錯誤。以下是代碼和其中一種方法的測試。通用擴展陣列不工作

extension Array { 
    func replaced<T: Equatable>(each valueToReplace: T, with newValue: T) -> [T] { 
     var newArray:[T] = [] 
     for index:Int in 0..<self.count { 
      if let temp = self[index] as? T, temp == valueToReplace{ 
       newArray.append(newValue) 
      }else{ 
       newArray.append(self[index] as! T) 
      } 
     } 
     return newArray 
    } 
    mutating func replace<T: Equatable>(each valueToReplace: T, with newValue: T) { 
     for index:Int in 0..<self.count { 
      if let temp = self[index] as? T, temp == valueToReplace { 
       // FIXME: self[index] = newValue 
      } 
     } 
     return 
    } 
} 
var j = [1,2,3,4,3,6,3,8,9] 
var newArray = j.replaced(each: 3, with: 0) 

我上第二方法的編譯時間錯誤,更換()中,在以「// FIXME:」註釋的註解行。編譯時錯誤說:「模糊引用成員'下標'」。

如何修復替換()代碼,所以它的工作原理?

+1

非常類似的問題,以http://stackoverflow.com/q/41045212/2976878 - 您正在定義新的本地通用佔位符「T」,而不是使用「Array」的「元素」類型。 – Hamish

+0

只是讓在陣列擴展'擴展陣列的約束,其中元素:Equatable {' –

+0

一旦你使用了'Element',你可以簡單的實現'replaced'顯著爲'返回地圖{$ 0 == valueToReplace? NEWVALUE:$ 0}'順便說一句:) – Hamish

回答

1

這給了一槍

extension Array where Element: Equatable { 
    func replaced (each valueToReplace: Element, with newValue: Element) -> [Element] { 
     var newArray = [Element]() 
     newArray.reserveCapacity(self.count) 

     for element in self { 
      let newElement = (element == valueToReplace) ? newValue : element 
      newArray.append(newElement) 
     } 

     return newArray 
    } 

    mutating func replace(each valueToReplace: Element, with newValue: Element) { 
     for (i, element) in self.enumerated() { 
      if element == valueToReplace { self[i] = newValue } 
     } 
    } 
} 

var j = [1,2,3,4,3,6,3,8,9] 
var newArray = j.replaced(each: 3, with: 0) 

這將是更好的只是讓replaced委託replace去除冗餘:

extension Array where Element: Equatable { 
    func replaced(each valueToReplace: Element, with newValue: Element) -> [Element] { 
     var copy = self 
     copy.replace(each: valueToReplace, with: newValue) 
     return copy 
    } 

    mutating func replace(each valueToReplace: Element, with newValue: Element) { 
     for (i, element) in self.enumerated() { 
      if element == valueToReplace { self[i] = newValue } 
     } 
    } 
} 
+0

'突變FUNC取代(每個元素:元素,具有爲newElement:元素){ 自我=地圖{$ 0 ==元件?爲newElement:$ 0} }' –

+0

@LeoDabus好一點,但我最終修剪代碼反正 – Alexander

+1

@Alexander對於'replace'你可以在使用'where'子句中的for循環 - '在自我(索引,元) .enumerated()其中元素== valueToReplace {self [index] = newValue}':) – Hamish