MyPlayground

##乱七八糟的基础知识测试

//: Playground - noun: a place where people can play


import UIKit
import Foundation





// +++++++++++++++++++++++ 字典,值传递

// +++++++++++++++++++++++ Range
let r = Range(0..<3) //old: let _ = NSRange(location: 0, length: 3)

// +++++++++++++++++++++++ 遍历数组
let arr = [1,3,5,2,4,6]
// 遍历数组
for (index,value) in arr.enumerated() {
    print("\(index) - \(value)") // 下标 - item
}
// 遍历数组
for item in arr {
    print(item)// 1    3    5    2    4    6
}
// 反向遍历数组
for item in arr.reversed(){
    print(item)// 6    4    2    5    3    1
}

// +++++++++++++++++++ 正则表达式 密码强度校验
//要求密码长度最少12位,包含至少1个特殊字符,2个数字,2个大写字母和一些小写字母。: (?=^.{12,25}$)(?=(?:.*?\d){2})(?=.*[a-z])(?=(?:.*?[A-Z]){2})(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&]*$
//纯数字:          ^\d+$
//纯字母:          ^[a-zA-Z]+$
//纯特殊字符:       ^[@#$%^&]+$  ps:特殊字符看你定义的标准是什么
//字母+数字:        ^(?!\d+$)(?![a-zA-Z]+$)[a-zA-Z\d]+$
//字母+特殊字符:     ^(?![a-zA-Z]+$)(?![@#$%^&]+$)[a-zA-Z@#$%^&]+$
//数字+特殊字符:      ^(?!\d+)(?![@#$%^&]+$)[\d@#$%^&]+$
//字母+数字+特殊字符: ^(?!\d+$)(?![a-zA-Z]+$)(?![@#$%^&]+$)[\da-zA-Z@#$%^&]+$

do{
    let pattern: String = "^(?!\\d+$)(?![a-zA-Z]+$)(?![@#$%^&]+$)[\\da-zA-Z@#$%^&]+$"
    let input: String  = "123qwe"
    let regex: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
    
    let match = regex.matches(
        in: input,
        options: NSRegularExpression.MatchingOptions.reportProgress,
        range: NSRange(location: 0, length: (input as NSString).length)
    )
    match.count
}catch let err{
    print("err \(err)")
}


// +++++++++++++++  while 1=白色,0=黑色; alpha 1=不透明,0=透明
UIColor(white: 0, alpha: 0.7)


// +++++++++++++++++++++ AnyObject.integerValue
let a:[String:AnyObject] = ["a":"-123a","b":123]
a["a"]?.integerValue // -123
a["a"] as? Int // nil


// +++++++++++++++++++++ 根据日期,获取星期
let dateFmt = NSDateFormatter()
dateFmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFmt.dateFromString("2016-09-03 12:12:12")
date?.description
let interval = Int(date!.timeIntervalSince1970) + NSTimeZone.localTimeZone().secondsFromGMT
let days = Int(interval/86400) // 24*60*60
let weekday = ((days + 4)%7+7)%7
weekday == 0 ? 7 : weekday
let week = (days - 3) % 7;

// +++++++++++++++++++++++ String ---> Array
let str = "1,2,3,4,5,6"
let arr = str.componentsSeparatedByString(",")
// ++++++++ String.substring
let a = str.rangeOfString("4,")

// ++++++++++++++++++++++++ 时间戳 ---> 星期
let interval = NSDate().timeIntervalSince1970
let days = Int(interval / (60*60*24));
let week2 = ((days + 4)%7+7)%7
let week = (days - 3) % 7;

// ++++++++++++++++++++++++++ String / Int ---> Bool
let  a = "true"
a.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
a.characters
a.characters.count
Bool(13)
a as? Bool

// ++++++++++++++++++++++++ String 转换为 Array dictionary
let str:String = "[{\"url\":\"http://123/1435910039433019072_lite.jpg\"}]"
let data = str.dataUsingEncoding(NSUTF8StringEncoding)
let any = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
let arr = any as! NSArray
let dict = arr.firstObject as! NSDictionary

