LoginSignup
1
1

More than 5 years have passed since last update.

Cannot assign through subscript: '○○' a 'let' constant とエラーが出た

Posted at

動物の名前をランダムに並び替える関数を書いていいたらエラーが出た

class ViewController: UIViewController {

var c = ["うさぎ","ねこ","たぬき","ぞう","キリン","パンダ"]

    func change(c:[String]) -> [String] {
        for x in 0...5 {
            var a = c[x]
            var y = Int(arc4random_uniform(6))
            var b = c[y]
            c[x] = b
            c[y] = a
        }
        return c
    }




}

c[x] = b
c[y] = a
のところで両方とも
Cannot assign through subscript: 'c'is a 'let' constant
というエラーが出る。

調べると
https://samekard.blogspot.jp/2014/09/swifterror.html
にあった。

『関数の引数で与えられたものを関数内で変更しようとした。関数の引数はデフォルトで定数扱い。関数内で変数として使いたいなら関数の頭でvar a = aなどとして書き換え可能にする。』

とのこと
change関数を記述しているが、そのchange関数の引数であるcという配列はletという変更できない定数として扱われるのでc[x] = bやc[y] = aというような定数に値を代入して変更させるようなことをしてはいけないのだろう

fun changeの中にforの繰り返しの処理を入れるのではなく、funcにわざわざしないで、直接ボタンを押した時にforを行うようにするとエラーが消えた

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1