swift基础笔记(二)

373 阅读6分钟

let和var

var a = 10 //变量
let b = 20 //常量 赋值一次 不可修改
print(a,b)///10 20
a = 30
print(a)///30
b = 50 ///报错Cannot assign to value: 'b' is a 'let' constant
//常量、在初始化之前都不能使用

基础数据类型

  • Int、Float、Double、Bool、Character、String
  • Array、Dictionary、(元组类型)Tuple
  • 数据类型的首字母都是大写、两个类型不相同的数值,是不能直接进行运算的

类型别名

typealias SK = Int
let i:SK = 666
print(i)
typealias Block = (_ age:Int)->()
let myBlock : Block

类型转换

let str: String = "10"
let a = Int(str)

let str: String = "10"
let a = Double(str)

let a: Int = 20
let str = String(a)

let a: Int = 20
let b = Double(a)

let a: Double = 3.14
let str = String(stringInterpolationSegment: a)

let a: Double = 3.14
let b = Int(a)

??语法

//如果对象为nil,则使用后面的值代替,但是原变量不修改
let defaultColorName = "red"
var userDefinedColorName: String?   // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName

可选类型以及可选类型取值

//可选类型定义
var newName : String?
newName = "swift"
print(newName)///Optional("swift")
let dictionary = ["name":"objective"]
let item = dictionary["name"]
print(item)///Optional("objective") 可选项 不能拿来用
//取值
///1.强制解包
print(newName!,item!)///swift objective
///不建议使用 值为空会崩溃
let itemS = dictionary["nil"]
print(itemS)///nil 不会崩溃
//print(itemS!)///崩溃 Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
///可选项绑定
if let item = item {
  print(item)///objective
}
///2. ??
print(item ?? "默认值")///objective
///3.guard
guard let new = item else {
     return//不符合条件 直接返回 符合条件 继续执行下面的代码
}
print(new)///objective

元组

///元组定义
var yz = ("he",true,"swift",15)//var变量 可以改值
let h :(Int,String) = (66,"swift")///指定类型 let不能修改
let c = (age:10,name:"swift")
let (age,name) = (22,"sk")
///取值
let itemYZ = yz.1
let itemH = h.1
let itemC = c.name
///修改
yz.1 = false
print(age,name)///22 sk
print(itemYZ,itemH,itemC)///true swift

数组

///定义
let array = ["1","2","3"]///不可变数组
var mArray = Array<String>()///可变数组
var selectArray : Array<Dictionary<String,Any>> = []///装有字典的可变空数组
///操作数组-针对可变数组
//1.添加元素
mArray.append("First")
mArray.append("Second")
mArray.append("Third")
print(array,mArray)///["1", "2", "3"] ["First", "Second", "Third"]
//2.删除元素
mArray.remove(at: 1)
print(mArray)///["First", "Third"]
//3.取出元素
let item = mArray[0]
 print(item)///First
//4.修改元素
mArray[0] = "edit First"
print(mArray)///["edit First", "Third"]
//5.遍历
for item in mArray {
    print(item) ///edit First、 Third
}
for item in mArray[0..<1] {///遍历指定区间
    print(item) ///edit First
}
for (index,value) in mArray.enumerated() {
    print(index,value)///0 edit First 1 Third
}
///遍历 数组内的model对象
let watch_list = NSMutableArray.init()//oc 可变数组
let array = CommonDataManage.sharedManager().watchBindArray
if let modelArray = array as? [ContectWatchModel] {
for model in modelArray {
    watch_list.add(["watch_userid":NSNumber.init(value: Int(truncating: model.watch_userid))])
    }
}

字典

let dic:[String:Any] = ["name":"s","age":10]
let dictionary = ["name":"swift","age":"10"]///不可变
print(dic,dictionary)//1.["age": 10, "name": "s"]2.["age": "10", "name": "swift"]
var dicM = [String : Any]()///可变
///添加元素
dicM["height"] = 20
dicM["name"] = "objective"
print(dicM)///["name": "objective", "height": 20]
///删除元素
dicM.removeValue(forKey: "name")
print(dicM)///["height": 20]
///修改元素
dicM["height"] = 178
print(dicM)///["height": 178]
///获取元素
let item = dicM["height"]
print(item!)///178
///遍历元素
dicM["weight"] = 108
dicM["age"] = 28
for key in dicM.keys {
    print(key)///age height weight
}
for value in dicM.values {
    print(value)///28 178 108
}
for (key,value) in dicM {
    print(key)
    print(value)
}