// ++++++++++++++++++++++++ 秒 转换为 时间长度
// 天 时 分 秒
var timeInterval = (60*60*24*2) + (60*60*5) + (60*3) + (20)
// 时间戳 --> 分钟
var dateStr = ""
if timeInterval >= 60*60*24 {
    let v = timeInterval / (60*60*24)
    timeInterval -= (60*60*24) * v
    dateStr += "\(v)天"
}
if timeInterval >= 60*60 {
    let v = timeInterval / (60*60)
    timeInterval -= (60*60) * v
    dateStr += "\(v)小时"
}
if timeInterval >= 60 {
    let v = timeInterval / (60)
    timeInterval -= (60) * v
    dateStr += "\(v)分"
}
dateStr += "\(timeInterval)秒"
print("\(dateStr)") // 2天5小时3分20秒
//时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
//获取当前时间
let now = NSDate()
// 创建一个日期格式器
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
print("当前日期时间:\(fmt.stringFromDate(now))")
//当前时间的时间戳
let timeInterval:NSTimeInterval = now.timeIntervalSince1970
let timeIntervalInt = Int(timeInterval)
print("当前时间的时间戳:\(timeIntervalInt)  ++  \(timeInterval)")
//将时间戳转为日期时间
let date = NSDate(timeIntervalSince1970: timeInterval)
print("对应的日期时间:\(fmt.stringFromDate(date))")
// 当前时间, 60*60(1小时)后的时间
let otherDate = NSDate(timeInterval: 60*60, sinceDate: now)
print("1小时后 日期时间:\(fmt.stringFromDate(otherDate))")
// 时间戳
// 晚 timeIntervalSinceDate 早 === 晚 - 早 === 正数 === 间隔秒钟
let difference = otherDate.timeIntervalSinceDate(now)
print("间隔秒钟:\(difference)")

// +++++++++++++++++++++ 字典 转 json str
let dict:[String:AnyObject] = ["a":"1:2:3","b":456,"c":"789c"]
var data = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
let jsonDict = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
var jsonStr = String(data: data, encoding: NSUTF8StringEncoding)!
jsonStr = jsonStr.stringByReplacingOccurrencesOfString("\n", withString: "")
print(dict)
print(jsonDict)
print(jsonStr)
// json ---> data ---> anyObject
data = jsonStr.dataUsingEncoding(NSUTF8StringEncoding)!
var any = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
print("AllowFragments +++++ \(any)")
any = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
print("MutableContainers +++++ \(any)")
any = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves)
print("MutableLeaves +++++ \(any)")

// ++++++++++++++++++++++ 数组转json
// 字典
let d:[String:AnyObject] = ["a":"1:2:3","b":456]
print(d.description) // ["b": 456, "a": 1:2:3]

// 字典型数组 转  json  无法处理 1:2:3
var arr = [[String:AnyObject]]()
arr.append(d)
arr.append(d)
print(arr.description) // [["b": 456, "a": 1:2:3], ["b": 456, "a": 1:2:3]]

// 字符串数组 转 json  无法处理 1:2:3   多了  “”
var strArr = [String]()
strArr.append(d.description)
strArr.append(d.description)
print(strArr.description) // ["[\"b\": 456, \"a\": 1:2:3]", "[\"b\": 456, \"a\": 1:2:3]"]

// AnyObject Array 多了 \n 换行
var anyArr = [AnyObject]()
// dict --> data --> string
let j = try! NSJSONSerialization.dataWithJSONObject(d, options: NSJSONWritingOptions.PrettyPrinted)
let s = String(data: j, encoding: NSUTF8StringEncoding)!
anyArr.append(s)
anyArr.append(s)
var result = anyArr.description
result = result.stringByReplacingOccurrencesOfString("\n", withString: "")
print(result) // [{  "b" : 456,  "a" : "1:2:3"}, {  "b" : 456,  "a" : "1:2:3"}]

// +++++++++++++++++ 前缀后缀
let a = "asdf1234\n778\n7641]789"
a.hasPrefix("a")
a.hasSuffix("]")

// ++++++++++++++++++++ 替换字符
var a = "   1 11    2   3\t222"
print(a)
var b = a
b = a.stringByReplacingOccurrencesOfString("\t", withString: "")
print(b)
b = a.stringByReplacingOccurrencesOfString(" ", withString: "")
print(b)
b = a.stringByReplacingOccurrencesOfString("    ", withString: "")
print(b)

// +++++++++++++++++ 字典转字符串
let d:[String:AnyObject]=["a":"aaaa","b":"bb"]
var s = d.description
print(s)
// +++++++++++++++++ 数组转字符串
let a  = ["a","b","c"]
s = a.description
print(s)

//+++++++++++++++++++++ guard let 测试
func a(){
    let d:[String:AnyObject]=["a":"aaaa","b":"bb"]
    guard let a = d["a"] as? String where false else{
        print(11)
        return
    }
    
    print(a)
}
a()

