viewcontroller.swift 文件的viewdidload方法下面写代码
- 定义变量 var myvar1=1;由于是swift是弱变量类型,所以会根据你的赋值来确定你定义的变量是什么类型的。但是一旦确定下来就不会改了。举个错误的例子:var myvar1=1;myvar1=1.0;就会报错。但是你这样就是可以的:myvar1=1.0;myvar1=1;这样其实他还是可以的。另外如果你确实需要转换变量类型,可以再定义一个不同的变量。例如:var var1=“hello”;var var2=12;var var3=var1+String(var2)。此外,swift有一个屌炸天的功能,变量可以是英语之外的其他语言,例如以下就是正确的:var 姓名=“张三”; 但是不推荐这样。
- swift除了可以用var定义变量,还可以用let定义常量。例如:let let1=12;但是一旦定义,就不可以在重新赋值。例如以下就是错误的: let let1=12; let1=90;
- swift的语句可以不用 ;但是如果一行有多句,就必须了。但是不推荐这样写。
- swift引用变量的值\(变量名)。例如: println(“myvar is \(myvar1)”);也可以这样let let1=‘l have \(myvar) apples“
- swift中字典的使用。 var capital=["sichuan":"chengdu","henan":"zhengzhou","shandong":"jinan"];
//println(capital["sichuan"]! );
capital["shandong"]="shijiazhuang";
// println(capital["shandong"]);
//capital["shandong"]=nil;
//capital.removeValueForKey("shandong");
for (mykey,myvalue) in capital{
println(mykey);
}
for (mykey,myvalue) in capital{
println(mykey);
}
for myinfo in capital{
println(myinfo);
}
//(key,value)中的key和value不仅可以普通的变量,还可以是数组。例如:
let interestingNumbers = [
"Prime": [2,3,5, 7,11,13],
"Fibonacci": [1,1,2, 3,8],
"Square": [1,4,9, 16,25],
]
var largest = 0
for (kind,numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
println("\(largest)");
- swift中的switch和where。代码如下:
let vegetable = "red pepper"
var vegetableComment="vagetableComment";
switch vegetable {
case "celery":
vegetableComment = "Add some raisins and make ants on a log."
case "cucumber","watercress":
vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper11"):
vegetableComment = "Is it a spicy \(x)?"
println("\(x)")
case let x where x.hasSuffix("pepper"):
vegetableComment = "Is it a spicy \(x)?"
println("\(x)")
default:
vegetableComment = "Everything tastes good in soup."
}
println(vegetableComment);
原文链接:https://www.f2er.com/swift/325830.html