Swift Pass Variable to Reference - swift

In C++ you can do
int x = 5;
int &y = x;
So both x and y point to the same place. Can I do this in Swift?
I'm programming a class with some functionality, and another class which is basically a driver.
class Driver {
var otherClass: OtherClass
var referenceVariable: Int = otherClass.referenceVariable // how to make a reference here
...
}
Or is there a better / more semantically correct way to do this in Swift?

You could use a computed property for this functionality:
class Driver {
var otherClass: OtherClass
var referenceVariable: Int {
get { otherClass.referenceVariable }
set { otherClass.referenceVariable = newValue }
}
...
}
A computed property doesn't store a value itself. It provides closures for reading and writing the property. In this case, we're operating on the value stored in the otherClass.

Int is a struct in Swift. Structs in Swift are first citizen. Basically
structs are value types. Values types usually are copied on assigning.
If you want to use reference type, just use classes.
One of the basic solution for your task is to wrap Int value in a class
final class IntWrapper {
let value: Int
init(value: Int) {
self.value = value
}
}
Now, changing referenceVariable: IntWrapper will change all references to it
class Driver {
var otherClass: OtherClass
var referenceVariable: IntWrapper = otherClass.referenceVariable // how to make a reference here
...
}
If you want to get pointer on your class IntWrapper you can create it this way.
var pointer = UnsafePointer(&i)
But, I suppose, you aren't gonna need it

Related

How to define variable that can be set and get in extension of protocol

I come from Java world. Now I am programming in Swift 4.
I would like to implement abstract class in Swift, I know in Swift there is no such concept of abstract class. But I know we could mimic this concept in Swift by using protocol. For example this is what I tried:
// With protocol, I can define functions that concrete class have to implement
protocol ProductProvider {
func getProductNumber() -> Int
}
// with protocol extension, I can define shared (computed) properties and functions among concrete classes that comply with this protocol
extension ProductProvider {
var maxProductCount: Int {
return 10
}
}
But now, I would like to have a shared variable that could be set & get ("shared" means to be shared with classes that comply with this protocol):
extension ProductProvider {
var maxProductCount: Int {
set(newValue) {
// set to what if I couldn't define private stored variable in extension to hold the most recent set value ?
}
get{
// how to return the most recent value set?
}
}
}
My question is in the comment of above code. How can I do that set and get for a variable in extension of protocol in Swift 4? If it is impossible, what are the workarounds possible?
The simplest way i think is define the variable in the protocol with the getter and setter. Then in your conform object you should declare the variable to conformance.
An Example:
protocol AbstractObject {
var maxProductCount: Int { get set }
}
struct ConformObject: AbstractObject {
var maxProductCount: Int
}
So now you can use your variable in your default implementations
extension AbstractObject {
mutating func addOne() -> Int {
self.maxProductCount += 1
return self.maxProductCount
}
}
Aside from the discussion if its a right way to achieve what you want, you can use object association.
public final class ObjectAssociation<T: AnyObject> {
private let policy: objc_AssociationPolicy
/// - Parameter policy: An association policy that will be used when linking objects.
public init(policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) {
self.policy = policy
}
/// Accesses associated object.
/// - Parameter index: An object whose associated object is to be accessed.
public subscript(index: AnyObject) -> T? {
get { return objc_getAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque()) as! T? }
set { objc_setAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque(), newValue, policy) }
}
}
And in your extension
extension SomeType {
private static let association = ObjectAssociation<NSObject>()
var simulatedProperty: NSObject? {
get { return SomeType.association[self] }
set { SomeType.association[self] = newValue }
}
}
It is not possible to store Swift types via object association directly. You can store e.g. NSNumber instead of Int.
Source: https://stackoverflow.com/a/43056053/1811810

Cannot create class object or array of class objects

