Swift and mutating struct

后端 未结 8 1739
鱼传尺愫
鱼传尺愫 2020-12-04 06:54

There is something that I don\'t entirely understand when it comes to mutating value types in Swift.

As the \"The Swift Programming Language\" iBook states:

8条回答
  •  星月不相逢
    2020-12-04 07:27

    Swift structs can be instantiated as either constants (via let) or variables (via var)

    Consider Swift's Array struct (yes it's a struct).

    var petNames: [String] = ["Ruff", "Garfield", "Nemo"]
    petNames.append("Harvey") // ["Ruff", "Garfield", "Nemo", "Harvey"]
    
    let planetNames: [String] = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
    planetNames.append("Pluto") //Error, sorry Pluto. No can do
    

    Why didn't the append work with the planet names? Because append is marked with the mutating keyword. And since planetNames was declared using let, all methods thus marked are off limits.

    In your example the compiler can tell you're modifying the struct by assigning to one or more of its properties outside of an init. If you change your code a bit you'll see that x and y aren't always accessible outside the struct. Notice the let on the first line.

    let p = Point(x: 1, y: 2)
    p.x = 3 //error
    p.moveToX(5, andY: 5) //error
    

提交回复
热议问题