Simpler way to alias instance variables to other instance variables in Swift? - swift

Given the below struct in Swift, is there a more concise way to alias the instance variables x, y, and z to the properties of the three-tuple, _v?
Note: I realize that, of course, I could just declare these instance variables as Doubles and not need the tuple. However, the reason I'm doing it this way is so I can set three variables with a single-line statement like you will see in the init method and the below sample code.
Sample code with desired output of "1.0" "4.0":
var myVector = Vector3([1.0,2.0,3.0])
let x = myVector.x
print(x)
myVector.v = (4.0,5.0,6.0)
print(x)
The class:
struct Vector3 {
typealias V3 = (x:Double,y:Double,z:Double)
var v:V3 = (x:0.0,y:0.0,z:0.0)
var x:Double {
get {
return v.x
}
set(x) {
v.x = x
}
}
var y:Double {
get {
return v.y
}
set(y) {
v.y = y
}
}
var z:Double {
get {
return v.z
}
set(z) {
v.z = z
}
}
init(_ args:AnyObject...) {
if(args[0].isKindOfClass(NSArray)) {
v = (args[0][0].doubleValue,args[0][1].doubleValue,args[0][2].doubleValue)
}
else if(args.count == 3){
v = (args[0].doubleValue,args[1].doubleValue,args[2].doubleValue)
}
}
}
What I would like to be able to do is:
struct Vector3 {
typealias V3 = (x:Double,y:Double,z:Double)
var v:V3 = (x:0.0,y:0.0,z:0.0)
alias x = v.x
alias y = v.y
alias z = v.z
init(_ args:AnyObject...) {
if(args[0].isKindOfClass(NSArray)) {
v = (args[0][0].doubleValue,args[0][1].doubleValue,args[0][2].doubleValue)
}
else if(args.count == 3){
v = (args[0].doubleValue,args[1].doubleValue,args[2].doubleValue)
}
}
}
Of course that doesn't work. But is there another way to achieve the same thing?

Just do the opposite!
I realize that, of course, I could just declare these instance variables as Doubles and not need the tuple. However, the reason I'm doing it this way is so I can set three variables with a single-line statement like you will see in the init method and the below sample code.
If this is the reason then just do the opposite
struct Vector3 {
var x: Double
var y: Double
var z: Double
var coordinates: (Double, Double, Double) {
set { (x, y, z) = newValue }
get { return (x, y, z) }
}
}
Usage
var vector = Vector3(x: 1, y: 2, z: 3)
vector.x = 4
vector.coordinates // (4, 2, 3)
Final note
Your initializer could be improved in several ways.
Stop using NSArray, you are using Swift not Objective-C
Stop using isKindOfClass, use as? to perform a conditional cast
You have faith the objects inside the first array/s will have a doubleValue property. So I could easily crash your init passing something different right?
Now my question
What's wrong with the memberwise struct initializer?
It is automatically generated when you don't explicitly define an initializer for a struct, like in my previous code snipped.
Are you sure you want to define an initializer that literally accept any sort of objects an will crash with 99.99% of the combinations of values someone can pass to it?

Related

Is it possible to set a variable via its own setter method? [duplicate]

