var someStrs = [String]() someStrs.append("Apple") someStrs.append("Amazon") someStrs.append("Runoob") someStrs += ["Google"] for (index, item) in someStrs.enumerated() { print("在 index = \(index) 位置上的值为 \(item)") }
不带索引的
1 2 3 4 5 6 7 8
var someStrs = [String]() someStrs.append("Apple") someStrs.append("Amazon") someStrs.append("Runoob") someStrs += ["Google"] for item in someStrs { print(item) }
数组合并也比OC简单
类型一样的话直接加就行了
1 2 3 4 5 6 7 8
var intsA = [Int](repeating: 2, count:2) var intsB = [Int](repeating: 1, count:3)
var intsC = intsA + intsB
for item in intsC { print(item) }
遍历字典
1 2 3 4 5
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict { print("字典 key \(key) - 字典 value \(value)") }
数组的长度还是count没有变
Swift还加了一个判断为空的函数isEmpty
字典也是一样
count 代表字典里键值的个数
isEmpty则是判断字典是否为空
接下来就是循环和判断了
在Swift中if后面必须跟一个布尔值的表达式
不能像之前OC一样可以用对象
1 2 3 4 5 6 7 8 9 10
let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } print(teamScore)
?和??是Swift新增的内容
?代表的是变量可以为空
对应的还有一个!代表不可能为空
??代表如果当前值为空可以设置一个默认值
有点a ? b : c的意思
Switch就比较厉害了
支持任意类型的数据以及各种比较操作
这一点就像if else if else
1 2 3 4 5 6 7 8 9 10 11
let vegetable = "red pepper" switch vegetable { case "celery": print("Add some raisins and make ants on a log.") case "cucumber", "watercress": print("That would make a good tea sandwich.") case let x where x.hasSuffix("pepper"): print("Is it a spicy \(x)?") default: print("Everything tastes good in soup.") }
与OC不一样的是不用在case里面写break
for in和OC差不多
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 for (_, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number } } } print(largest) // 输出 "25"
while变化的不太多
1 2 3 4 5 6 7 8 9 10 11
var n = 2 while n < 100 { n *= 2 } print(n)
var m = 2 repeat { m *= 2 } while m < 100 print(m)
唯一改变的就是条件增加了一范围
1 2 3 4 5
var total = 0 for i in 0..<4 { total += i } print(total)
..<不包含0
要想包含0就得改成...
方法基本全改了
func后面跟方法名
(参数名:参数类型)里面传参数
->后面跟返回值
1 2 3 4
func greet(_ person: String, on day: String) -> String { return "Hello \(person), today is \(day)." } greet("John", on: "Wednesday")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { var min = scores[0] var max = scores[0] var sum = 0
for score in scores { if score > max { max = score } else if score < min { min = score } sum += score }
// 定义枚举 enum DaysofaWeek { case Sunday case Monday case TUESDAY case WEDNESDAY case THURSDAY case FRIDAY case Saturday }
var weekDay = DaysofaWeek.THURSDAY weekDay = .THURSDAY switch weekDay { case .Sunday: print("星期天") case .Monday: print("星期一") case .TUESDAY: print("星期二") case .WEDNESDAY: print("星期三") case .THURSDAY: print("星期四") case .FRIDAY: print("星期五") case .Saturday: print("星期六") }
break case continue default do else fallthrough for if in return switch where while
class deinit enum extension func import init internal let operator private protocol public static struct subscript typealias var
as dynamicType false is nil self Self super true _COLUMN_ _FILE_ _FUNCTION_ _LINE_
associativity convenience dynamic didSet final get infix inout lazy left mutating none nonmutating optional override postfix precedence prefix Protocol required right set Type unowned weak willSet
Swift变量和运算符一定要加一个空格
NSLog也变成了print
Swift没有了++和--
只能num = num + 1或者num = num - 1
但是+=-=*=/=%=都还在
Swift 打印常量和变量
打印常量
1 2 3
var stringA = "菜鸟教程:" stringA += "http://www.runoob.com" print( stringA )
打印变量
1 2 3 4 5
var varA = 20 let constA = 100 var varC:Float = 20.0 var stringA = "\(varA) 乘于 \(constA) 等于 \(varC * 100)" print( stringA )
字符串的连接也特别的简单
直接用+连接就行了比OC要好
1 2 3 4
let constA = "菜鸟教程:" let constB = "http://www.runoob.com" var stringA = constA + constB print( stringA )
也可以直接用+=来拼接字符串
两个字符串比较也直接用=就可以直接比较
1 2 3 4 5 6 7 8
var varA = "Hello, Swift!" var varB = "Hello, World!"
var chemCount = 0 var mathsCount = 0 for item in sa { // 如果是一个 Chemistry 类型的实例,返回 true,相反返回 false。 if item is Chemistry { ++chemCount } else if item is Maths { ++mathsCount } }
for item in sa { // 类型转换的条件形式 if let show = item as? Chemistry { print("化学主题是: '\(show.physics)', \(show.equations)") // 强制形式 } else if let example = item as? Maths { print("数学主题是: '\(example.physics)', \(example.formulae)") } }
for item in saprint { // 类型转换的条件形式 if let show = item as? Chemistry { print("化学主题是: '\(show.physics)', \(show.equations)") // 强制形式 } else if let example = item as? Maths { print("数学主题是: '\(example.physics)', \(example.formulae)") } }
for item2 in exampleany { switch item2 { case let someInt as Int: print("整型值为 \(someInt)") case let someDouble as Double where someDouble > 0: print("Pi 值为 \(someDouble)") case let someString as String: print("\(someString)") case let phy as Chemistry: print("主题 '\(phy.physics)', \(phy.equations)") default: print("None") } }
for item in sa { // 类型转换的条件形式 if let show = item as? Chemistry { print("化学主题是: '\(show.physics)', \(show.equations)") // 强制形式 } else if let example = item as? Maths { print("数学主题是: '\(example.physics)', \(example.formulae)") } }
// 可以存储Any类型的数组 exampleany var exampleany = [Any]()
for item2 in exampleany { switch item2 { case let someInt as Int: print("整型值为 \(someInt)") case let someDouble as Double where someDouble > 0: print("Pi 值为 \(someDouble)") case let someString as String: print("\(someString)") case let phy as Chemistry: print("主题 '\(phy.physics)', \(phy.equations)") default: print("None") } }
extension Int { var add: Int {return self + 100 } var sub: Int { return self - 10 } var mul: Int { return self * 10 } var div: Int { return self / 5 } }
let addition = 3.add print("加法运算后的值:\(addition)")
let subtraction = 120.sub print("减法运算后的值:\(subtraction)")
let multiplication = 39.mul print("乘法运算后的值:\(multiplication)")
let division = 55.div print("除法运算后的值: \(division)")
let mix = 30.add + 34.sub print("混合运算结果:\(mix)")
添加方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
extension Int { func topics(summation: () -> ()) { for _ in 0..<self { summation() } } }
protocol classa { var marks: Int { get set } var result: Bool { get } func attendance() -> String func markssecured() -> String }
protocol classb: classa {
var present: Bool { get set } var subject: String { get set } var stname: String { get set } }
class classc: classb { var marks = 96 let result = true var present = false var subject = "Swift 协议" var stname = "Protocols" func attendance() -> String { return "The \(stname) has secured 99% attendance" } func markssecured() -> String { return "\(stname) has scored \(marks)" } }