加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – 不可变值只有变异成员

发布时间:2020-12-14 05:50:25 所属栏目:百科 来源:网络整理
导读:我已经使用var声明了一个数组,并将其填充在一个init()中。然而,当我尝试改变该数组时,我发现一堆错误告诉我的数组是不可变的。我在这里缺少什么? struct Deck { var cards: Card[] = [] init () { for i in 1...4 { for ii in 1...13 { self.cards.appen
我已经使用var声明了一个数组,并将其填充在一个init()中。然而,当我尝试改变该数组时,我发现一堆错误告诉我的数组是不可变的。我在这里缺少什么?
struct Deck {
    var cards: Card[] = []

    init () {
        for i in 1...4 {
            for ii in 1...13 {
                self.cards.append(Card(rank: Rank.fromRaw(ii)!,suit: Suit.fromRaw(i)!))
            }
        }
    }

    func shuffle () {
        var shuffledDeck: Card[] = []
        var count = self.cards.count

        for i in 1...52 {
            var limit = count - i
            var key = Int(arc4random_uniform(UInt32(limit)));
            shuffledDeck.append(self.cards[key])
            self.cards.removeAtIndex(key)
        }

        self.cards = shuffledDeck
    }
}

我得到的错误:

Playground execution failed: error:
<REPL>:75:22: error: immutable value of type 'Card[]' only has mutating members named 'removeAtIndex'
            self.cards.removeAtIndex(key)
                 ^     ~~~~~~~~~~~~~
<REPL>:78:24: error: cannot assign to 'cards' in 'self'
            self.cards = shuffledDeck
一个struct被认为是一个值类型,所以默认情况下它是不可变的。如果要使用方法更改它,则必须声明方法变异。引用Swift书:

Structures and enumerations are value types. By default,the
properties of a value type cannot be modified from within its instance
methods.

However,if you need to modify the properties of your structure or
enumeration within a particular method,you can opt in to mutating
behavior for that method. The method can then mutate (that is,change)
its properties from within the method,and any changes that it makes
are written back to the original structure when the method ends. The
method can also assign a completely new instance to its implicit self
property,and this new instance will replace the existing one when the
method ends.

You can opt in to this behavior by placing the mutating keyword before
the func keyword for that method.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读