简体   繁体   中英

Trying to declare an array of custom objects in swift

Here is my code

    var planetNames = ["mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune", "pluto"] //names of the planets

    for currentRing in 0..<orbitMarkers.count
    {
        var planetNames[currentRing] = planet(size: 1.2)

    }

and here is my class

class planet
{
   var size: CGFloat
   init(size: CGFloat)
   {
     self.size = size
   }
}

I am trying to figure out how I can make an array of 8 new "planet" objects

you can do it like this:

class planet
{
    var name: String
    var size: CGFloat
    init(name: String, size: CGFloat)
    {
        self.size = size
        self.name = name
    }
}

var planets: [planet] = []
var mercury = planet(name: "Mercury", size: 20)
planets.append(mercury)

I added a name variable for your planet class, and then the array initialization is var planets: [planet] and as an example I have appended one planet for you to see how its done.

It looks like you already have an array of orbit markers.. do you have an array of sizes?

Also, name your class with UpperCamelCase

class Planet {
    let name: String
    let size: CGFloat
}

let sizes: CGFloat = [1,2,3,....] // planet sizes
let names = ["mercury", "x", ...] // planet names

let planets = zip(names, sizes).map{Planet(name: $0, size: $1)}

Also.. size is a little bit nondescript. Consider changing it to radius, volume, diameter or whatever the value actually represents.

Quick explanation - zip combines two arrays of equal sizes into one array of tuples, attaching elements pairwise into a tuple. Element 1 from array 1 is paired with element 1 from array 2, etc.

Map performs an operation on every tuple in the array of tuples that resulted from the zipping, return a Planet object for each tuple.

Custom class array example swift 3.0

class Planet {
    var name: String!
    var size: CGFloat!

    init(name:String,size:CGFloat) {
        self.name = name
        self.size = size
    }
}

var planets = [Planet]()
let planet = Planet(name: "Earth", size: 1.2)
planets.append(planet)

for Planet in planets {
    print(Planet.name)
}

This is how you would do it in Swift 3

var planets = [planet]() // Initialize an array of type planet
var mercury = planet()   // Initialize an instance of type planet
mercury.size =           // set size on mercury
planets.append(mercury)  // Add mercury to the array planets

This is untested, but those are some basic statements working with an array of a custom type.

EDIT: I just noticed you have an initializer set up which means you could make a planet like this.

var earth = planet(size: earthSizeHere) // Use initializer
planets.append(earth)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM