我需要在String
擴展名內打印String
。我知道增加一個String
與另一個String
。但是,不能在類型'String'的不可變值上使用變異成員
爲什麼下面的代碼給我一個錯誤?
這樣可以解決這個錯誤嗎?
如果是,如何?
代碼:
extension String{
func fruit(){
//After some manipulation with self I need to print
print("Apple".parent("Tree"))
print("Tomato".parent("Plant"))
}
mutating func parent(_ word:String){
self = self+" "+word
}
}
錯誤:
無法在類型的不可變的值使用可變成員 '字符串'
返回比分配給自己更好。 +1。 – Alexander
第一個解決方案:當我需要打印1000個單獨的水果時,我認爲'var string =「Hello」'很差。它也給我一個錯誤:'不能分配類型'()'的值來鍵入'String?',而第二個是好的。感謝您的簡要解釋 –
@ RAJAMOHAN-S如果您認爲我的答案回答您的問題,請考慮接受它! – Sweeper