2017-07-13 70 views
1

我最近開始學習編碼,並遇到一個問題,就是將已經變成變量的字符串附加到數組中。 這裏是控制檯說:如何使用變量將字符串追加到數組中? Swift

不能轉換型的價值「[字符串]」到期望的參數類型「字符串」

這裏是我的代碼:

var randomList = [String]() 

func getList(inputList:Array<String>) -> Array<String>{ 

    randomList = inputList 

    return randomList 
} 

func addItem(item: String...) -> String{ 

    randomList.append(item) 

    return "\(item) was added" 
} 

func getItem(x: Int) -> String{ 
    return randomList[x] 
} 
+1

T因爲你正在嘗試追加randomList的數組。 * item *的類型是array不是String。因此,通過* item *循環,然後附加循環值 – kathayatnk

回答

3

字符串數組只需更改您的代碼:

func addItem(item: String...) -> String{ 

    randomList.append(contentsOf: item) 

    return "\(item) was added" 
} 

然後你就可以增加1個或多個字符串像此:

addItem(item: "Hello", "you", "there") 

結果數組看起來像這樣:

print(randomList) 

[ 「你好」, 「你」, 「有」]


要追加一個字符串:

let singleString = "hi" 

addItem(item: singleString) 

要附加多個字符串:

let stringOne = "one" 
let stringTwo = "two" 
let stringThree = "three" 

addItem(item: stringOne, stringTwo, stringThree) 
1

因爲要附加一個字符串數組不是單個字符串。 item是一個字符串數組。

您可以刪除...以追加單個項目。

func addItem(item: String) -> String{ 

    randomList.append(item) 

    return "\(item) was added" 
} 

,或者如果要追加使用randomList.append(contentsOf: item)

func addItem(item: String...) -> String{ 

    randomList.append(contentsOf: item) 

    return "\(item) was added" 
} 
1

您正在使用被視爲數組的可變參數(...)。

這就是錯誤信息所說的。您傳遞的是預期有單個字符串的字符串數組。

解決辦法有兩個:

  1. 更改item參數String

    func addItem(item: String) -> String{ 
    
  2. 使用API​​來追加數組的內容:

    randomList.append(contentsOf: item) 
    
相關問題