I'm working on a project thatand am simply trying to create a object instance of a simple custom class:
import Foundation
class Set {
private var gam1: Int!
private var gam2: Int!
init (gam1: Int, gam2: Int) {
self.gam1 = gam1
self.gam2 = gam2
}
//returns set info as array
func getStats () -> [Int] {
let arr = [gam1!, gam2!]
return arr
}
}
The class simply stores a few variables for use later and I want an array of such objects to store several values. However, when I try to create a n instance of the class in a different class I get errors:
import Foundation
class AnotherClass {
var mySet = Set(gam1: 6, gam2: 5) //error 1
//array of set objects
var setArray = [Set]() // error 2
//returns array of set objects
func getSets () -> [Set] { //error 3
return setArray
}
}
The errors state:
Cannot find an initializer for type 'Set' that accepts an argument list of type '(gam1: Int, gam2: Int)'
Cannot invoke initializer for type '[Set]' with no arguments
and
Reference to generic type 'Set' requires arguments in <...>
Any ideas of what the issue is here? could the 'Set' name of the class be conflicting with a reserved keyword?
Many thanks,
Kw
The issue that you are having is due to the naming conflict between Set in the Swift standard library and the one you defined.
This is never a good idea. Instead, give it a more descriptive name (and one that doesn't conflict with anything else). For instance, call it gamHolder and initialize it gamHolder(gam1: <an int>, gam2: <another int>).
Also, if you have defined variables inside the init function they do not need to be forced unwrapped optionals.
For example:
class myClass {
var myInt: Int
init(anInt: Int) {
myInt = anInt
}
}
You defined 2 parameters in your init method (since gam1 and gam2 are not optional). So, you have 2 solutions:
1 - You add parameters into your init call (like this):
var mySet = Set(gam1: 1, gam2: 2)
2 - You change gam1 and gam2 to optionals and you add a zero parameters init:
class Set {
private var gam1: Int?
private var gam2: Int?
init() {
}
init(gam1: Int, gam2: Int) {
self.gam1 = gam1
self.gam2 = gam2
}
// returns set info as array
func getStats() -> [Int] {
let arr = [gam1!, gam2!]
return arr
}
}
So, you will be able to call it like this: var mySet = Set()
Also: be careful: Set is a class used in the Swift standard library. It's never a good idea to use same class names than Swift Standard Library. A name like TenisSet would be better.
Edit:
Here is a final working example with a renamed class:
class TenisSet {
private var gam1: Int?
private var gam2: Int?
init() {
}
init(gam1: Int, gam2: Int) {
self.gam1 = gam1
self.gam2 = gam2
}
// returns set info as array
func getStats() -> [Int] {
let arr = [gam1!, gam2!]
return arr
}
}
class AnotherClass {
var mySet = TenisSet()
// array of set objects
var setArray = [TenisSet]()
// returns array of set objects
func getSets() -> [TenisSet] {
return setArray
}
}

How to access static variables in methods using Swift's 'abstract class'-like protocol extensions

I've been trying to make abstract superclass-like behaviour in Swift using the protocols and extensions suggested here: Abstract classes in Swift Language
But I can't figure out how to write methods that make use of static (class) variables. For example, if I want to get the perimeter of an abstract shape class:
protocol Shape {
static var numSides: Int {get}
var sideLength: Double {get}
}
class Triangle: Shape {
static var numSides: Int = 3
var sideLength: Double
init (sideLength: Double) { self.sideLength = sideLength }
}
class Square: Shape {
static var numSides: Int = 4
var sideLength: Double
init (sideLength: Double) { self.sideLength = sideLength }
}
extension Shape {
func calcPerimeter() -> Double {
return sideLength * Double(numSides)
}
}
Swift doesn't want me to use static var numSides in the calcPerimeter method. I know that if I made it an instance variable the code would run, but this doesn't seem like the right way to go. What is the best way to do this?
You should use numSide as a static variable not instance one.
You cannot call Shape.numSides but you can use Self keyword which reference to the concrete class.
Try this:
Self.numSides

Instance member cannot be used on type

I have the following class:
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }
}
Compilation fails with the message:
Instance member 'categoriesPerPage' cannot be used on type
'ReportView'
What does this mean?
Sometimes Xcode when overrides methods adds class func instead of just func. Then in static method you can't see instance properties. It is very easy to overlook it. That was my case.
You just have syntax error when saying = {return self.someValue}. The = isn't needed.
Use :
var numPages: Int {
get{
return categoriesPerPage.count
}
}
if you want get only you can write
var numPages: Int {
return categoriesPerPage.count
}
with the first way you can also add observers as set willSet & didSet
var numPages: Int {
get{
return categoriesPerPage.count
}
set(v){
self.categoriesPerPage = v
}
}
allowing to use = operator as a setter
myObject.numPages = 5
For anyone else who stumbles on this make sure you're not attempting to modify the class rather than the instance! (unless you've declared the variable as static)
eg.
MyClass.variable = 'Foo' // WRONG! - Instance member 'variable' cannot be used on type 'MyClass'
instanceOfMyClass.variable = 'Foo' // Right!
It is saying you have an instance variable (the var is only visible/accessible when you have an instance of that class) and you are trying to use it in the context of a static scope (class method).
You can make your instance variable a class variable by adding static/class attribute.
You instantiate an instance of your class and call the instance method on that variable.
Another example is, you have class like :
#obc class Album: NSObject {
let name:String
let singer:Singer
let artwork:URL
let playingSong:Song
// ...
class func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
// ...
return playingSong.lyric
}
}
you will also get the same type of error like :
instance member x cannot be used on type x.
It's because you assign your method with "class" keyword (which makes your method a type method) and using like :
Album.getCurrentlyPlayingSongLyric(duration: 5)
but who set the playingSong variable before? Ok. You shouldn't use class keyword for that case :
// ...
func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
// ...
return playingSong.lyric
}
// ...
Now you're free to go.
Your initial problem was:
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }
}
Instance member 'categoriesPerPage' cannot be used on type 'ReportView'
previous posts correctly point out, if you want a computed property, the = sign is errant.
Additional possibility for error:
If your intent was to "Setting a Default Property Value with a Closure or Function", you need only slightly change it as well. (Note: this example was obviously not intended to do that)
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
var numPages: Int = { return categoriesPerPage.count }()
}
Instead of removing the =, we add () to denote a default initialization closure. (This can be useful when initializing UI code, to keep it all in one place.)
However, the exact same error occurs:
Instance member 'categoriesPerPage' cannot be used on type 'ReportView'
The problem is trying to initialize one property with the value of another. One solution is to make the initializer lazy. It will not be executed until the value is accessed.
class ReportView: NSView {
var categoriesPerPage = [[Int]]()
lazy var numPages: Int = { return categoriesPerPage.count }()
}
now the compiler is happy!
I kept getting the same error inspite of making the variable static.
Solution: Clean Build, Clean Derived Data, Restart Xcode. Or shortcut
Cmd + Shift+Alt+K
UserNotificationCenterWrapper.delegate = self
public static var delegate: UNUserNotificationCenterDelegate? {
get {
return UNUserNotificationCenter.current().delegate
}
set {
UNUserNotificationCenter.current().delegate = newValue
}
}
Just in case someone really needs a closure like that, it can be done in the following way:
var categoriesPerPage = [[Int]]()
var numPagesClosure: ()->Int {
return {
return self.categoriesPerPage.count
}
}

