Create Objects/Instances in Variables Swift

create objects/instances in variables swift

You can do that with a classic loop:

let input = [("Ann", 1), ("Bob", 2)]

var guests: [Guest] = []
for each in input {
guests.append(Guest(name: each.0, age: each.1))
}

However, it can be done more concisely (and with avoidance of var) using functional techniques:

let guests = [("Ann", 1), ("Bob", 2)].map { Guest(name: $0.0, age: $0.1) }

EDIT: Dictionary-based solution (Swift 4; for Swift 3 version just use the classic loop)

let input = [("Ann", 1), ("Bob", 2)]
let guests = Dictionary(uniqueKeysWithValues: input.map {
($0.0, Guest(name: $0.0, age: $0.1))
})

Or, if it's possible for two guests to have the same name:

let guests = Dictionary(input.map { ($0.0, Guest(name: $0.0, age: $0.1)) }) { first, second in
// put code here to choose which of two conflicting guests to return
return first
}

With the dictionary, you can just do:

if let annsAge = guests["Ann"]?.age {
// do something with the value
}

Swift - How to create an instance of an object whose variables are data from Parse?

Asynch methods with completion blocks are tricky, because the code doesn't execute in the order you find it in the source file...

// edit - outside of this method, in the containing class:
var question: QuestionModel

query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
self.question.options = // ...
// use objects here, e.g. what your posted code does
// update your UI with objects here, because they are valid here
println("this runs SECOND")
// no matter what you assign in here...
}

// ...it won't be accessible here, because this code runs *before* the code
// in the block
println("this runs FIRST")

How to create an array of classes and instance objects with it in Swift?

All you need is a required init, some way to create an instance that will be shared between all Types you want this to work for. A protocol that holds an init method will do fine.

Obviously this works simplest when the init does not require parameters.

Downside is that you do need to downcast the resulting instances.

protocol ZeroParamaterInit {
init()
}

class Base : ZeroParamaterInit {
func launch(code1: Int, code2: Int) { }
required init() {

}
}

class A: Base {}
class B: Base {}
class C: Base {}

let classes : [ZeroParamaterInit.Type] = [A.self,B.self]
var instances : [Any] = []

for cls in classes {

let instance = cls.init()
instances.append(instance)

}

for instance in instances {

if let test = instance as? A {
print("A")
}
if let test = instance as? B {
print("B")
}
if let test = instance as? C {
print("C")
}
}

Initialize class-instance and access variables in Swift

The syntax for a class declaration is:

class <class name>: <superclass>, <adopted protocols> {
<declarations>
}

Your declaration of ViewController includes rex.age = 2 which itself is not a declaration, it is a statement - specifically a binary expression with an infix operator.

best way to define instance variables in swift

What you show is not called class variable, it is called instance variable in Objective-C.

In order to create "instance" variable in Swift you can just declare variable like this:

let backLayer = CALayer()

However, I would recommend to add private in front of var or let, so it will not be accessed outside the class - same as instance variable in Objective-C:

private let backLayer = CALayer()
private var selectedRow: Int = 0

Computed class variable can be defined like this:

class var pi: Double { return 3.14 }

I would recommend to use class vars only if you want to override it in a subclass, otherwise you can use:

static let pi = 3.14

iOS: create an object class with Swift

This is not actually an answer (see other answers for a solution, such as @Greg's and @zelib's), but an attempt to fix some mistakes I see in your code

  1. No need to create computed + stored property (unless you have a reason for that):

    class City: NSObject {
    var name: String = ""
    }
  2. If you inherit from NSObject, you automatically lose all swift features - avoid it (unless you have a reason for that)

    class City {
    var name: String = ""
    }
  3. You are using an empty string as absence of value - swift provides optionals for that

    class City {
    var name: String?
    }
  4. Alternative to 3., a city without a name wouldn't make much sense, so you probably want each instance to have a name. Use non optional property and an initializer:

    class City {
    var name: String
    init(name: String) {
    self.name = name
    }
    }
  5. Avoid implicitly unwrapped optionals (unless you have a reason for that):

    var city: City

How to create an instance of an object in SwiftUI without duplication?

I've found the solution to this.

Here's the project repo that represents the bug with Object duplication and the version that fix this. I'm still have no idea how objects have been duplicate in that case. But I figured out why. It happens because this line:

@Environment(\.myObjectsStore.objects) var myObjectsStores: MyObjectsStore

I've used @Environment(\.key) to connect my model to each view in the navigation stack including Modal one, which are unavailable by the other ways provided in SwiftUI, e.g.: @State, @ObjectBinding, @EnvironmentObject. And for some reason @Environment(\.key) wrapper produce these duplications.

So I'd simply replace all variables from @Environment(\.) to @ObjectBinding and now almost everything works well.

Note: The code is in the rep is still creates one additional object by each workflow walkthrough. So it creates two objects totally instead of one. This behavior could be fixed by way provided in this answer.



Related Topics



Leave a reply



Submit