Basics Flashcards
Swift combines the best of:
C and Objective-C.
Printing text
print(“Hello, world!”)
Print the value of a variable inside a text
place it in parentheses, and insert a backslash just prior to the opening parenthesis:
print(“The value is (myVariable)”)
For printing only the variable value:
print(myVariable)
The keyword to declare a variable
The keyword var
The following example declares a variable, “a”, and assigns its value as “42”.
var a = 42
It is possible to change variable values over time:
a = 88 // Now "a" has a value of 88.
Declare a constant
using the let keyword.
This example declares a constant named “one” and assigns it a value of 1:
let one = 1
Declare multiple constants on a single line
separate them with commas:
let x = 0.0, y = 0.0, z = 0.0
Can constant and variable names contain almost any character?
Constant and variable names can contain almost any character, including Unicode characters.
However, constant and variable names must have no blank spaces, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line and box-drawing characters. Numbers can appear anywhere within a name, except for at the beginning.
Constants or variables of a certain type can’t be declared again with the same name, nor can they be altered to store values of differing types. Also, a constant cannot be made a variable, nor can a variable be made a constant.
Type annotations?
Type annotations ensure that your code is clear about the value stored within your constant or variable. Swift’s basic types include:
- *Int**: Integers
- *Double and Float**: Floating-Point Values
- *Bool**: Boolean Values
- *String**: Textual Data.
Add a type annotation by placing a colon (:) after the constant or variable name, then add a space, and then add the type name, as follows:var welcomeMsg: String
welcomeMsg = “Hello”
Are type annotations necessary?
In practice, you will rarely need to add type annotations. Providing an initial value for a constantor a variable at the point at which it is defined, will almost always be sufficient for Swift to infer which type should be used:
let pi = 3.14159 //Double
Basic Operators?
An operator is a special symbol or phrase used to check, change, or combine values.
Unary Operator
Has a single target (-a). A unary prefix operator is placed before the target (!b). A unary postfix operator is placed after the target (i++).
Binary Operator
Has two targets (4 + 5) and is infixed, appearing between the two targets.
Ternary Operator
Has three targets. Like C, Swift has one ternary operator, the ternary conditional operator (a ? b : c).