BetaCat_HA
BetaCat_HA
Published on 2022-06-09 / 46 Visits
0
0

Swift基本语法

“随机”

random(in: lower … upper) or random(in: lower ..< upper) 
Int.random(in: 1…10) 		//从1到10随机取
Float.random(in: 1…10)
Double.random(in: 1…10)
Bool.random(in: 1…10)

randomElement()
arry.randomElement() 		//随机抽取数组“array”的元素

shuffle()
array.shuffle() 				//随机打乱数组“array”的元素

取范围方法

a…b    	//a<=范围<=b
a..<b   //a<=范围<b
…b      //范围<b

#colorLiteral()无法呼出的解决方法:用变量存储

var someColor = #colorLiteral(

解包UnWarp

示例文件位于:Swift ThinkingBootcamp

方法1: 使用if let

@State var displayText: String? = nil
...
if let text = displayText {
    //当text不为nil时,执行这段代码
}

方法2: 使用guard

@State var displayText: String? = nil
...
guard let text = displayText else {
    //text为nil时,执行这里的代码
    return
}
//当text不为nil时,往下执行

方法3: 使用??

@State var displayText: String? = nil
...
Text(displayText ?? "none")

数组Array

添加一系列数组的方法

var array: [String] = []
array.append(contentsOf: ["iPhone", "iPad", "iMac", "Apple Watch"])

通知Notification

获取权限

let options: UNAuthorizationOptions = [.alert, .sound, .badge]
UNUserNotificationCenter.current().requestAuthorization(options: options) { success, error in
    if let error = error {
        print("Error: \(error)")
    } else {
        print("Success: requestAuthorization")
    }
}

本地推送

时间触发

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false)

日历触发

var dateComponents = DateComponents()
dateComponents.hour = 23
dateComponents.minute = 35

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

位置触发

//设置经纬度
let coordinates = CLLocationCoordinate2D(
    latitude: 40.00,
    longitude: 50.00)

let region = CLCircularRegion(
    center: coordinates,
    radius: 100, //设置半径
    identifier: UUID().uuidString)
region.notifyOnEntry = true //进入时激活
region.notifyOnExit = false //离开时激活

let trigger = UNLocationNotificationTrigger(region: region, repeats: true)

添加通知

let request = UNNotificationRequest(
    identifier: UUID().uuidString,
    content: content,
    trigger: trigger)

UNUserNotificationCenter.current().add(request)

删除通知

//删除所有在等待推送队列中的通知
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
//删除所有已经推送到通知中心的消息
UNUserNotificationCenter.current().removeAllDeliveredNotifications()

Comment