This question already has answers here:
Ways to Create Instance
(2 answers)
Closed 5 years ago.
I apologize in advance for a possible duplicate but since I do not know the names of these declarations I was not able to find any answers to simular questions.
I would appreciate if anyone could explain the difference between these to object declarations to me:
var objectname: Classname!
var objectname = Classname()
Both are an instance of the class Classname right? So when do I use the first declaration and when the second? And why?
var objectname: Classname!
This declares an object of type Classname but does not give it a value. If you were to try to access this value, it would be nil. Because having no value in Swift is not allowed, the ! tells the compiler that the variable will have a value when it is accessed. For iOS development, I would not recommend using the first declaration because it is unsafe. I would use var objectname: Classname? which creates the same variable but does not assume that it has a value. You could use this type like this:
var objectname: Classname?
if let obj = objectname {
// do something with obj (the unwrapped value of objectname)
}
If objectname has a value, then the if statement executes, otherwise it doesn't.
var objectname: Classname()
This declares a variable of type Classname and initializes it at the same time. So while the first statement is nil, the second statement represents an object of type Classname. You should use this statement when creating an instance variable.
Related
//First way
var myVar: String = " Hello"
print(myVar)
//Second way
var str = "Hello"
print(str)
I get the same output no matter which of the two I use. What's the difference between them?
These two are basically the same.
When you use var myVar: String = "Hello", you directly tell the swift compiler that your variable is type String.
When you use var myVar = "Hello", you do not specify the type of your variable, so the swift compiler has do do that for you.
Usually, you can get away without declaring your variable type and just have swift do it for you. However, in some cases, namely computed properties and custom classes/structures, you must manually declare your variable to be a specific type.
In your case, either way is fine. The end result is the same, just be aware of the difference for the future.
These two variable are same but with different names :
var myVar
var str
in swift Type doesn't matter that defined because, swift based on value it recognizes what type it is.
This question already has answers here:
Check if `Any` value is object
(2 answers)
Closed 3 years ago.
Is it possible to check if an object (not as in OOP) is of reference type or value type?
let something : Any = getSomething() // func getSomething() -> Any
let isReferenceType : Bool = // how to check?
EDIT:
As pointed out this is practically a duplicate of Check if `Any` value is object
This is not so easy as it seems, see
let isReferenceType: Bool = type(of: something) is AnyClass
See How to test whether generic variable is of type AnyObject
However, if you need such things, then usually you have some big problem with your architecture that you should address instead. Using Any type should be the last resort for exceptional situations.
This question already has answers here:
In Swift, what's the difference between calling UINavigationController() vs UINavigationController.init()?
(3 answers)
Closed 5 years ago.
class A {
private var value: Int
init(value: Int) {
self.value = value
}
}
We have class A and what is the difference between I create this object by using A.init(value: 5) and A(value: 5)? Thanks
There is no functional difference between the two. Both styles will call the same initializer and produce the same value.
Most style guides that I've seen prefer to leave out the explicit .init-part in favor of the shorter A(value:) syntax — that also resembles the constructor syntax in many other languages.
That said, there are some scenarios where it's useful to be able to explicitly reference the initializer. For example:
when the type can be inferred and the act of initialization is more important than the type being initialized. Being able to call return .init(/* ... */) rather than return SomeComplicatedType(/* ... */) or let array: [SomeComplicatedType] = [.init(/* ... */), .init(/* ... */)]
when passing the initializer to a higher order function, being able to pass "something".map(String.init) rather than "something".map({ String($0) })
Again, it's a matter of style.
This question already has an answer here:
Swift 3 incorrect string interpolation with implicitly unwrapped Optionals
(1 answer)
Closed 6 years ago.
I don't understand why the type system lets me do this?
In other words I would expect this to crash when foo is passed to the function.
var foo:String!
func someFunction(_ bar:String?) {
print("-- \(bar) --")
}
someFunction(foo)
=> writes "-- nil --"
As #Hamish so correctly points out here:
https://stackoverflow.com/a/39537558/308189
If the expression can be explicitly type checked with a strong optional type, it will be. However, the type checker will fall back to forcing the optional if necessary.
And the comment on the answer explains why this question was asked:
As if it weren't bad enough that you have to use an IUO, now they're less useful and behave contradictorily. If I use one it's because I want it to be implicitly unwrapped. They should be called Schrödinger Optionals from now on. – Andreas
Inside your someFunction you are printing the optional not String. that's why it is not crashing. if you want to print bar as String you have to unwrap the value.
// This line will create variable named foo and type of it will be String! and value of it will be nil.
// It mean i can access this variable is force-wraped so it may dangerous but uses of this variable without type checking compiler will not give any warning(ignore by compiler).
var foo:String!
// This function will accept `String` value or `nil`.
func someFunction(_ bar:String?) {
print("-- \(bar) --")
}
// So calling this function use of `foo`(valued nil) will not give any compiler issue.
someFunction(foo)
This question already has answers here:
What is the difference between `let` and `var` in Swift?
(32 answers)
Closed 7 years ago.
The community reviewed whether to reopen this question 4 months ago and left it closed:
Original close reason(s) were not resolved
Consider this two codes:
if let myValue = myObject.value as NSString?{
//logic here
}
vs
if var myValue = myObject.value as NSString?{
//logic here
}
I know the let keyword is define a constant, is this mean that the first line of code, if the myObject.value is NSString , the myValue constant will be made? This looks confusing.
If you use the let then you will not be able to change myValue.
if let myValue = myObject.value as NSString? {
myValue = "Something else" // <-- Compiler error
}
On the other hand with var you can.
if var myValue = myObject.value as NSString? {
myValue = "Something else" // <-- It's fine
}
Please note that myValue does exists only within the scope of the if and changing its value does not produce effect outside of its scope.
Hope this helps.
You use let to create a constant, so in the first example you cannot change myValue.
When you use var, myValue is a variable which you can change inside the if statement.
The variable type is a different depending if you are using let or var.
let is final and can not be changed afterwards.
var is a normal variable.
Your myValue cannot be changed or modified if you using let in this statement.
“Use let to make a constant and var to make a variable.
The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.
This means you can use constants to name a value that you determine once but use in many places.
var myVariable = 42
myVariable = 50
let myConstant = 42
A constant or variable must have the same type as the value you want to assign to it.
However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type.
In the example above, the compiler infers that myVariable is an integer because its initial value is an integer.
Read the : iBook The Swift Programming Language
Thanks .
The example you stated is of Optional Binding
Optional binding is used to determine whether an optional has a value, and if so, to make that value available as a temporary constant or variable.
if let myValue = myObject.value as NSString?{
//logic here
}
Above code will extract myObject.value if exist as a constant, whereas the code below will extract myObject.value as a variable
if var myValue = myObject.value as NSString?{
//logic here
}