var
// 变量
var a = 6;
var b = 26;
let
// 常量
let c = a+b;
:String
:Int
……
// 指明变量类型
var s = "Save"
var y:String = "you"
var z:Int = 6 ;
print
Swift2.0后,就废弃和原有的println方法,同时拓展的print方法。
那么用
print换行
print("pirntln!", terminator: "\n")
"\()"
// 字符串连接
var s2 = "Save"
var s3 = "you"
var i = 06
s3 = "\(s2) \(s3)"
var s4 = "\(s3) \(i)"
print(s4, terminator: "\n")
// 数组
var array = ["Save","you",0,6]
var array2 = []
var array3 = [String]()
print(array, terminator: "\n")
print("[] = \(array2)", terminator: "\n")
print("[String]() = \(array3)", terminator: "\n")
var dict = ["name":"CaMnter","age":"22"]
dict["language"] = "Swift"
print(dict, terminator: "\n")
print(dict["language"], terminator: "\n")
for
var dict = ["name":"CaMnter","age":"22"]
for (key,value) in dict{
print("\(key) \(value)", terminator: "\n")
}
for index in 0...5{
print(index, terminator: "\n")
}
var i1 = 5
while i1<10{
print(i1, terminator: "\n")
i1++
}
var s:String?
var s:String!
?的作用
- 1.声明Optional值变量
- 2.对Optional值操作中,用来判断是否能响应后面的操作
- 3.安全调用protocol的optional方法
- 4.as? 向下转型(Downcast)
!的作用
- 1.强制对Optional值进行拆包(unwrap)
- 2.声明Implicitly Unwrapped Optionals值,一般用于类中的属性
if
和if let
for index2 in 0...10{
if index2%2 == 0{
print(index2, terminator: "\n")
}
}
有一种独特的流程控制是if let
,可用于判断变量或者表达式的值是否为空。 s7这里就相当于一个Optional类型,用于判断下面的操作是否执行。
var s5:String?="CaMnter"
var s6:String?="\n"
s6 = nil
if let s7=s5{
print(s5, terminator: "\n")
}
if let s8=s6{
print(s6, terminator: "\n")
}
只输出结果为s6的值,因为s5赋值给s7后,判断了s7为nil,下面括号里的操作就不执行了。
Optional("CaMnter")
// 无返回值
func say(name:String){
print("\(name)", terminator: "\n")
}
// 有返回值(返回多个)
func getValue()->(String,String){
return ("CaMnter","Swift")
}
// 接收多个返回值
let (s9,s10) = getValue()
print(s10, terminator: "\n")
// 可以定义一个变量接收函数
var fun1 = say
say("Save you from anything")
class
和 :
// 父类
class Parent {
func info(){
print("Parent class", terminator: "\n")
}
}
// 继承自父类
class Child: Parent {
var _tag:String
init(tag:String) {
self._tag=tag
}
// 重写父类的方法
override func info() {
print("Child class \(self._tag)", terminator: "\n")
}
}
var p = Parent()
var c2 = Child(tag: "CaMnter")
p.info()
c2.info()
输出结果:
Parent class
Child class CaMnter