How to assign a value to optional property of class - swift

I've tried a bunch of different ways to assign a value to stepperValue to no avail. I get my Offence model filled through Firebase and I simply want to "assign" a stepper value to each offences so that I can make calculations i.e points X stepperValue .
Model swift file:
class Offence : Comparable {
var section: String
var name: String
var cost: Int
var points: Int
var stepperValue: Double?
init(section: String, name: String, cost: Int, points: Int) {
self.section = section
self.name = name
self.cost = cost
self.points = points
}
class Variables {
static var selectedOffencesArray: [Offence] = [Offence]()
}
This one is in its own TableViewCell class in its own swift file
#IBAction func stepperValueChanged(_ sender: Any) {
for offence in Variables.selectedOffencesArray {
offence.stepperValue! = 3.0
}

The following just work
for offence in Variables.selectedOffencesArray {
offence.stepperValue = 3.0 // << no force (!) needed
}

Related

How to save and load GKGameModelPlayer from Realm in Swift?

I am attempting to implement a GKGameModel in my application. In it, it holds variables to a few things, but for the purposes of my question I'm interested in the following two variables:
import GameplayKit
final class GameModel: NSObject, GKGameModel {
var players: [GKGameModelPlayer]?
var activePlayer: GKGameModelPlayer?
}
I do something like this to initialise the game with 3 players (not exact)
let game = GameModel.init()
game.players = [Player(),Player(),Player()] // Create 3 players
guard let firstPlayer = game.players.first else {
return
}
game.activePlayer = firstPlayer
A player class is defined as:
class Player : NSObject, GKGameModelPlayer {
var playerId: Int // GKGameModelPlayer protocol variable
let name: String
var cash: Int = 0
}
In my project I have Realm Entities and the models seperated. So there will be a PlayerEntity and a Player class.
I'm wanting to use RealmSwift to save and load the GKGameModelPlayer data, and more specifically the ability to store/re-store the active player.
I think the key here is the playerId variable; but I am not sure.
But what I'm not sure about is retrieving this information and then re-mapping it into a valid GKGameModelPlayer format
My current idea/theory is that I need to map my model to an entity class and vice-versa.
Ie:
// [REALM] Player entity
class PlayerEntity: Object {
#objc dynamic var id = UUID().uuidString
#objc dynamic var playerId: Int = 0
#objc dynamic var name: String = ""
#objc dynamic var cash: Int = 0
override static func primaryKey() -> String {
return "id"
}
}
And then I extend this class to do some "mapping":
extension PlayerEntity {
// Map model -> entity
convenience init(model: Player) {
self.init()
self.playerId = model.playerId
self.name = model.name
self.cash = model.cash
}
}
extension Player {
// Map entity -> model
convenience init(entity: PlayerEntity) {
let playerId = entity.playerId
let name = entity.name
let cash = entity.cash
self.init(id: playerId, name: name, cash: cash)
}
}
Right now, the playerId is always zero (0) because I'm not really sure how to set it.
I can save a player to realm.
The issue comes from when I try to restore the player, and I want to restore the activePlayer variable in the GameModel
Therefore, my question is:
How would I go about saving and restoring the activePlayer variable so that it continues to comply to GKGameModelPlayer?
I appreciate any assistance on this.
With thanks
While you could use those extensions, sometimes simpler is better. Here's a rough example:
class PlayerEntity: Object {
#objc dynamic var playerId: Int = 0
#objc dynamic var name: String = ""
#objc dynamic var cash: Int = 0
convenience init(withPlayer: PlayerClass) {
self.init()
self.playerId = withPlayer.playerId
self.name = withPlayer.name
self.cash = withPlayer.cash
}
func getPlayer() -> Player {
let p = Player()
p.playerId = self.playerId
p.name = self.name
p.cash = self.cash
return p
}
override static func primaryKey() -> String {
return "playerId"
}
}
to load all the players into an array... this will do it
let playerResults = realm.objects(PlayerEntity.self)
for player in playerResults {
let aPlayer = player.getPlayer()
self.playerArray.append(aPlayer)
}
Notice the removal of
#objc dynamic var id = UUID().uuidString
because it's not really being used to identify the object as a primary key.
The primary key is really
var playerId: Int // GKGameModelPlayer protocol variable
which is fine to use as long as it's unique.

Swift: The proper way to initialize model class with a lot of properties

How do you initialize your classes/structs with a lot of properties?
This question could probably be asked without Swift context but Swift brings a flavour to it, so I add Swift tag in headline and tags.
Let's say you have a User class with 20 properties. Most of them should not be nil or empty. Let's assume these properties are not interdependent. Let's assume that 33% of it should be constant (let) by the logic of the class. Let's assume that at least 65% of them do not have meaningful default values. How would you design this class and initialize an instance of it?
So far I have few thoughts but none of it seems to be completely satisfactory to me:
put all of the properties linearly in the class and make huge init method:
class User {
// there is 20 properties like that
let id : String
let username : String
let email : String
...
var lastLoginDate : Date
var lastPlayDate : Date
// then HUUUUGE init
init(id: String,
username: String,
...
lastPlayDate: Date) {
}
}
try to group properties into sub types and deal with smaller inits separately
class User {
struct ID {
let id : String
let username : String
let email : String
}
struct Activity {
var lastLoginDate : Date
var lastPlayDate : Date
}
let id : ID
...
var lastActivity : Activity
// then not so huge init
init(id: ID,
...
lastActivity: Activity) {
}
}
another solution is to break requirements a bit: either declare some of the properties optional and set values after init or declare dummy default values and set normal values after init, which conceptually seems to be the same
class User {
// there is 20 properties like that
let id : String
let username : String
let email : String
...
var lastLoginDate : Date?
var lastPlayDate : Date?
// then not so huge init
init(id: String,
username: String,
email: String) {
}
}
// In other code
var user = User(id: "1", username: "user", email: "user#example.com"
user.lastLoginDate = Date()
Is there a nice paradigm/pattern how to deal with such situations?
You can try the builder pattern.
Example
class DeathStarBuilder {
var x: Double?
var y: Double?
var z: Double?
typealias BuilderClosure = (DeathStarBuilder) -> ()
init(buildClosure: BuilderClosure) {
buildClosure(self)
}
}
struct DeathStar : CustomStringConvertible {
let x: Double
let y: Double
let z: Double
init?(builder: DeathStarBuilder) {
if let x = builder.x, let y = builder.y, let z = builder.z {
self.x = x
self.y = y
self.z = z
} else {
return nil
}
}
var description:String {
return "Death Star at (x:\(x) y:\(y) z:\(z))"
}
}
let empire = DeathStarBuilder { builder in
builder.x = 0.1
builder.y = 0.2
builder.z = 0.3
}
let deathStar = DeathStar(builder:empire)
Example taken from here: https://github.com/ochococo/Design-Patterns-In-Swift
If you are looking for a bit more Java like solution, you can try something like this.
Alternative Example
final class NutritionFacts {
private let servingSize: Int
private let servings: Int
private let calories: Int
private let fat: Int
private let sodium: Int
private let carbs: Int
init(builder: Builder) {
servingSize = builder.servingSize
servings = builder.servings
calories = builder.calories
fat = builder.fat
sodium = builder.sodium
carbs = builder.carbs
}
class Builder {
let servingSize: Int
let servings: Int
private(set) var calories = 0
private(set) var fat = 0
private(set) var carbs = 0
private(set) var sodium = 0
init(servingSize: Int, servings: Int) {
self.servingSize = servingSize
self.servings = servings
}
func calories(value: Int) -> Builder {
calories = value
return self
}
func fat(value: Int) -> Builder {
fat = value
return self
}
func carbs(value: Int) -> Builder {
carbs = value
return self
}
func sodium(value: Int) -> Builder {
sodium = value
return self
}
func build() -> NutritionFacts {
return NutritionFacts(builder: self)
}
}
}
let facts = NutritionFacts.Builder(servingSize: 10, servings: 1)
.calories(value: 20)
.carbs(value: 2)
.fat(value: 5)
.build()
Example taken from: http://ctarda.com/2017/09/elegant-swift-default-parameters-vs-the-builder-pattern

Swift protocol property set not executed

I try to use the set method for calling a function after the value is changed.
I did not see why the set method is not called.
The code could be directly executed in playground
//: Playground - noun: a place where people can play
import UIKit
protocol RandomItem {
var range : (Int,Int) {get set}
var result : Int {get set}
init()
mutating func createRandom()
}
extension RandomItem {
var range : (Int,Int) {
get {
return range
}
set {
range = newValue
self.createRandom()
}
}
}
struct Item: RandomItem {
var range = (0,1)
var result: Int = 0
init() {
self.createRandom()
}
mutating func createRandom() {
let low = UInt32(range.0)
let high = UInt32(range.1)
result = Int(arc4random_uniform(high - low + 1) + low)
}
}
Your struct Item declares its own range property, which overrides the default you created in the protocol extension. The range property in Item has no getters or setters defined to do what your extension version does.
Another issue:
Your protocol extension defines the range property as a computed property (no storage) whose getter and setter both call itself. This will loop infinitely.
Maybe you are looking for something more like:
protocol RandomItem {
var storedRange: (Int, Int) { get }
var range : (Int,Int) {get set}
var result : Int {get set}
init()
mutating func createRandom()
}
extension RandomItem {
var range : (Int,Int) {
get {
return storedRange
}
set {
storedRange = newValue
self.createRandom()
}
}
}
struct Item: RandomItem {
var result: Int = 0
var storedRange = (0, 1)
init() {
self.createRandom()
}
mutating func createRandom() {
let low = UInt32(range.0)
let high = UInt32(range.1)
result = Int(arc4random_uniform(high - low + 1) + low)
}
}
This requires a conforming type to define a stored property storedRange, which the default implementation of the computed property range will interact with.

Maintain value semantics in Swift struct, which contains object reference

I have a Swift struct which contains an object for internal storage. How can I make sure the struct has value semantics?
public struct Times {
private let times = NSMutableIndexSet()
mutating func addTimeRange(openTime: Int, closeTime: Int) {
self.times.addIndexesInRange(NSRange(location: openTime, length: closeTime - openTime))
}
}
Swift 3 Update
Swift 3 includes value types for many types from the Foundation framework. There is now an IndexSet struct, which bridges to NSIndexSet. The internal implementation is similar to the Swift 2 solution below.
For more information on the new Foundation value types see: https://github.com/apple/swift-evolution/blob/master/proposals/0069-swift-mutability-for-foundation.md
Old approach in Swift 2
The copy-on-write approach is the right solution. However, it is not necessary to create a copy of the NSMutableIndexSet, if only one struct instance references it. Swift provides a global function called isUniquelyReferencedNonObjC() to determine if a pure Swift object is only referenced once.
Since we cannot use this function with Objective-C classes, we need to wrap NSMutableIndexSet in a Swift class.
public struct Times {
private final class MutableIndexSetWrapper {
private let mutableIndexSet: NSMutableIndexSet
init(indexSet: NSMutableIndexSet) {
self.mutableIndexSet = indexSet
}
init() {
self.mutableIndexSet = NSMutableIndexSet()
}
}
private let times = MutableIndexSetWrapper()
mutating func addTimeRange(openTime: Int, closeTime: Int) {
// Make sure our index set is only referenced by this struct instance
if !isUniquelyReferencedNonObjC(&self.times) {
self.times = MutableIndexSetWrapper(indexSet: NSMutableIndexSet(indexSet: self.times.mutableIndexSet))
}
let range = NSRange(location: openTime, length: closeTime - openTime)
self.times.mutableIndexSet.addIndexesInRange(range)
}
}
Store an NSIndexSet instead of an NSMutableIndexSet. That is exactly why the immutable superclass exists.
public struct Times {
private var times = NSIndexSet()
mutating func addTimeRange(openTime: Int, closeTime: Int) {
let t = NSMutableIndexSet(indexSet:self.times)
t.addIndexesInRange(NSRange(location: openTime, length: closeTime - openTime))
self.times = NSIndexSet(indexSet:t)
}
}
If this were a class instead of a struct, you could cause the last step to be performed automatically by declaring times as #NSCopying and then just using simple assignment:
public class Times {
#NSCopying private var times = NSIndexSet()
func addTimeRange(openTime: Int, closeTime: Int) {
let t = NSMutableIndexSet(indexSet:self.times)
t.addIndexesInRange(NSRange(location: openTime, length: closeTime - openTime))
self.times = t // ensure immutable copy
}
}
It might be an option to use Swift's native Set type which has value-semantics built in since it is a struct itself.
public struct Times {
private var times = Set<Int>()
mutating func addTimeRange(openTime: Int, closeTime: Int) {
(openTime ..< closeTime).map({ index -> Void in self.times.insert(index) })
}
}
let t1 = Times()
var t2 = t1
t2.addTimeRange(0, closeTime: 3)
println(t1.times) // []
println(t2.times) // [2, 0, 1]

Change the value that is being set in variable's willSet block

I'm trying to sort the array that is being set before setting it but the argument of willSet is immutable and sort mutates the value. How can I overcome this limit?
var files:[File]! = [File]() {
willSet(newFiles) {
newFiles.sort { (a:File, b:File) -> Bool in
return a.created_at > b.created_at
}
}
}
To put this question out of my own project context, I made this gist:
class Person {
var name:String!
var age:Int!
init(name:String, age:Int) {
self.name = name
self.age = age
}
}
let scott = Person(name: "Scott", age: 28)
let will = Person(name: "Will", age: 27)
let john = Person(name: "John", age: 32)
let noah = Person(name: "Noah", age: 15)
var sample = [scott,will,john,noah]
var people:[Person] = [Person]() {
willSet(newPeople) {
newPeople.sort({ (a:Person, b:Person) -> Bool in
return a.age > b.age
})
}
}
people = sample
people[0]
I get the error stating that newPeople is not mutable and sort is trying to mutate it.
It's not possible to mutate the value inside willSet. If you implement a willSet observer, it is passed the new property value as a constant parameter.
What about modifying it to use didSet?
var people:[Person] = [Person]()
{
didSet
{
people.sort({ (a:Person, b:Person) -> Bool in
return a.age > b.age
})
}
}
willSet is called just before the value is stored.
didSet is called immediately after the new value is stored.
You can read more about property observers here
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html
You can also write a custom getter and setter like below. But didSet seems more convenient.
var _people = [Person]()
var people: [Person] {
get {
return _people
}
set(newPeople) {
_people = newPeople.sorted({ (a:Person, b:Person) -> Bool in
return a.age > b.age
})
}
}
It is not possible to change value types (including arrays) before they are set inside of willSet. You will need to instead use a computed property and backing storage like so:
var _people = [Person]()
var people: [Person] {
get {
return _people
}
set(newPeople) {
_people = newPeople.sorted { $0.age > $1.age }
}
}
Another solution for people who like abstracting away behavior like this (especially those who are used to features like C#'s custom attributes) is to use a Property Wrapper, available since Swift 5.1 (Xcode 11.0).
First, create a new property wrapper struct that can sort Comparable elements:
#propertyWrapper
public struct Sorting<V : MutableCollection & RandomAccessCollection>
where V.Element : Comparable
{
var value: V
public init(wrappedValue: V) {
value = wrappedValue
value.sort()
}
public var wrappedValue: V {
get { value }
set {
value = newValue
value.sort()
}
}
}
and then assuming you implement Comparable-conformance for Person:
extension Person : Comparable {
static func < (lhs: Person, rhs: Person) -> Bool {
lhs.age < lhs.age
}
static func == (lhs: Person, rhs: Person) -> Bool {
lhs.age == lhs.age
}
}
you can declare your property like this and it will be auto-sorted on init or set:
struct SomeStructOrClass
{
#Sorting var people: [Person]
}
// … (given `someStructOrClass` is an instance of `SomeStructOrClass`)
someStructOrClass.people = sample
let oldestPerson = someStructOrClass.people.last
Caveat: Property wrappers are not allowed (as of time of writing, Swift 5.7.1) in top-level code— they need to be applied to a property var in a struct, class, or enum.
To more literally follow your sample code, you could easily also create a ReverseSorting property wrapper:
#propertyWrapper
public struct ReverseSorting<V : MutableCollection & RandomAccessCollection & BidirectionalCollection>
where V.Element : Comparable
{
// Implementation is almost the same, except you'll want to also call `value.reverse()`:
// value = …
// value.sort()
// value.reverse()
}
and then the oldest person will be at the first element:
// …
#Sorting var people: [Person]
// …
someStructOrClass.people = sample
let oldestPerson = someStructOrClass.people[0]
And even more directly, if your use-case demands using a comparison closure via sort(by:…) instead of implementing Comparable conformance, you can do that to:
#propertyWrapper
public struct SortingBy<V : MutableCollection & RandomAccessCollection>
{
var value: V
private var _areInIncreasingOrder: (V.Element, V.Element) -> Bool
public init(wrappedValue: V, by areInIncreasingOrder: #escaping (V.Element, V.Element) -> Bool) {
_areInIncreasingOrder = areInIncreasingOrder
value = wrappedValue
value.sort(by: _areInIncreasingOrder)
}
public var wrappedValue: V {
get { value }
set {
value = newValue
value.sort(by: _areInIncreasingOrder)
}
}
}
// …
#SortingBy(by: { a, b in a.age > b.age }) var people: [Person] = []
// …
someStructOrClass.people = sample
let oldestPerson = someStructOrClass.people[0]
Caveat: The way SortingBy's init currently works, you'll need to specify an initial value ([]). You can remove this requirement with an additional init (see Swift docs), but that approach is much less complicated when your property wrapper works on a concrete type (e.g. if you wrote a non-generic PersonArraySortingBy property wrapper), as opposed to a generic-on-protocols property wrapper.