What is analogue of Objective C static variable in Swift?

It was very convenient to have static variables in Objective C (static variable's value is maintained throughout all function/method calls), however I couldn't find anything like this in Swift.
Is there anything like this?
This is an example of static variable in C:
void func() {
static int x = 0;
/* x is initialized only once across four calls of func() and
the variable will get incremented four
times after these calls. The final value of x will be 4. */
x++;
printf("%d\n", x); // outputs the value of x
}
int main() { //int argc, char *argv[] inside the main is optional in the particular program
func(); // prints 1
func(); // prints 2
func(); // prints 3
func(); // prints 4
return 0;
}
After seeing your updated answer, here is the modification for your Objective-C code:
func staticFunc() {
struct myStruct {
static var x = 0
}
myStruct.x++
println("Static Value of x: \(myStruct.x)");
}
Call is anywhere in your class
staticFunc() //Static Value of x: 1
staticFunc() //Static Value of x: 2
staticFunc() //Static Value of x: 3
Declare the variable at the top level of a file (outside any classes) which is called global variable.
variables at the top level of a file are initialised lazily! So you
can set the default value for your variable to be the result of
reading the file, and the file won't actually be read until your code
first asks for the variable's value.
Reference from HERE.
UPDATE:
From your C example you can achieve same thing in swift this way:
var x = 0 //this is global variable
func staticVar() {
x++
println(x)
}
staticVar()
x //1
staticVar()
x //2
staticVar()
x //3
Tested with playground.
From Apple Document:
In C and Objective-C, you define static constants and variables
associated with a type as global static variables. In Swift, however,
type properties are written as part of the type’s definition, within
the type’s outer curly braces, and each type property is explicitly
scoped to the type it supports.
You define type properties with the static keyword. For computed type
properties for class types, you can use the class keyword instead to
allow subclasses to override the superclass’s implementation. The
example below shows the syntax for stored and computed type
properties:
struct SomeStructure {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
// return an Int value here
}
}
enum SomeEnumeration {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
// return an Int value here
}
}
class SomeClass {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
// return an Int value here
}
class var overrideableComputedTypeProperty: Int {
// return an Int value here
}
}
NOTE
The computed type property examples above are for read-only computed type >properties, but you can also define read-write computed
type properties with the same syntax as for computed instance
properties.