I am confuse structure vs class in swift language [duplicate] - swift

This question already has answers here:
structure vs class in swift language
(13 answers)
Closed 3 years ago.
I am confused about structure vs class. I have seen this example According to this example structure-vs-class According to link may be code output is 15,15,15,20
BUT code output is
because Structure is not changed but when I have run code on Xcode it returns me 15,15,20,20
class objectmanagement
{
public var x : Int = 10;
func display()
{
print("\(x)")
}
}
struct StuctManagement{
var obj = objectmanagement()
}
let SA = StuctManagement()
SA.obj.x = 15
var SB = StuctManagement()
SB.obj = SA.obj
SA.obj.display()
SB.obj.display()
SB.obj.x = 20
SA.obj.display()
SB.obj.display()
I am confused please help me to understand this output this is same as a class output

In swift class is reference type. (see here)
When you say:
SB.obj = SA.obj
It means that the object of SA is the exact object in SB. (there is one pointer for SA.obj and SB.obj)
Although
let SB = SA
makes copy of SA and create SB with different reference.

Related

Swift adding object to array appends a copy instead of a reference? [duplicate]

This question already has answers here:
Is Swift Pass By Value or Pass By Reference
(10 answers)
Closed 1 year ago.
Sample code:
struct test {
var itest: Int?;
}
var tests : [test] = [];
var t = test();
tests.append(t)
t.itest = 99;
print(tests[0].itest)
print(t.itest)
produces
nil
Optional(99)
So it seems the append command creates a copy of t and not its reference.
If the array would contain a reference of t, both print outs must be itest=99.
A struct is not an "object" in the way you are probably thinking. It's a value. When you assign a value, it's copied. That's by design.

var to let type conversion or vice versa in swift: [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Can a var type be changed into let type or vice versa in swift. I try to search it online but there is no such content available online.
You cannot change the mutability of a variable once it has been declared. However, you can create a mutable/immutable copy of any variable.
let immutable = 21
var mutableCopy = immutable
mutableCopy = 2
var mutable = 3
let immutableCopy = 4
You also have to be aware though that mutability and copying means different things for reference and value types.
conversion from let to var
let a = "" /* Constant */
var b = a /* Variable */
b = "b"
conversion from var to let
var c = "" /* Variable */
let d = c /* Constant */
Declaring Constants and Variables Constants and variables must be declared before they’re used. You declare constants with the let
keyword and variables with the var keyword. source
Struct (Value Type) vs Class (Reference Type)
class TotoClass {
var str = "str"
}
struct TotoStruct {
var str = "str"
}
let classToto = TotoClass()
let structToto = TotoStruct()
classToto.str = "new Str"
structToto.str = "new Str"
last line doesn't compile and there will be an error
Cannot assign to property: 'structToto' is a 'let' constant

Fixing a bug in a ternary-like if-else block [duplicate]

This question already has answers here:
Change in Xcode 10 Playgrounds Variable Initialization change? Are Xcode 10 Playgrounds an interpreter?
(2 answers)
Closed 4 years ago.
Instead of using the ternary operator, I coded a if-else block which doesn't seem to compile... Didn't understand the bug exactly, why isn't it working? Error line is :
error: MyPlayground2.playground:6:1: error: variables currently must have an initial value when entered at the top level of the REPL
var parentAge: Int
And my code:
import UIKit
var parent: String = "mom"
var parentAge: Int
let optOne = 39
let optTwo = 43
if parent == "mom" {
parentAge = optOne
print(parentAge)
} else {
parentAge = optTwo
print(parentAge)
}
error: variables currently must have an initial value when entered at the top level of the REPL
You should either initialise it with optional or assign an initial value if not optional.
var parentAge: Int?
var parentAge: Int = 0
Both of above representation are correct.

Print contents of array with custom class swift [duplicate]

This question already has answers here:
Overriding description method in NSObject on swift
(1 answer)
How can I change the textual representation displayed for a type in Swift?
(7 answers)
Closed 5 years ago.
I have an array of type custom class as seen below. It has strings, ints, and double values.
class TrendData: NSObject {
var earlyTime = Date()
var recentTime = Date()
var earlyTimePrice = Double()
var recentTimePrice = Double()
}
I have an array as follows
let dataArray = [TrendData]()
I have filled in 2 values into the dataArray.
Right now when I use a print command as follows
print ("Label: \(dataArray)")
it prints this Label: [<App.TrendData: 0x600000472440>] ** [<App.TrendData: 0x600000472440>]
This is the correct behavior but I want to see all the values within each of these elements in the array. What is the best way to do that? I don't want to explicitly list out each element or even put it into a loop if I can avoid it. I am able to do it, it is just really messy right now. Is there any function or command that does this automatically?

Defining stored type properties on classes [duplicate]

This question already has answers here:
Stored type properties for classes in Swift
(2 answers)
Why no stored type properties for classes in swift?
(3 answers)
Closed 7 years ago.
I'm a Swift rookie and found myself confused when reading this paragraph from "The Swift Programming Language" reference book (on Language Guide > Properties > Type Properties):
“For value types (that is, structures and enumerations), you can define stored and computed type properties. For classes, you can define computed type properties only.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/br/jEUH0.l
But a couple of pages after this, the following code snippet can be found:
...
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
}
}
...
Where a stored type property is clearly defined inside a class context, which apparently negates what was stated earlier.
So, is this a documentation error or am I just missing something?
Edit 1
I don't feel like this is a duplicate from this question. I'm not asking why this functionality is not implemented, because apparently it is currently implemented (since the compiler won't identify it as an error). All I'm asking is if the documentation os out of date or my interpretation is incorrect.
Edit 2
This issue was addressed here. Apparently the documentation is out of date. This functionality was added on Swift 1.2
I believe what the documentation meant (in a rather confusing way) is that you cannot have class stored vars (while you can still have static stored vars).
So, to summarize
class Foo {
static var bar: Int { // ok (computed static type variable)
return 2
}
static var foo = "" // ok (stored static type variable)
class var foobar: Int { // ok (computed class type variable)
return 2
}
class var baz = "" // nope (stored class type variable)
}