Swift3自学01
2016-10-31 本文已影响0人
hibear
终于开始学Swift3了 要坚持下去!!!
Paste_Image.png
变量与常量
let 常量
var 变量
optional 可选项
不同类型之间不可以直接运算
定义可选项"?" 解包"!"
var的可选默认值为nil let没有默认值
?? 简单的三目 如果有值使用值 没有值使用??后面的值 优先级低
if let, if var 连用
switch 不需要break
取消传统for循环
for in 开闭空间 .xxx() 反转等
let x : Double = 3;
let y = 3.3;
let we : String = "sdf"
let xx : Optional = 234
let yy : Int? = 20
print(xx!+yy!)
x > 5 ? print("大于10") : print("小余10")
x > 19 ? print("大于10") : ()
let x : Int? = 10;
let y : String? = "老王";
if let xx = x, let yy = y {
print(String(xx)+yy)
}else{
print("no")
}
guard let xxx = x ,let yyy = y else { return }
print(String(xxx)+yyy)
let age :Int = 9;
switch age {
case 8,9:
print("yes")
default:
print("no")
}
for i in 0..<10 {
print(i)
}
for i in 0...9 {
print(i)
}
for i in (0..<10).reversed() {
print(i)
}
字符串处理
//返回指定编码的对应字节数量
//UTF8 每个汉字是3个字节
print(s.lengthOfBytes(using: .utf8))
//返回字符串长度
print(s.characters.count)
// 值 as 类型 -> 类型转换
let osStr = s as NSString
print(osStr.length)
//\(变量/常量)
var str : String = "\(s) 这样?"
let point = CGPoint(x: 100, y: 200)
//format日期
let h = 10;let m = 2;let sss=3;
let dateStr = String(format: "%.2d:%.2d:%.2d", h,m,sss)
let s :String = "第一次感受Swift3.0"
let osStr = s as NSString
let s1 = osStr.substring(with: NSMakeRange(0, 5));
let s2 = s.range(of: "Sw")
guard let ra = s.range(of: "Sw") else {
print("no")
return
}
print(s.substring(with: ra))
数组
let array = ["sf","我们"]
let arr2 = [1,2,3,4]
let pi = CGPoint(x: 100, y: 100)
let arr3 = [pi]
//Swift 中一个累可以没有任何父类
//Swift 中有一种[AnyObject] ->任意对象
let arr4 = ["sdf",2] as [Any]
print(arr4)
数组遍历
let array = ["sf","我们","搜索"]
for s in 0..<array.count {
print(array[s])
}
for s in array {
print(s)
}
//元组
for s in array.enumerated() {
print("\(s.offset) with \(s.element)")
}
// n 对应索引下标 s 对应元素
for (n,s) in array.enumerated() {
print("\(n) ns \(s)")
}
//反序
for s in array.reversed() {
print(s)
}
//错误的反序 索引和内容不一致
for (i, s) in array.reversed().enumerated() {
print("\(i) \(s)")
}
//正确的反序 先枚举再反序
for (i, s) in array.enumerated().reversed() {
print("\(i) \(s)")
}