Optional strings can be represented by var optionalString : String ? = "Hello"
? after the type indicates that the value is optional. if the string contains no value, it will be set to nil
in the below statement, if the value for optionalName is present, it is assigned to the name variable and the conditional block will be executed
if let name = optionalName
{
greeting = "Hello \(name)"
}
Switches will now support any kind of data type. they are not limited to integers.
let vegetable = "red pepper"
switch vegetable
{
case "celery":
let vegetableComment = "Add some raisins"
case "cucumber", "watercress":
let vegetableComment = "That would make a good sandwich"
case let x where x.hasPrefix("pepper")
let vegetableComment = "It is a spicy \(x)?"
default:
let vegetableComment = "every thing tastes good in soup"
}
unlike earlier case, if any of the switch statement matches, it goes inside and exists after this, we don't need to have a break by default.
for looping we need to use for-in statements
let interestingNumbers = [
"Prime" : [2,3,5,7,11,13],
"Fibanocci" : [1,1,2,3,5,8],
"Square" : [1,4,9,16,25],
]
int largest = 0
for (kind, numbers) in interestingNumbers
{
for (number in numbers)
{
if (number > largest)
{
largest = number
}
}
}
var n = 2
while n < 100
{
n = n *2
}
n
we can keep an index in a loop using a .. operator !
var firstLoop = 0
for i in 0..3
{
firstLoop += i
}
firstLoop
var secondLoop = 3
for var i = 0; i < 3; i++
{
secondLoop +=3
}
secondLoop
No comments:
Post a Comment