With this simple class I am getting the compiler warning
Attempting to modify/access x within its own setter/getter
and when I use it like this:
var p: point = Point()
p.x = 12
I get an EXC_BAD_ACCESS. How can I do this without explicit backing ivars?
class Point {
var x: Int {
set {
x = newValue * 2 //Error
}
get {
return x / 2 //Error
}
}
// ...
}
Setters and Getters apply to computed properties; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x to be assigned.
Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need something to backup the computed property. Try this:
class Point {
private var _x: Int = 0 // _x -> backingX
var x: Int {
set { _x = 2 * newValue }
get { return _x / 2 }
}
}
Specifically, in the Swift REPL:
15> var pt = Point()
pt: Point = {
_x = 0
}
16> pt.x = 10
17> pt
$R3: Point = {
_x = 20
}
18> pt.x
$R4: Int = 10
You can customize the set value using property observer. To do this use 'didSet' instead of 'set'.
class Point {
var x: Int {
didSet {
x = x * 2
}
}
...
As for getter ...
class Point {
var doubleX: Int {
get {
return x / 2
}
}
...
Setters/getters in Swift are quite different than ObjC. The property becomes a computed property which means it does not have a backing variable such as _x as it would in ObjC.
In the solution code below you can see the xTimesTwo does not store anything, but simply computes the result from x.
See Official docs on computed properties.
The functionality you want might also be Property Observers.
What you need is:
var x: Int
var xTimesTwo: Int {
set {
x = newValue / 2
}
get {
return x * 2
}
}
You can modify other properties within the setter/getters, which is what they are meant for.
To elaborate on GoZoner's answer:
Your real issue here is that you are recursively calling your getter.
var x:Int
{
set
{
x = newValue * 2 // This isn't a problem
}
get {
return x / 2 // Here is your real issue, you are recursively calling
// your x property's getter
}
}
Like the code comment suggests above, you are infinitely calling the x property's getter, which will continue to execute until you get a EXC_BAD_ACCESS code (you can see the spinner in the bottom right corner of your Xcode's playground environment).
Consider the example from the Swift documentation:
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
Notice how the center computed property never modifies or returns itself in the variable's declaration.
In order to override setter and getter for swift variables use the below given code
var temX : Int?
var x: Int?{
set(newX){
temX = newX
}
get{
return temX
}
}
We need to keep the value of variable in a temporary variable, since trying to access the same variable whose getter/setter is being overridden will result in infinite loops.
We can invoke the setter simply like this
x = 10
Getter will be invoked on firing below given line of code
var newVar = x
Update: Swift 4
In the below class setter and getter is applied to variable sideLength
class Triangle: {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) { //initializer method
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get { // getter
return 3.0 * sideLength
}
set(newValue) { //setter
sideLength = newValue / 4.0
}
}
Creating object
var triangle = Triangle(sideLength: 3.9, name: "a triangle")
Getter
print(triangle.perimeter) // invoking getter
Setter
triangle.perimeter = 9.9 // invoking setter
You are recursively defining x with x. As if someone asks you how old are you? And you answer "I am twice my age". Which is meaningless.
You must say I am twice John's age or any other variable but yourself.
computed variables are always dependent on another variable.
The rule of the thumb is never access the property itself from within the getter ie get. Because that would trigger another get which would trigger another . . . Don't even print it. Because printing also requires to 'get' the value before it can print it!
struct Person{
var name: String{
get{
print(name) // DON'T do this!!!!
return "as"
}
set{
}
}
}
let p1 = Person()
As that would give the following warning:
Attempting to access 'name' from within it's own getter.
The error looks vague like this:
As an alternative you might want to use didSet. With didSet you'll get a hold to the value that is was set before and just got set to. For more see this answer.
Try using this:
var x:Int!
var xTimesTwo:Int {
get {
return x * 2
}
set {
x = newValue / 2
}
}
This is basically Jack Wu's answer, but the difference is that in Jack Wu's answer his x variable is var x: Int, in mine, my x variable is like this: var x: Int!, so all I did was make it an optional type.
Setters and getters in Swift apply to computed properties/variables. These properties/variables are not actually stored in memory, but rather computed based on the value of stored properties/variables.
See Apple's Swift documentation on the subject: Swift Variable Declarations.
Here is a theoretical answer. That can be found here
A { get set } property cannot be a constant stored property. It should be a computed property and both get and set should be implemented.
Update for Swift 5.1
As of Swift 5.1 you can now get your variable without using get keyword. For example:
var helloWorld: String {
"Hello World"
}
I don't know if it is good practice but you can do something like this:
class test_ancestor {
var prop: Int = 0
}
class test: test_ancestor {
override var prop: Int {
get {
return super.prop // reaching ancestor prop
}
set {
super.prop = newValue * 2
}
}
}
var test_instance = test()
test_instance.prop = 10
print(test_instance.prop) // 20
Read more

An array of dictionaries with a tuple as the key and a bool as the value

I started this question for the purpose of asking it, but upon research I found an answer, so I compiled the answer here to share. Please let me know if it can be improved or if I have any errors.
I made an array of dictionaries where a 'tuple' (fake tuple, actually a class) is the key and a bool is the value.
I wanted something to this effect:
var dict = [(Int, Int): Bool]()
var pointDictionaryArray = [dict]()
of better compressed:
var pointDictionaryArray = [[(Int, Int): Bool]]()
However, upon research, I can't use a tuple as a key, because it's not hashable, but it seems that I can use a struct or class instead.
There is a very thorough answer given, but it was a bit confusing for me, so I'm sharing what I learned from it in a simplified manner for others.
// have an array of dictionaries with a tuple of the x,y being the key and a boolean being the value for each pixel array
class TupleClass: Hashable {
var x: Int!
var y: Int!
init(newX: Int, newY: Int) {
x = newX
y = newY
}
// required for the Hashable protocol
var hashValue: Int {
return x * y + y
}
}
// required function for the Equatable protocol, which Hashable inherits from
func ==(left: TupleStruct, right: TupleStruct) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
var pointDictionaryArray = [[TupleClass: Bool]]()
Assigning data example:
I'm using it to sort data from pixels similarly to this.
for i in 0..<image.count {
...
for j in 0..<imageWidth {
for k in 0..<imageHeight {
...
tempTuple = TupleClass(j, k)
...
if (/*pixel is white */) {
(pointDictionaryArray[i])[tempTuple] = true
} else {
(pointDictionaryArray[i])[tempTuple] = false
}
...
}
}
...
}
Retrieving data example:
for var i = 0; i < pointDictionaryArray.count; i++ {
for var j = 0; j < imageWidth; j++ {
for var k = 0; k < imageHeight; k++ {
let tempTuple = TupleClass(newX: j, newY: k)
// check to see if there is a key-value pair for the tempTuple used
if let temp = pointDictionaryArray[i][tempTuple] {
if temp {
print("true")
} else {
print("false")
}
}
}
}
}
Again, if I made any errors or if there are improvements to be made, let me know in the comments and I'll do my best to fix it.

Is it possible to create a "Positive Number" type in Swift?

Sorry if this is a stupid question but I'm wondering if there's a way in Swift to create a type that exclusively holds numbers that are strictly greater than zero and where the "positiveness" of the values is enforced at compile time.
For example, can I create somehow write code like
func divide(x: PositiveNumber, y: PositiveNumber){
return x / y
}
such that
divide(1, 3)
works but
divide(1, 0)
won't compile?
The closest thing I could come up with was a struct with only one fallible initializer such that the type has either a positive value or is nil:
struct PositiveNumber {
let value: Float
init?(value: Float){
if value > 0 {
self.value = value
} else {
return nil
}
}
}
func / (left: PositiveNumber, right: PositiveNumber) -> Float {
return left.value / right.value
}
func divide(x: PositiveNumber?, y: PositiveNumber?) -> Float? {
if let x = x, y = y {
return x / y
}
return nil
}
let x1 = PositiveNumber(value: 1)
let y1 = PositiveNumber(value: 3)
let x2 = PositiveNumber(value: -1)
let y2 = PositiveNumber(value: 0)
divide(x1, y: y1)! // .333
divide(x2, y: y2)! // runtime error
That's not terrible but we still have to deal with a lot of optional handling/unwrapping. I'm asking this question because I have many places in my code where I need to check that a value is not zero and I'm curious if there's a way to remove that code and let the compiler handle it. The struct-based solution requires pretty much the same amount of code.
Number Type build on Float
This gist is contains a Struct that conforms to pretty much everything Float conforms too. It is just a vanilla copy of Float, change it to your liking.
Have you considered a custom operator?
infix operator /+ { associativity left precedence 150 }
func /+(lhs:Float,rhs:Float) -> Float? {
guard rhs > 0 else {
return nil
}
return lhs / rhs
}
let test = 2 /+ -1 // nil
let test2 = 2 /+ 1 // 2
let test3 = 2 /+ 1 + 2 // warning
It doesn't really matter if you let it return an optional, or an enum value, or different protocols. You will have to handle the return. But this way you get compiler warnings.
Limited Number Type with just an operator to handle divisions:
You could change math altogether and create a PositiveNumber Type that returns NaN when dividing by a value less than Zero.
public struct PositiveFloat {
public var value: Float
/// Create an instance initialized to zero.
public init() {
self.value = 0
}
/// Create an instance initialized to `value`.
public init(_ value: Float) {
self.value = value
}
public init(_ value: PositiveFloat) {
self.value = value.value
}
}
extension Float {
public var positive : PositiveFloat {
return PositiveFloat(self)
}
}
public func /(lhs:Float,rhs:PositiveFloat) -> Float {
if 0 > rhs.value {
return lhs / rhs.value
} else {
return Float.NaN
}
}
public func /(lhs:PositiveFloat,rhs:PositiveFloat) -> Float {
if 0 > rhs.value {
return lhs.value / rhs.value
} else {
return Float.NaN
}
}
let testNormal : Float = 10
let testFloat : Float = -5
let test = testFloat / testNormal.positive
if test.isNaN {
// do stuff
}

Property getters and setters

With this simple class I am getting the compiler warning
Attempting to modify/access x within its own setter/getter
and when I use it like this:
var p: point = Point()
p.x = 12
I get an EXC_BAD_ACCESS. How can I do this without explicit backing ivars?
class Point {
var x: Int {
set {
x = newValue * 2 //Error
}
get {
return x / 2 //Error
}
}
// ...
}
Setters and Getters apply to computed properties; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x to be assigned.
Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need something to backup the computed property. Try this:
class Point {
private var _x: Int = 0 // _x -> backingX
var x: Int {
set { _x = 2 * newValue }
get { return _x / 2 }
}
}
Specifically, in the Swift REPL:
15> var pt = Point()
pt: Point = {
_x = 0
}
16> pt.x = 10
17> pt
$R3: Point = {
_x = 20
}
18> pt.x
$R4: Int = 10
You can customize the set value using property observer. To do this use 'didSet' instead of 'set'.
class Point {
var x: Int {
didSet {
x = x * 2
}
}
...
As for getter ...
class Point {
var doubleX: Int {
get {
return x / 2
}
}
...
Setters/getters in Swift are quite different than ObjC. The property becomes a computed property which means it does not have a backing variable such as _x as it would in ObjC.
In the solution code below you can see the xTimesTwo does not store anything, but simply computes the result from x.
See Official docs on computed properties.
The functionality you want might also be Property Observers.
What you need is:
var x: Int
var xTimesTwo: Int {
set {
x = newValue / 2
}
get {
return x * 2
}
}
You can modify other properties within the setter/getters, which is what they are meant for.
To elaborate on GoZoner's answer:
Your real issue here is that you are recursively calling your getter.
var x:Int
{
set
{
x = newValue * 2 // This isn't a problem
}
get {
return x / 2 // Here is your real issue, you are recursively calling
// your x property's getter
}
}
Like the code comment suggests above, you are infinitely calling the x property's getter, which will continue to execute until you get a EXC_BAD_ACCESS code (you can see the spinner in the bottom right corner of your Xcode's playground environment).
Consider the example from the Swift documentation:
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
Notice how the center computed property never modifies or returns itself in the variable's declaration.
In order to override setter and getter for swift variables use the below given code
var temX : Int?
var x: Int?{
set(newX){
temX = newX
}
get{
return temX
}
}
We need to keep the value of variable in a temporary variable, since trying to access the same variable whose getter/setter is being overridden will result in infinite loops.
We can invoke the setter simply like this
x = 10
Getter will be invoked on firing below given line of code
var newVar = x
Update: Swift 4
In the below class setter and getter is applied to variable sideLength
class Triangle: {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) { //initializer method
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get { // getter
return 3.0 * sideLength
}
set(newValue) { //setter
sideLength = newValue / 4.0
}
}
Creating object
var triangle = Triangle(sideLength: 3.9, name: "a triangle")
Getter
print(triangle.perimeter) // invoking getter
Setter
triangle.perimeter = 9.9 // invoking setter
You are recursively defining x with x. As if someone asks you how old are you? And you answer "I am twice my age". Which is meaningless.
You must say I am twice John's age or any other variable but yourself.
computed variables are always dependent on another variable.
The rule of the thumb is never access the property itself from within the getter ie get. Because that would trigger another get which would trigger another . . . Don't even print it. Because printing also requires to 'get' the value before it can print it!
struct Person{
var name: String{
get{
print(name) // DON'T do this!!!!
return "as"
}
set{
}
}
}
let p1 = Person()
As that would give the following warning:
Attempting to access 'name' from within it's own getter.
The error looks vague like this:
As an alternative you might want to use didSet. With didSet you'll get a hold to the value that is was set before and just got set to. For more see this answer.
Try using this:
var x:Int!
var xTimesTwo:Int {
get {
return x * 2
}
set {
x = newValue / 2
}
}
This is basically Jack Wu's answer, but the difference is that in Jack Wu's answer his x variable is var x: Int, in mine, my x variable is like this: var x: Int!, so all I did was make it an optional type.
Setters and getters in Swift apply to computed properties/variables. These properties/variables are not actually stored in memory, but rather computed based on the value of stored properties/variables.
See Apple's Swift documentation on the subject: Swift Variable Declarations.
Here is a theoretical answer. That can be found here
A { get set } property cannot be a constant stored property. It should be a computed property and both get and set should be implemented.
Update for Swift 5.1
As of Swift 5.1 you can now get your variable without using get keyword. For example:
var helloWorld: String {
"Hello World"
}
I don't know if it is good practice but you can do something like this:
class test_ancestor {
var prop: Int = 0
}
class test: test_ancestor {
override var prop: Int {
get {
return super.prop // reaching ancestor prop
}
set {
super.prop = newValue * 2
}
}
}
var test_instance = test()
test_instance.prop = 10
print(test_instance.prop) // 20
Read more

init function for structs

I realize that Go does not have classes but pushes the idea of structs instead.
Do structs have any sort of initialization function that can be called similar to a __construct() function of a class?
Example:
type Console struct {
X int
Y int
}
func (c *Console) init() {
c.X = "5"
}
// Here I want my init function to run
var console Console
// or here if I used
var console Console = new(Console)
Go doesn't have implicit constructors. You would likely write something like this.
package main
import "fmt"
type Console struct {
X int
Y int
}
func NewConsole() *Console {
return &Console{X: 5}
}
var console Console = *NewConsole()
func main() {
fmt.Println(console)
}
Output:
{5 0}
Go does not have automatic constructors. Typically you create your own NewT() *T function which performs the necessary initialization. But it has to be called manually.
This is a Go struct initialize complete:
type Console struct {
X int
Y int
}
// Regular use case, create a function for easy create.
func NewConsole(x, y int) *Console {
return &Console{X: x, Y: y}
}
// "Manually" create the object (Pointer version is same as non '&' version)
consoleP := &Console{X: 1, Y: 2}
console := Console{X: 1, Y: 2}
// Inline init
consoleInline := struct {
X int
Y int
}{
X: 1,
Y: 2,
}