Ive searched for the answer to this for a while and can't seem to find it.
But for example, what is the difference here:
var this: that
var this = that
Thanks
var this: That
declares a mutable variable of type That.
var this = that
declares a mutable variabel and assigns an instance of That to it. The type (That) is inferred in this case.
A more belt and braces method of declaring it:
var this: That = that
But usually type inference is enough.
: force assigns a constant/variable a type, whereas = assigns it a value
example of ::
let str: String = ""
example of =:
let str = ""
":" refers to defining the type of the variable
"=" refers to assigning a value to that variable
e.g.
var myString: String (declares a variable of type String)
var myString = "example text" (declares a variable who's type is implicitly determined to be String and assigns the value "example text" to it)
var myString: Int = "example text" (Syntax error. Defined a variable of type Int and tried to assign a String to that value)
Related
I'm trying to understand why casting in the first case works while in the second it fails. What is the difference between the two?
var myVariable = 2
var myDoubleTest1 = Double(myVariable)
var myDoubleTest2 = myVariable as? Double
print(myDoubleTest1) // 2.0
print(myDoubleTest2) // nil
var myDoubleTest1 = Double(myVariable)
This line is just an initializer on Double. It takes an int, and initializes a new double. The documentation is here.
var myDoubleTest2 = myVariable as? Double
The as? keyword in Swift performs a cast. This means, in English, "create a variable named myDoubleTest2. If myVariable is of type Double, then use that. Otherwise, make it nil. We know, from the first line in your code (var myVariable = 2), that myVariable is not a Double (it is an Int), so myDoubleTest2 will be nil. You can read more about type casting here.
The first case
var myDoubleTest1 = Double(myVariable)
you actually converts the Int to Double
but in second
var myDoubleTest2 = myVariable as? Double
it checks whether myVariable is of Double type & has no nil value if passed ,it assigns it's value to myDoubleTest2
Why am i getting this error?
Error: Value of type 'Any' (aka protocol<>) has no member 'name'
import UIKit
var alican = (name: "alican", surame:"yilmaz")
var array:[Any] = [alican]
print(array[0].name)
You've declared your Array as containing Any type. If you declare it like this the error should go away:
var array:[(name: String, surame: String)] = [alican]
If the array needs to be able to contain Any type you can pull out just those matching a particular type using flatMap.
var array:[Any] = [alican]
var nameSurnames = array.flatMap({ return $0 as? (name: String, surame: String) })
print(nameSurnames[0].name)
Just drop the typing of the array...
var array = [alican]
Typs is inferred wherever possible by swift.
You only need to explicitly type a variable if it is not possible to infer it automatically.
This is how you can access name and surname
var alican = (name: "alican", surame:"yilmaz")
var array = [alican]
print(array[0].name)
When you cannot initialize an object due to invalid input, you can use a "failable init".
init?(s:String) {
if s.isEmpty {
return nil
}
// now set up instance vars
}
Then you can do this:
var x:Foo = ""
if x == nil { blah blah
But is you conform to the StringLiteralConvertible protocol and implement those 3 inits, you cannot have a failable init.
My question: how do you check for invalid input when you use StringLiteralConvertible?
Here's a gist of those 3 inits if you've never used StringLiteralConvertible.
If you use StringLiteralConvertible, you can assign a literal string to a variable:
var x: Foo = "test"
Any string you provide is good, as long as it is a valid string. If it's not a string:
var x: Foo = 1
or it's a malformed string:
var x: Foo = test"
it won't pass compilation, so a failable initializer would be useless.
But if by valid you mean depending on the content of the string, then you are right. A literal must be syntactically correct and of the expected type in order to be considered valid in the context where it is used, and I don't think there's a way to override that.
I tried searching around for what this is
[]()
But I'm not really sure. In a playground, I did this:
var test = [Int]();
test.append(1);
test.append(2);
If I leave off the () and do
var test = [Int];
test.append(1);
test.append(2);
It still looks like an array of Ints to me. What is the difference?
Type() means "call init()" - i.e., make a new instance of Type.
[Int] is a type, like String. [Int] means "array-of-Int".
String() makes a new empty String instance. [Int]() makes a new empty array-of-Int instance.
You can declare a variable as being of type array-of-Int. Or you can make and assign a new array-of-Int instance. Which is what you are doing here:
var test = [Int]()
But you cannot assign a type to a variable without further syntax. Thus, this is illegal:
var test = [Int]
EXTRA for experts
You can say:
var test = [Int].self
That does assign the type to the variable! That is unlikely to be what you want here, because now you have no array; you have a type, itself, as object!!
[Type] is syntactic sugar for Array<Type>, so it represents the array type, which is a generic struct, and for which you specify the type of elements it holds (Int in this example)
So the difference between:
[Int]
and
[Int]()
is the same as for
Array<Int>
and
Array<Int>()
The first is just a type, which you can use when declaring a variable or a function parameter.
The second invokes the parameterless constructor on that type, i.e. creates an instance of that type.
In Swift Programming, should we need to declare datatype of the variable or will the variable change it's type based on value?
Which one is enough to declare a variable:
var MyVar: Int = 50
Or:
var Myvar = 50
var myVar: Int = 50
Or:
var myVar = 50
They are absolutely equivalent. The : Int is unnecessary because you are assigning 50 right there in the declaration, so Swift infers that this is to be an Int variable.
If you are going to assign as part of the declaration, the only time you need to supply the type is when the type is surprising. For example:
var myChar : Character = "s"
If you don't say Character, you'll get a String.
WWDC 2104 - Introduction To Swift (Session 402)
var languageName = “Swift” // inferred as String
var version = 1.0 // inferred as Double
var introduced = 2014 // inferred as Int
var isAwesome = true // inferred as Bool
Also…
var 🐸 = “Frog” // using unicode names
You should also use “let” for variables that will not change.
Type inference is one of the great parts of Swift. This means that when you assign a variable or constant, the system infers what type it should be. If for instance, you were declaring a variable before you set it, you'd need to specify its type explicitly.
var someVar: Int
someVar = 15
That way the compiler knows when it is being properly set.
You can declare a variable implicitly as:
var myVar = 50
or explicitly as:
var myVar:Int = 50
Also notice that you do not use the semi-colon ; to end the line.
Note that values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type, such as the following:
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
From a complete beginner's view (mine) i see the following benefit of declaring a variable explicitly - the compiler will validate the input value - i.e. if you declare an empty variable and then update it with the wrong type value you will be prompted.
The first seems to be used only integer assignment.
I need to write code to test.
Update:
I mean,
Defined as int can not assign to string, the following is wrong:
var myVar: Int
myVar = "50"
And such is wrong:
var myVar
myVar = "50"
So, if assignment when you define a variable, use both two.
Otherwise, use:
var myVar: Int
Therefore, it is no difference between the two lists you.
Note that I changed MyVar to myVar to follow the convention.
var myVar: Int = 50
means -> message to the compiler will be.
Declare a variable called myVar that is of type(:) Int
and
var myVar = 50
will result the exact same. But here compiler will deduce the type for us. (Welcome to modern intelligent compilers). Type inference is strong feature of swift language.
Be aware that Swift is Type Safe Language