参考网络教程(感谢资源)
// test.swift
// 开始
print("Hello world")
// 定义变量
var age = 25
age = 28
print("age: ",age)
// 定义常量
let const_age = 25
// age = 28 error
// 指定类型
var name:String = "hello world"
print(name)
// 字符串与数字结合
var player_nm = "curry"
var is_var:Bool = true
print(player_nm+" is "+String(is_var))// 字符串相加
print("\(player_nm) is \(is_var)")// 嵌入变量
// 创建数组
var my_list = ["curry","leborn","harden"]
print(my_list)
print(my_list[1])
// 追加球员
my_list.append("leonard")
print(my_list)
// 创建hash-map结构
var my_skills = [
"java":3,
"python":5,
"node":4
]
print(my_skills)
print(my_skills["python"] )
// 追加技能
my_skills["go"] = 2
print(my_skills)
// 要创建一个空数组或字典,请使用初始化程序语法
let my_empty_list = [String]()
let my_empty_dict = [String:Float]()
print(my_empty_list)
print(my_empty_dict)
// 使用for-in 循环数组my_list
for val in my_list {
print(val)
}
// 循环hash表
for skill in my_skills {
if skill.value >= 3 {
print("\(skill.key) is my gooding at.")
}else {
print("\(skill.key) is good skill.")
}
}
// 设置可以为空的(nil)的变量
var haha:Int? = 25
haha = nil //?代表Optional
if haha == nil {
print("haha is nil")
}else {
print("\(haha)")
}
// ??运算符
var fireball:String? = "火球"
var arrows = "万箭齐发"
print("对付骷髅海,首选的卡片是:\(fireball ?? arrows)")//如果??前者不为nil,前者
fireball = nil
print("对付骷髅海,首选的卡片是:\(fireball ?? arrows)")
// switch语法
var iris_p = 0
switch iris_p {
case 0:
print("山鸡")
case 1:
print("杂色鸡尾")
case 2:
print("维吉尼亚")
default:
print("这啥呀这是")
}
// 各种循环的写法
var i = 1
while i <= 5 {
print("i: ",i)
i+=1
}
var j = 0
repeat {
print("j: ",j)
j+=1
} while j <= 15
// 左闭右开
for k in 0..<3 {
print("k: ",k)
}
// 闭区间
for m in 0...3 {
print("m: ",m)
}
// 定义一个函数,参数,包括返回值
func say_hello(name:String)->String {
return "hello \(name)."
}
print(say_hello(name: "swift"))
// 定义一个返回元组的函数
func cal_math(x:Int,y:Int)->(plus:Int,minus:Int,mutil:Int,divide:Int){
return (x+y,x-y,x*y,x/y)
}
print(cal_math(x:20,y:30))
// 获取计算结果,逐个输出
let result = cal_math(x:20,y:10)
print(result.plus)
print(result.minus)
print(result.mutil)
print(result.divide)
// 嵌套定义函数
func add2(x:Int,y:Int)->Int{
func add()->Int{
return x + y
}
return add()
}
print(add2(x:100,y:2))
// 返回一个函数
func add_test()->((Int,Int)->Int){
func add(x:Int,y:Int)->Int{
return x + y
}
return add
}
var func_add = add_test()
print(func_add(10,20))
// 定义回调函数
func show_screen(threshold:Int,cb:(String)->Void/*回调函数*/){
print("show_screen: ",threshold)
cb("hello u.")
}
func screen_cb(screen_data:String)->Void{
print("screen_data is ",screen_data)
}
show_screen(threshold:100,cb:screen_cb)
// 闭包的使用,就是匿名函数
var numbers = [1,2,3,4,5]
var num_list = numbers.map({(number:Int)->Int in
return number * number
})
print(num_list)
// 正规的写法
func power2(number:Int)->Int{
return number * number
}
num_list = numbers.map(power2)
print(num_list)
// 简单的写法
num_list = numbers.map({number in number * number})
print(num_list)
// 排序闭包
num_list = numbers.sorted{$0 > $1} //注意是 `{ }`
print(num_list)
// 面向对象
class Player {
var score = 0
init(score:Int){
self.score = score
}
func player_level()->String {
if self.score >= 30 {
return "MVP"
}else if self.score >= 20 {
return "球星"
}else if self.score >= 10 {
return "首发"
}else {
return "板凳"
}
}
}
var player = Player(score:25)
print(player.player_level())
// 类继承,方法重载
class NBAPlayer:Player{
override func player_level()->String{
if self.score >= 15 {
return "交易过来"
}else {
return "交易出去"
}
}
}
var nab_player = NBAPlayer(score:23)
print(nab_player.player_level())
// 定义getter和setter
class Circle{
// 半径属性,默认public
var radius:Float = 0
init(radius:Float){
self.radius = radius
}
// 面积属性
var area:Float {
get{
return 3.14 * self.radius
}
set{
self.radius = newValue / 3.14 //newValue在这里相当于特殊字符
}
}
}
var cicle = Circle(radius:10)
print(cicle.area)
// 传入面积后,自动计算半径长度
cicle.area = 62.8
print(cicle.radius)
// 枚举和结构
enum Lang {
case java
case python
case javascript
case typescript
case go
case vb
case ruby
case php
}
let my_lang = Lang.java
switch my_lang {
case Lang.python:
print("机器学习必备")
case Lang.java:
print("老牌健壮的web大哥")
case Lang.go:
print("并发超强")
default:
print("很不错的语言,特性有意思")
}
// 枚举的自描述方法
enum ELang {
case java
case python
case go
case ruby
case cpp
// 枚举类型下的方法
func desc(){
switch self {
case .python:
print("机器学习必备")
case .java:
print("机构大哥大")
case .cpp:
print("不要用垃圾语言和c++比")
default:
print("傻逼语言")
}
}
}
let my_cpp = ELang.cpp
my_cpp.desc()
// 枚举的参数
enum HttpResponse {
// 成功返回代码
case success(Int)
// 错误返回信息
case failure(String)
}
let succ = HttpResponse.success(200)
let result = HttpResponse.failure("数据库访问失败")
switch result{
case let .success(code):
print("请求成功")
case let .failure(message):
print("请求失败")
}
// 定义结构体,全是字段
struct LoginForm {
var uid:String
var pwd:String
var authorized_code:String
}
let user1 = LoginForm(uid:"komavideo",pwd:"iloveu",authorized_code:"12345678")
print(user1)
// 协议和扩展
// 定义一个协议(接口,每个实现接口的类,必须实现接口的属性(赋值)和方法(重写))
protocol IDatabase {//多数据库产品模式
var dbname:String{get set}
func exeSql(sql:String)->Int
mutating func upgrade(dbname:String)
}
// PostgreSql实现接口
class PostgreSql:IDatabase{
var dbname:String = "postgre"
func exeSql(sql:String)->Int{
print("Postgre执行Sql: ",sql)
return 100
}
func upgrade(dbname:String){
self.dbname = dbname
}
}
// Mysql
class MySql:IDatabase{
var dbname:String = "mysql"
func exeSql(sql:String)->Int{
print("MySql执行Sql: ",sql)
return 200
}
func upgrade(dbname:String){
self.dbname = dbname
}
}
let db1 = PostgreSql()
var ret1 = db1.exeSql(sql:"SELECT * FROM TABLES")
db1.upgrade(dbname:"PostgreSql 12.4")
print(db1.dbname)
let db2 = MySql()
var ret2 = db2.exeSql(sql:"DESC TABLES")
db2.upgrade(dbname:"MySql 8.0.21")
print(db2.dbname)
// 扩展PostgreSql类,添加新功能
// 追加新函数
extension PostgreSql {
func batchExeSql(sql:[String])->Int{
print("批处理Sql: ",sql)
return 300
}
}
let db3 = PostgreSql()
db3.batchExeSql(sql:["BEGIN TRANSACTION...","UPDATE TABLE SET ..."])
// 错误处理
// 错误枚举
enum DatabaseError:Error{
case db_error
case sql_error
case network_error
}
// 定义一个抛出异常的方法
func exeSqlCom(sql:String?/*可nil*/) throws -> Int {
if sql == nil {
throw DatabaseError.sql_error
}
return 1
}
// 捕捉异常
do {
try exeSqlCom(sql:nil)
}catch DatabaseError.sql_error{
print("sql出错")
}
// try? 捕捉,我不理解??
let db_result = try? exeSqlCom(sql:nil)
print(db_result)