//+++++++++++++++++++++++++ 当前时间
let format = NSDateFormatter()
format.dateFormat = "yyyy MM dd HH mm ss SSS"
format.stringFromDate(NSDate())

// +++++++++++++++++++++++++ 引用传递,改一个对象,影响到所有引用该对象的地方
class A{
    var a = 10
}
class B{
    var aA:A?
}
let a = A()
let b = B()

b.aA?.a
b.aA = a

let c = b.aA!

a.a
b.aA?.a
c.a

a.a = 20
a.a
b.aA?.a
c.a


b.aA?.a = 30
a.a
b.aA?.a
c.a

c.a = 40
a.a
b.aA?.a
c.a
// ++++++++++++++++++++++++++++++++++ string <---> int
let a:[String:AnyObject] = ["a":"123" , "b":123]
a["a"]?.integerValue
a["a"] as? Int
a["b"] as? String
String(a["b"] as! Int)

// +++++++++++++++++++++++++++++++++ int - string - data - string - int
let a = 123
let b = "\(a)"
let c = b.dataUsingEncoding(NSUTF8StringEncoding)!
let d = String(data: c, encoding: NSUTF8StringEncoding)!
let f = Int("123")

// +++++++++++++++++++++++++++++++++++ timeIntervalSinceDate
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd hh:mm"
let d1 = fmt.dateFromString("2016-06-12 11:12")
let d2 = fmt.dateFromString("2016-06-12 11:14")
d1?.timeIntervalSinceDate(d2!)
d2?.timeIntervalSinceDate(d1!)

// ++++++++++++++++++++++++++++++++++++++++
class B {
    var b = 123
}
let a = B()
let b = a

a.b
b.b

a.b = 345

a.b
b.b

b.b = 789

b.b
a.b

// ++++++++++++++++++++++++++++++++++++++++++++

//将解析的更新人员数据批量同步到数据库
+(void)operateCompUsers:(NSMutableArray*)operateCompUsers
{
    sqliteHelper *mysqlite = [[sqliteHelper alloc]init];
    if (operateCompUsers.count<=0) return;
    if([mysqlite openDatabase:@"ucab_db.db"])
    {
        NSMutableArray *transactionSql= [[NSMutableArray alloc]init];
        for (int i=0; i<operateCompUsers.count; i++)
        {
            CompUser *operateCompUser = [operateCompUsers objectAtIndex:i];
            
            if ([operateCompUser.operateType isEqualToString:@"0"])   //删除
            {
                NSString *nsstrSql = [[NSString alloc]initWithFormat:@"%@%@%@",@"delete from cloud_contacts where uid='",operateCompUser.uId,@"'"];
                
                [mysqlite execSql:nsstrSql];
            }
            if ([operateCompUser.operateType isEqualToString:@"1"])   //可用,新增数据
            {
                //先将数据库中的数据删除
                NSString *nsstrSql = [[NSString alloc]initWithFormat:@"%@%@%@",@"delete from cloud_contacts where uid='",operateCompUser.uId,@"'"];
                [mysqlite execSql:nsstrSql];
                
                //再添加一次
                if (nil==operateCompUser.uId) operateCompUser.uId=@"";
                if (nil==operateCompUser.cn) operateCompUser.cn=@"";
                if (nil==operateCompUser.telephoneNumber) operateCompUser.telephoneNumber=@"";
                if (nil==operateCompUser.departmentNumber) operateCompUser.departmentNumber=@"";
                if (nil==operateCompUser.deptName) operateCompUser.deptName=@"";
                if (nil==operateCompUser.coNo) operateCompUser.coNo=@"";
                if (nil==operateCompUser.coName) operateCompUser.coName=@"";
                if (nil==operateCompUser.cuOrder) operateCompUser.cuOrder=@"";
                if (nil==operateCompUser.mobile) operateCompUser.mobile=@"";
                if (nil==operateCompUser.cuMail) operateCompUser.cuMail=@"";
                if (nil==operateCompUser.cuAllShow) operateCompUser.cuAllShow=@"";
                if (nil==operateCompUser.cuEntryStatus) operateCompUser.cuEntryStatus=@"";
                if (nil==operateCompUser.imagePath) operateCompUser.imagePath=@"";
                if (nil==operateCompUser.sort) operateCompUser.sort=@"";
                if (nil==operateCompUser.duty) operateCompUser.duty=@"";
                if (nil==operateCompUser.sex) operateCompUser.sex=@"0";  //性别默认为男
                
                //组sql语句
                NSString *strSql = [NSString stringWithFormat:@"insert into cloud_contacts (uid,cn,telephoneNumber,departmentNumber,deptName,coNo,coName,cuOrder,mobile,cuMail,cuAllShow,cuEntryStatus,imagePath,sort,duty,sex) values ('%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@');",operateCompUser.uId,operateCompUser.cn,operateCompUser.telephoneNumber,operateCompUser.departmentNumber,operateCompUser.deptName,operateCompUser.coNo,operateCompUser.coName,operateCompUser.cuOrder,operateCompUser.mobile,operateCompUser.cuMail,operateCompUser.cuAllShow,operateCompUser.cuEntryStatus,operateCompUser.imagePath,operateCompUser.sort,operateCompUser.duty,operateCompUser.sex];
                
                [transactionSql addObject:strSql];
            }
        }
        [mysqlite execInsertTransactionSql:transactionSql];
        [mysqlite closeDatabase];
    }
}//执行插入事务语句
-(void)execInsertTransactionSql:(NSMutableArray *)transactionSql
{
    //使用事务,提交插入sql语句
    @try{
        char *errorMsg;
        if (sqlite3_exec(database, "BEGIN", NULL, NULL, &errorMsg)==SQLITE_OK)
        {
            NSLog(@"启动事务成功");
            sqlite3_free(errorMsg);
            sqlite3_stmt *statement;
            for (int i = 0; i<transactionSql.count; i++)
            {
                if (sqlite3_prepare_v2(database,[[transactionSql objectAtIndex:i] UTF8String], -1, &statement,NULL)==SQLITE_OK)
                {
                    if (sqlite3_step(statement)!=SQLITE_DONE)
                    sqlite3_finalize(statement);
                }
            }
            if (sqlite3_exec(database, "COMMIT", NULL, NULL, &errorMsg)==SQLITE_OK)   NSLog(@"提交事务成功");
            sqlite3_free(errorMsg);
        }
        else sqlite3_free(errorMsg);
    }
    @catch(NSException *e)
    {
        char *errorMsg;
        if (sqlite3_exec(database, "ROLLBACK", NULL, NULL, &errorMsg)==SQLITE_OK)  NSLog(@"回滚事务成功");
        sqlite3_free(errorMsg);
    }
    @finally{}
}


// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/**
 1. 打开数据库
 2. 如果没有数据表,需要首先创表
 3. 数据操作
 */
class SQLite {
    var db: COpaquePointer = nil
    ///  打开数据库
    ///
    ///  :param: dbname 数据库名称
    ///
    ///  :returns: 是否打开成功
    func openDatabase(dbname: String) -> Bool {
        // UnsafePointer<Int8> UnsafePointer<CChar>
        // 对应C语言中的 char*
        // filename 必须是完整的路径名
        let path = dbname.documentPath()
        println(path)
        // sqlite3_open 如果如果数据库不存在,会新建数据库文件
        // 如果数据库文件已经存在,就直接打开,返回句柄,不会对数据有任何影响
        if sqlite3_open(path, &db) == SQLITE_OK {
            println("打开数据库成功")
            // 本质上只需要运行一次就可以了
            if createTable() {
                println("创表成功")
                // TODO: 测试查询数据
                let sql = "SELECT id, DepartmentNo, Name FROM T_Department;"
                recordSet(sql)
            } else {
                println("创表失败")
            }
        } else {
            println("打开数据库失败")
        }
        return false
    }
    ///  创建数据表,将系统需要的数据表,一次性创建
    private func createTable() -> Bool {
        // 准备所有数据表的 SQL
        // 1> 每一个 SQL 完成后都有一个 ;
        // 2> 将所有创表 SQL 写在一起,每一个换行添加一个 \n
        let sql = "CREATE TABLE \n" +
            "IF NOT EXISTS T_Department (\n" +
            "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
            "DepartmentNo CHAR(10) NOT NULL DEFAULT '',\n" +
            "Name CHAR(50) NOT NULL DEFAULT '' \n" +
            "); \n" +
            "CREATE TABLE IF NOT EXISTS T_Employee ( \n" +
            "'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \n" +
            "'name' TEXT NOT NULL, \n" +
            "'age' INTEGER NOT NULL, \n" +
            "'department_id' INTEGER, \n" +
            "CONSTRAINT 'FK_DEP_ID' FOREIGN KEY ('department_id') REFERENCES 'T_Department' ('id') \n" +
        ");"
        return execSQL(sql)
    }
    ///  执行没有返回值的 SQL 语句
    ///
    ///  :param: sql SQL 字符串
    ///
    ///  :returns: 是否成功
    func execSQL(sql: String) -> Bool {
        /**
         1. 数据库指针
         2. SQL 字符串的 C 语言格式
         3. 回调,执行完成 SQL 指令之后的函数回调,通常都是 nil
         4. 回调的第一个参数的指针
         5. 错误信息,通常也传入 nil
         */
        return sqlite3_exec(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, nil, nil, nil) == SQLITE_OK
    }
    ///  执行 SQL 返回一个结果集(对象数组)
    ///
    ///  :param: sql SQL 字符串
    func recordSet(sql: String) {
        // 1. 准备语句
        var stmt: COpaquePointer = nil
        /**
         1. 数据库句柄
         2. SQL 的 C 语言的字符串
         3. SQL 的 C 语言的字符串长度 strlen,-1 会自动计算
         4. stmt 的指针
         5. 通常传入 nil
         */
        if sqlite3_prepare_v2(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, -1, &stmt, nil) == SQLITE_OK {
            // 单步获取SQL执行的结果 -> sqlite3_setup 对应一条记录
            while sqlite3_step(stmt) == SQLITE_ROW {
                // 获取每一条记录的数据
                recordData(stmt)
            }
        }
    }
    ///  获取每一条数据的记录
    ///
    ///  :param: stmt prepared_statement 对象
    func recordData(stmt: COpaquePointer) {
        // 获取到记录
        var count = sqlite3_column_count(stmt)
        println("获取到记录,共有多少列 \(count)")
        // 遍历每一列的数据
        for i in 0..<count {
            let type = sqlite3_column_type(stmt, i)
            // 根据字段的类型,提取对应列的值
            switch type {
            case SQLITE_INTEGER:
                println("整数 \(sqlite3_column_int64(stmt, i))")
            case SQLITE_FLOAT:
                println("小树 \(sqlite3_column_double(stmt, i))")
            case SQLITE_NULL:
                println("空 \(NSNull())")
            case SQLITE_TEXT:
                let chars = UnsafePointer<CChar>(sqlite3_column_text(stmt, i))
                let str = String(CString: chars, encoding: NSUTF8StringEncoding)!
                println("字符串 \(str)")
            case let type:
                println("不支持的类型 \(type)")
            }
        }
    }
}