字符串

///1.空字符串
var string = ""
print(string)
if string.isEmpty {
    print("空字符串!")///执行
}
string = "swift"
print(string)//swift
///2.定义字符串 初始化为nil 后期可赋值
var str : String?
/*
if str.isEmpty {///报错 Value of optional type 'String?' must be unwrapped to refer to member 'isEmpty' of wrapped base type 'String'
    print("空字符串!")
}
*/
str = "objective"
print(str ?? "")///objective
///3.字面量
let str_1 = "a little"///swift会自己推断为String类型
print(str_1)///a little
///4.多行显示
let softWrappedQuotation = """
1. 我是swift
2. 你好好的生活着
3. 理解万岁
"""
print(softWrappedQuotation)
/*
1. 我是swift
2. 你好好的生活着
3. 理解万岁
*/
///5.遍历
let open_swift = "openswift"
for c in open_swift {
    print(c)///每一个独立的Character
}
///6.字符串比较
/*
1.字符串和字符相等性(== 和 !=)
2.前缀相等性 hasPrefix(_:)
3.后缀相等性 hasSuffix(_:)
*/
///7.拼接字符串
let a = 10
let c:String = "hello"
let h:String = c + "\(a)"
print(h) //hello10

注释

// 单行注释
/*多行注释*/

闭包

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ///1.通过闭包表达式 定义函数
        let sum = {
            ///大括号+参数+返回值类型+in+函数体代码
            (num1: Int, num2: Int) -> Int  in
            return num1 + num2
        }
        let result =  sum(5,5)
        print(result)//10
        
        ///2.作为函数参数 回调
        callBck { (dictionary) in
            print(dictionary)///["key": "10"]
        }
    
        ///3.尾随闭包是一个书写在函数括号之后的闭包表达式,函数支持将其作为最后一个参数调用。
        callBck { (dic) in///注意: 如果函数只需要闭包表达式一个参数,当您使用尾随闭包时,您甚至可以把()省略掉。
            print(dic)///["key": "10"]
        }
    }
    
    typealias SumBlock = (Dictionary<String, String>) -> ()
    
    func callBck(block:SumBlock)///类似 网络请求回调结果
    {
        let dictionary = ["key" : "10"]
        block(dictionary)
    }
    
    
}

函数

//函数定义
///1.无返回值
func initUI(title : String)  {
}
///2.有返回值
func callTitle(title : String) -> String  {
    return title + "改变!"
}
///3.无参数 无返回值
func blindWatch() {
}
///4.可变参数
//调用  callName("hello","swift","php","小程序","fluute","web")
func callName(_ name:String...) {
    var totalStr = ""
    for str in name {
        totalStr += str
        print(str)/// 传进来的参数 逐个打印 hello swift php 小程序 fluute web
    }
    print(totalStr)///helloswiftphp小程序fluuteweb
}
///5.嵌套函数 函数中定义函数

///6. inout 本质 地址传递 swift中需要对参数只进行修改,需要用到inout 关键字,调用函数时加&
/*
func sd_change(name : String)  {
    name = "new_" + name//报错 参数默认为let 不能修改
}
*/
//  调用 var name = "swift" sd_change(name: &name)
func sd_change(name : inout String)  {
    name = "new_" + name //swift中需要对参数只进行修改,需要用到inout 关键字,调用函数时加&
    print(name)
}

枚举

import UIKit

/*
OC:
枚举只能为Int类型
swift :
可以在枚举中定义方法
可以声明case的类型是Int、Double、String等类型
可以使用使用关联值,也就是case携带参数
可以使用rawValue取值,但必须声明类型
可以使用init(rawValue:)创建枚举,但必须声明类型
*/

enum PustType  {
    case commonPushType
    case historyPushType
    case recordPushType
}

/*----可以简写如下
enum PustType  {
    case commonPushType, historyPushType, recordPushType
}
*/

///String类型
enum Week: Int{
    case MON, TUE, WED, THU, FRI, SAT, SUN
}

enum Season {
    case spring,summer,autumn,winter
}

///关联
enum Shape{
    case circle(radius: Double)
    case rectangle(width: Int, height: Int)
}

enum Code{
    case num(Int,Int,Int)
    case str(String,String)
}

class ViewController: UIViewController {
    
