类型' [String]'的不可变值只有变异成员

时间:2015-07-30 13:06:58

标签: ios arrays swift

在我的swift项目中获取Immutable value of type '[String]' only has mutating member的错误并研究了一些答案,似乎没有人在我的上下文中解决问题。看一看: 导入UIKit

class PassionViewController: UIViewController {

   var factIndex = 0
   var counter = 1


    @IBOutlet var QuoteImage: UIImageView!

    @IBOutlet weak var funFactLabel: UILabel!

    let factBook = FactBook()
    let Liked = Favourite()
    override func viewDidLoad() {
        super.viewDidLoad()



        funFactLabel.text = factBook.factsArray[factIndex]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func showFunFact() {
        factIndex++
        if (factIndex >= factBook.factsArray.count) {
            self.factIndex = 0
        }
        funFactLabel.text = factBook.factsArray[factIndex]

        if counter == 36 {

            counter = 1

        } else {

          self.counter++

        }

        QuoteImage.image = UIImage(named: "frame\(counter).jpg")

    }
    @IBAction func goBack() {
        factIndex--
        var number = factBook.factsArray.count-1
        if (factIndex < 0){
            self.factIndex = number


        }
        funFactLabel.text = factBook.factsArray[factIndex]
        if counter == 1 {

            counter = 36

        } else {

            self.counter--

        }

        QuoteImage.image = UIImage(named: "frame\(counter).jpg")

    }
    @IBAction func Like() {


    let currentQuote = factBook.factsArray[factIndex]
           Liked.favouriteArray.append(currentQuote)
        }
    }

从另一个视图控制器中检索let currentQuote = factBook.factsArray[factIndex], factBook.factsArray,该控制器是一个数组集合。 Liked.favouriteArray.append(currentQuote)是将此元素存储到favouriteArray中,该元素来自名为Favorite:

的结构
import Foundation



struct Favourite {

    var favouriteArray:[String] = []








}

然而,Liked.favouriteArray.append(currentQuote)行正在生成错误:类型&#39; [String]&#39;的不可变值。只有变异成员。我该如何解决这个错误?

1 个答案:

答案 0 :(得分:1)

目前还不清楚,因为您没有提供Favourite类型,但我认为它不是struct,或者是{{1}包含class作为factsArray变量的}。在任何一种情况下,您都试图修改let变量,这是不允许的(改变不可变值)。 letliked必须为factsArray。 (如果varFavourite,则struct在任何一种情况下都必须为liked。)

请注意,Swift函数,方法,属性和变量应以小写字母开头。前导大写字母表示类型。