// willSet +++++++++++++++++++++++
var a:Int? {
willSet{
    print("willSet \(a) \t \(newValue)")
}
didSet{
    print("didSet \(a) \t \(oldValue)")
}
}
a = 1

// gcd ++++++++++++++++++++++++++
class GCDDemo{
    // 1 5 2 4 3
    func method1(){
        print("\(#function) 1")
        
        weak var weakSelf = self
        let queue:dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        dispatch_async(queue) {
            print("\(#function) 2")
            weakSelf!.method2()
            //            dispatch_async(dispatch_get_main_queue(), {
            print("\(#function) 3")
            //            })
            print("\(#function) 4")
        }
        print("\(#function) 5")
    }
    
    // 1 5 2 4 3
    func method2(){
        print("\(#function) 1")
        let queue:dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        dispatch_async(queue) {
            print("\(#function) 2")
            //            dispatch_async(dispatch_get_main_queue(), {
            print("\(#function) 3")
            //            })
            print("\(#function) 4")
        }
        print("\(#function) 5")
    }
}

let c = GCDDemo()
c.method1()

// lazy +++++++++++++
class A{
    init(){
        print("init a")
    }
    deinit{
        print("deint a")
    }
}
class B{
    lazy var a = A()
    init(){
        print("init b")
    }
    func bb(){
        print("B \(#function)")
        a
    }
}

var b:B? = B()
b!.bb()
b = nil

// ++++++++++++++++++++++
class A{
    init(){
        print("init a")
    }
    deinit{
        print("deint a")
    }
}
class B{
    var a:A?
    init(){
        print("init b")
    }
    deinit{
        print("deint b")
    }
}

var a:A? = A()
var b:B? = B()
b?.a = a
b!.a
a=nil
b=nil



// ---------------------------
class Test{
    var a:String {
        willSet {
            print("a willset \(newValue)")
        }
        didSet{
            print("a didSet \(oldValue) \(a)")
            f()
        }
    }
    var b:CGFloat
    
    init(a:String,b:CGFloat){
        self.a = a
        self.b = b
        
        f()
    }
    
    func f(){
        print("f a = \(a)")
        b = 100
    }
}

let t = Test(a: "abc", b: 123)
t.a
t.b
t.a = "qwe"
t.a
t.b





转载于:https://my.oschina.net/asjoker/blog/795322

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值