    var type : Shape?///常规用法 定义属性 外部传入
    override func viewDidLoad() {
        super.viewDidLoad()
      ///switch语句解析
        switch self.type {
        case .circle:
            print("the shape is circle")
        case .rectangle:
            print("the shape is rectangle")
        case .none:
            print("nil")
        }
        ///fuzhi
        let code = Code.str("A", "B")
        print(code)//str("A", "B")
        ///rawValue
        let week = Week(rawValue: 2)
        print(week ?? "nil")///WED
    }
 
}

可选项绑定

///举例一
let dic :Dictionary<String,String>? = ["key":"value"]
print(dic as Any) //Optional(["key": "value"])
//let value = dic["key"] ///报错 原因 dic为可选类型
if let dic = dic,let value = dic["key"] {
    print(dic)//["key": "value"]
    print(value)//value
}
///举例二
let adress: String? = "杭州"
    print(adress)//Optional("杭州")
if let adress = adress {
    print(adress)//杭州
}
///举例三
let a: Int? = 10
guard let value = a else {
    return
}
print(value)

guard语句

///可选项解包
let dictionary = ["name":"swift"]
let item = dictionary["name"]
print(item)///Optional("swift") 可选项 不能拿来用
guard let new = item else {
      return//不符合条件 直接返回 符合条件 继续执行下面的代码
}
print(new)///swift

if语句

let dic : Dictionary<String,String> = ["name":"Tom","age":"18","id":"60018"]
let name = dic["name"]
if name == "Tom" {
    print("找到了Tom")
}else if(name == "cat")
{
    print("找到了cat")
}else
{
    print("没找到了cat和Tom")
}

swich语句

///常规用法
let watch_id : Int? = 2
switch watch_id {
case 0:
    print("ID 为 0")
case 1:
    print("ID 为 1")
case 2,3:
    print("ID 为 2 或者 为3")
    fallthrough//贯穿 下一分支也执行
default:
    print("case")
}
///结合where
let somePoint = (1, -1)
switch somePoint {
    case let(x, y) where x == y:
       print("1")
    case let(x, y) where x == -y:
       print("2")
    case let(x, y):
       print("3")
}

三目运算符

//取a、b的最大值
let a = 20
let b = 30
let c = a > b ? a : b
print(c)///30

for语句

let array = ["健康","开心","气质","自信","富有","平安","长寿"]
for title in array {
    print(title)///逐个打印
}
let array_two : [Int] = [10, 20, 30]
for id in array_two {
    print( "index 的值为 \(id)")///逐个打印
}

属性

import UIKit

var allCan : String = "my_swif"///全局变量
class ViewController: UIViewController {
  ///1.存储属性是会占用当前实例对象的内存
    var age : Int = 18
    var nurse_userid : String?///定义属性
    ///2.计算属性 不会占用当前实例对象的内存
    var width: Double = 8.0
    var area: Double {
         get {
             return width * width
         }
         
         set (newValue){
             width = sqrt(newValue)
         }
     }
    
    var width_new: CGFloat {
        get { return self.view.frame.size.width }
        set { self.view.frame.size.width = newValue }
    }
    ///3.Lazy 属性 延迟存储在第一次访问的时候才被赋值
    lazy var ske_id : String = "60001"///注意:必须将延迟存储属性声明成变量(使用var关键字),因为属性的值在实例构造完成之前可能无法得到。而常量属性在构造过程完成之前必须要有初始值,因此无法声明成延迟属性。
    /*
     延迟存储必须有一个默认的初始值。
     延迟存储在第一次访问的时候才被赋值。
     延迟存储属性对实例对象的大小有影响。
     延迟存储属性不能保证线程安全。
    */
    ///4.类型属性 static 只被初始化一次
    static var weight: Int = 115
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.nurse_userid = "600028"
        print(self.age,self.nurse_userid ?? "123")///18 600028
        
        print("面积是:" +  "\(self.area)")
        print("屏幕宽度是:" + "\(self.width_new)")
        
        print(self.ske_id)//lazy 属性 60001
    }
}

属性监听器

var counter: Int = 0{
    willSet(newTotal){
        print("willSet: \(newTotal)")
    }
   didSet{
       if counter > oldValue {
            print("didSet \(counter - oldValue)")///减法操作
        }
    }
}
counter = 20
counter = 88
/*
willSet: 20
didSet 20
willSet: 88
didSet 68
*/