The Basics
Two type of values
Constants & Variables
Declaration
let keyword = "Hello, swift"
It cannot be changed or redefined once defined.
var keywork = "Hello, swift"
It is able to be changed later but not be changed the name.
Just use colon after the name to add a type annotation,
let keyword: String
var keyword2: String
Or, you can declare multiple variables in same type just on a single line, separated by commas:
let keyword = "Hello, swift", keyword2 = "Hello, Dan", keyword3 = "Hello, Kev"
var keyword, keyword2, keyword3: String
Just use print(_:separator:terminator:)
function to output the value in console.
let keyword = "Hello, swift"
print(keyword) //will show "Hello, swift" in console
print("The current value of keyword is \"\(keyword)\"")//will show "The current value of keyword is "Hello, swift"" in console
Numeric Literals
decimal number
we can describe it with an exponent of “e”, which means
For example:
- 1.5e2 means 1.5*
= 150
Hexadecimal number
we can describe it with an exponent of “p”, which means
For example:
- 0xFp2 means 15*
= 60
Tips:
We can use extra zero and underscores to make the number literal easier to read without changing its value.
For example:
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
Tuples
If we only need one value of tuple, we can use a underscore to handle the value, just like this:
let http404Error = (404, "Not Found")
let (justTheStatusCode, _) = http404Error
print(justTheStatusCode)// will print "404"
Or you can just use a specific value to handle this:
let http404Error = (404, "Not Found")
let (justTheStatusCode, _) = http404Error.0
print(justTheStatusCode)// will print "404"
And we can name the individual elements in a tuple:
let http404Error = (statusCode: 404, description: "Not Found")
print(http404Error.statusCode)// will print "404"
print(http404Error.description)// will print "Not Found"
Error Handling
we can make a function tailed a throws keyword, in which if we meet some error conditions we can throw an error.
func canThrowAnError() throws {
// can throw an error
}
do {
try canThrowAnError()
} catch {
//do things here if error occurs
}
Let's think!