第22章:Foundation框架(707)

//程序目的:学习《从零开始学swift》
//第22章:Foundation框架
//Create By ChenZhen
//var intSwift = 80
//
//var intNumber = NSNumber(value: intSwift)
//var floatNumber = NSNumber(value: 80.0)
//
//let myInt = intNumber.intValue
//let myFloat = floatNumber.floatValue


//比较NSNumber对象
//var intSwift = 89
//var intNumber = NSNumber(value: intSwift)
//var floatNumber = NSNumber(value: 89.1)
//
//if intNumber.isEqual(to: floatNumber) {
//    NSLog("相等")
//} else {
//    NSLog("不相等")
//}
//
//switch intNumber.compare(floatNumber) {
//case .orderedAscending:
//    NSLog("第一个数小于第二个数")
//case .orderedSame:
//    NSLog("第一个数等于第二个数")
//case .orderedDescending:
//    NSLog("第一个数大于第二个数")
//}


//数字格式化
//let number = 123456789
//let formatter = NumberFormatter()
//
十进制数字
//formatter.numberStyle = .decimal
//var stringNumber = formatter.string(from: NSNumber(value: number))
//print("DecimalStyle: \(stringNumber!)")
//
科学计数法
//formatter.numberStyle = .scientific
//stringNumber = formatter.string(from: NSNumber(value: number))
//print("ScientificStyle: \(stringNumber!)")
//
百分数
//formatter.numberStyle = .percent
//stringNumber = formatter.string(from: NSNumber(value: number))
//print("PercentStyle: \(stringNumber!)")
//
货币
//for localId in ["en_US", "fr_FR", "zh_CN"] {
//    formatter.locale = NSLocale(localeIdentifier: localId) as Locale!
//
//formatter.numberStyle = .currency
//stringNumber = formatter.string(from: NSNumber(value: number))
//print("\(localId):Currency: \(stringNumber!)")
//
大写数字
//formatter.numberStyle = .spellOut
//stringNumber = formatter.string(from: NSNumber(value: number))
//print("Spellout: \(stringNumber!)")
//}


//NSNumber与Swift原生数字类型之间的桥接
//let number1 = 0
//let number2: NSNumber = NSNumber(value: number1)
//
//var number3 = 0
//number3 = number2 as Int


//字符串类
//var str1: NSString = "aBcDeFgHiJk"
//var str2: NSString = "12345"
//var res: NSString
//var compareResult: ComparisonResult
//var subRange: NSRange
//
字符数
//NSLog("字符串str1长度: %i", str1.length)
//
复制字符串到res
//res = NSString(string: str1)
//NSLog("拷贝: %@", res)
//NSLog("拷贝: \(res)")
//
复制字符串到str1的尾部
//str2 = str1.appending(str2 as String) as NSString
//NSLog("连接字符串: %@", str2)
//
测试字符串是否相等
//if str1.isEqual(to: res as String) {
//    NSLog("str1 == res")
//} else {
//    NSLog("str1 != res")
//}
//
测试字符串 < > ==
//compareResult = str1.compare(str2 as String)
//switch compareResult {
//    case .orderedAscending:
//        NSLog("str1 < str2")
//    case .orderedSame:
//        NSLog("str1 == str2")
//    case .orderedDescending:
//        NSLog("str1 > str2")
//}
//
//res = str1.uppercased as NSString
//NSLog("大写字符串: %@", res)
//
获得前三个数
//res = str1.substring(to: 3) as NSString
//NSLog("str1的前三个字符: %@", res)
//res = str1.substring(from: 4) as NSString
//NSLog("str1从索引4到尾部: %@", res)
//
字符串查找
//subRange = str2.range(of: "2")
//if subRange.location == NSNotFound {
//    NSLog("字符串没有找到")
//} else {
//    NSLog("找到的字符串索引 %i 长度是 %i", subRange.location, subRange.length)
//}
//NSLog("\(str2)")


//NSMutableString
//var str1: NSString = "Objective C"
//var search: NSString
//var replace: NSString
//
//var mstr: NSMutableString
//var subRange: NSRange
//
从不可变的字符创建可变字符串对象
//mstr = NSMutableString(string: str1)
//NSLog("%@", mstr)
//
插入字符串
//mstr.insert(" Java", at: 9)
//NSLog("%@", mstr)
//
具有连接效果的插入字符串
//mstr.insert(" and C++", at:mstr.length)
//NSLog("%@", mstr)
//
字符串连接方法
//mstr.append(" and C")
//NSLog("%@", mstr)
//
使用NSRange删除字符串
//mstr.deleteCharacters(in: NSMakeRange(16, 13))
//NSLog("%@", mstr)
//
查找字符串位置
//subRange = mstr.range(of: " Java")
//if subRange.location != NSNotFound {
//    mstr.deleteCharacters(in: subRange)
//    NSLog("%@", mstr)
//}
//
直接设置可变字符串
//mstr.setString("This is String A")
//NSLog("%@", mstr)
//mstr.replaceCharacters(in: NSMakeRange(8, 8), with: "Kobe")
//NSLog("%@", mstr)
//
查找和替换
//search = "This is "
//replace = "A example of "
//
//subRange = mstr.range(of: search as String)
//
//if subRange.location != NSNotFound {
//    mstr.replaceCharacters(in: subRange, with: replace as String)
//    NSLog(" %@", mstr)
//}
//
查找和替换所有情况
//search = "a"
//replace = "X"
//subRange = mstr.range(of: search as String)
//
//while subRange.location != NSNotFound {
//    mstr.replaceCharacters(in: subRange, with: replace as String)
//    subRange = mstr.range(of: search as String)
//}
//NSLog("%@", mstr)

//NSArray类
//let weeksArray = ["星期一", "星期二", "星期三","星期四", "星期五", "星期六", "星期日"]
//var weeksNames = NSArray(array: weeksArray)
//
//NSLog("星期名字")
//NSLog("==== ====")
//
//for i in 0 ..< weeksNames.count {
//    //var obj = weeksNames.object(at: i)
//    var obj = weeksNames[i]
//    var day = obj as! NSString
//    NSLog("%i    %@", i, day)
//}
//
//for item in weeksNames {
//    var day = item as! NSString
//    NSLog("%@", day)
//}

//NSMutableArray类
//var weeksNames: NSMutableArray = NSMutableArray(capacity: 3)
//
//weeksNames.add("星期一")
//weeksNames.add("星期二")
//weeksNames.add("星期三")
//weeksNames.add("星期四")
//weeksNames.add("星期五")
//weeksNames.add("星期六")
//weeksNames.add("星期日")
//
//NSLog("星期名字")
//NSLog("==== ====")
//
//for i in 0..<weeksNames.count {
//    var obj = weeksNames.object(at: i) as! NSString
//    NSLog("%i    %@", i, obj)
//}

//NSArray 与 Swift 原生数组之间的桥接
//let foundationString: NSString = "alpha bravo charlie delta echo"
//let array = foundationString.components(separatedBy: " ")
//let foundationArray = NSArray(array: array)
//
//let swiftArray: [String] = foundationArray as! [String]
//
//for item in foundationArray {
//    print(item)
//}
//print("")
//for item in swiftArray {
//    print(item)
//}

//NSDictionary类
//let keyString: NSString = "one two three four five"
//var keys = keyString.components(separatedBy: " ")
//
//let valueString: NSString = "alpha bravo charlie delta echo"
//var values = valueString.components(separatedBy: " ")
//
//var dict = NSDictionary(objects: values, forKeys: keys as [NSCopying])
//
//NSLog("%@", dict.description)    //description按升序将键值排列
//
//var value: NSString = dict.object(forKey: "three") as! NSString
//
//NSLog("three = %@", value)
//
//var allkeys = dict.allKeys
//for item in allkeys {
//    var key = item as! NSString
//    NSLog("%@-%@", key, dict.object(forKey: key) as! NSString)
//}

//NSMutableDictionary
//var mutable = NSMutableDictionary(capacity: 1)
//
//mutable.setObject("Tom", forKey: "chenzhen@qq.com" as NSCopying)
//mutable.setObject("Bob", forKey: "bob@qq.com" as NSCopying)
//
//NSLog("%@", mutable.description)
//
//var keys = mutable.allKeys
//for item in keys {
//    var key = item as! NSString
//    NSLog("%@-%@", key, mutable.object(forKey: key) as! NSString)
//}

//NSSet类
//var weeksArray: NSSet = ["星期一", "星期二", "星期三", "星期四"]
//weeksArray = weeksArray.adding("星期五") as NSSet
//weeksArray = weeksArray.addingObjects(from: ["星期六", "星期日"]) as NSSet
//
//var weeksNames = NSSet(set: weeksArray)
//
//for item in weeksNames {
//    var day = item as! NSString
//    NSLog("%@", day)
//}


//文件管理

//访问目录
//let path1  = FileManager.default.currentDirectoryPath
//print(path1)

//let fileManager = FileManager.default
//let path = fileManager.currentDirectoryPath
//print(path)

//目录操作
//let fileManager = FileManager.default
//let path = fileManager.currentDirectoryPath
//print(path)
在当前目录下创建/dir1/dir0目录
//let dir = path.appending("/dir1/dir0")
//
//do {
//    try fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil)
//    
//    if fileManager.fileExists(atPath: dir) {
//        try fileManager.removeItem(atPath: dir)//删除dir0目录
//    }
//} catch let err as NSError {
//    print(err.description)
//}

//let fileManager = FileManager.default
//let path = fileManager.currentDirectoryPath
//print(path)
//
//let dir = path.appending("/dir1")
//
//do {
//    try fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil)
//    let filePath = dir.appending("/test1.txt")
//    let content: NSString = "这是一个测试"
//    try content.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8.rawValue)
//    
//    let copyFilePath = dir.appending("/test2.txt")
//    
//    try fileManager.copyItem(atPath: filePath, toPath: copyFilePath)
//    
//    let copyFileContent = try NSString(contentsOfFile: copyFilePath, encoding: String.Encoding.utf8.rawValue)
//    
//    print("读取拷贝文件的内容: \(copyFileContent)")
//    
//    if fileManager.fileExists(atPath: copyFilePath) {
//        try fileManager.removeItem(atPath: copyFilePath)
//        print("删除test2.txt成功")
//    }
//} catch let err as NSError {
//    print(err.description)
//}


字节缓存
//let pngURL = "http://www.51work6.com/template/veikei_dz_com_20130920_color/images/logo.png"
//
//
//let fileManager = FileManager.default
//let path = fileManager.currentDirectoryPath
//print(path)
//
在当前目录下创建dir1目录
//let dir = path.appending("/dir1")
//
//do {
//    try fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil)
//    
//    let url = NSURL(string: pngURL)
//    
//    let data = NSData(contentsOf: url! as URL)
//    
//    //保存到本地文件路径
//    let pngFile = dir.appending("/logo.png")
//    data!.write(toFile: "pngFile", atomically: true)
//    
//    //NSString => NSData
//    let content1: NSString = "这是一个测试1!\n"
//    let data1 = content1.data(using: String.Encoding.utf8.rawValue)
//    let content2: NSString = "这是一个测试2!\n"
//    let data2 = content2.data(using: String.Encoding.utf8.rawValue)
//    
//    let dataOut = NSMutableData()
//    dataOut.append(data1!)
//    dataOut.append(data2!)
//    
//    let txtFile = dir.appending("/test.txt")
//    //将字节缓存写入文件
//    dataOut.write(toFile: txtFile, atomically: true)
//    
//    //NSData=>NSString
//    //从文件读取字节缓存
//    let dataIn = NSData(contentsOfFile: txtFile)
//    
//    let str = NSString(data: dataIn! as Data, encoding: String.Encoding.utf8.rawValue)
//    print("从文件读取内容: \n\(str!)")
//} catch let err as NSError {
//    print(err.description)
//}

Base64解码与编码
//let pngURL = "http://www.51work6.com/template/veikei_dz_com_20130920_color/images/logo.png"
//
//let url = NSURL(string: pngURL)
//let data = NSData(contentsOf: url! as URL)
//
//let base64EncodeString = data!.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn)
//
print(base64EncodeString)
//
//let fileManager = FileManager.default
//let path = fileManager.currentDirectoryPath
//print(path)
//
在当前目录下创建dir1目录
//let dir = path.appending("/dir1")
//
//do {
//    try fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil)
//    
//    //将Base64字符串转换为字节缓存数据
//    let decodedData = NSData(base64Encoded: base64EncodeString , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)
//    
//    let file = dir.appending("/logo.png")
//    decodedData!.write(toFile: file, atomically: true)
//} catch let err as NSError {
//    print(err.description)
//}

日期与时间
//let now = NSDate()
//let secondsPerDay: TimeInterval = 24 * 60 * 60
//
创建一个明天这一时刻对象
//let tomorrow = NSDate(timeIntervalSinceNow: secondsPerDay)
//print(tomorrow)
创建一个昨天这一时刻对象
//let yesterday = NSDate(timeIntervalSinceNow: secondsPerDay * -1)
//print(yesterday)
创建一个2001-01-01 00:00:00 UTC时刻对象
//let date2001 = NSDate(timeIntervalSinceReferenceDate: 0)
//print(date2001)
创建一个1970-01-01 00:00:00 UTC时刻对象
//let date1970 = NSDate(timeIntervalSince1970: 0)
//print(date1970)
//let date1 = tomorrow.earlierDate(now as Date) as NSDate
//let date2 = yesterday.laterDate(now as Date) as NSDate
//
//print(date1.isEqual(to: date2))
//
//switch date1.compare(date2 as Date) {
//    case .orderedAscending:
//        print("date1 > date2")
//    case .orderedSame:
//        print("date1 == date2")
//    case .orderedDescending:
//        print("date1 < date2")
//}

//let now = NSDate()
//print(now)
//
//let formatter = DateFormatter()
//formatter.dateFormat = "yyyy-MM-dd-EEE-aa HH:mm:ss Z"
//
//let dateString = formatter.string(from: now as Date)
//print(dateString)


使用NSCalendar 和 NSDateComponents类
创建NSDatecomponents对象
//let comps = NSDateComponents()

设置开幕时间是2016-8-5
设置NSDateComponents中的日期
//comps.day = 5
//comps.month = 8
//comps.year = 2016
//
创建日历对象
//let calender = NSCalendar(calendarIdentifier:
//        NSCalendar.Identifier.gregorian)
从日历中获得2016-8-5日期对象
//let destinationDate = calender!.date(from: comps as DateComponents)
//
//let now: NSDate = NSDate()
//
获得当前日期到2016-8-5的时间段的NSDateComponents对象
//let components = calender!.components(NSCalendar.Unit.day, from: now as Date, to: destinationDate!, options: [])
//
获得当前日期到2016-8-5相差的天数
//let days = components.day


时区转换
//let formatter = DateFormatter()
//formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//
//extension NSDate {
//    
//    var toLocalTime: String {
//        let timeZone = NSTimeZone.local
//        let seconds =
//            TimeInterval(timeZone.secondsFromGMT(for: self as Date))
//        
//        let date = NSDate(timeInterval: seconds, since: self as Date)
//        let dateString = formatter.string(from: date as Date)
//        
//        return dateString
//    }
//    
//    var toUTCTime: String {
//        let timeZone = NSTimeZone.local
//        let seconds = -1 *
//            TimeInterval(timeZone.secondsFromGMT(for: self as Date))
//        
//        let date = NSDate(timeInterval: seconds, since: self as Date)
//        let dateString = formatter.string(from: date as Date)
//        
//        return dateString
//    }
//}
//
//let birthdayString = "1973-12-08 20:53:21"
//var birthday = NSDate()
//birthday = formatter.date(from: birthdayString)! as NSDate
//
//print(birthdayString)
//print("UTC时间:\(birthday.toUTCTime)")
//print("本地时间:\(birthday.toLocalTime)")


//使用谓词NSPredicate过滤数据
//class Employee: NSObject {
//    var no: Int
//    var name: String
//    var job: String
//    var salary: Double
//    var hiredate: NSDate
//    var dept: Department
//    
//    init(no: Int, name: String, job: String, salary: Double,
//         hiredate: NSDate, dept: Department) {
//        self.no = no
//        self.name = name
//        self.job = job
//        //工资
//        self.salary = salary
//        //受雇日期
//        self.hiredate = hiredate
//        self.dept = dept
//    }
//    
//    convenience init(no: Int, name: String, job: String, salary: Double,
//                     hiredateString: String, dept: Department) {
//        
//        let formatter = DateFormatter()
//        formatter.dateFormat = "yyyy-MM-dd"
//        //字符串转化为NSDate
//        let date = formatter.date(from: hiredateString)
//        self.init(no: no, name: name, job: job, salary: salary,
//                  hiredate: date! as NSDate, dept: dept)
//    }
//}
//
//class Department: NSObject {
//    var no: Int
//    var name: String
//    //所在地
//    var location: String
//    
//    init(no: Int, name: String, location: String) {
//        self.no = no
//        self.name = name
//        self.location = location
//    }
//}
//
创建Department测试数据
//let dept1 = Department(no: 10, name: "ACCOUNTING", location: "NEW YORK")
//let dept2 = Department(no: 20, name: "RESEARCH", location: "DALLAS")
//let dept3 = Department(no: 30, name: "SALES", location: "CHICAGO")
//let dept4 = Department(no: 40, name: "OPERATIONS", location: "BOSTON")
//
创建Employee测试数据
//let emp1 = Employee(no: 7369, name: "SMITH", job: "CLERK", salary: 800, hiredateString: "2000-12-17", dept: dept2)
//let emp2 = Employee(no: 7499, name: "ALLEN", job: "SALESMAN", salary: 1600, hiredateString: "2001-02-20", dept: dept3)
//let emp3 = Employee(no: 7521, name: "WARD", job: "SALESMAN", salary: 1250, hiredateString: "2001-02-22", dept: dept3)
//let emp4 = Employee(no: 7566, name: "JONES", job: "MANAGER", salary: 2975, hiredateString: "2000-12-17", dept: dept2)
//let emp5 = Employee(no: 7654, name: "MARTIN", job: "SALESMAN", salary: 1250, hiredateString: "2000-02-04", dept: dept3)
//let emp6 = Employee(no: 7698, name: "BLAKE", job: "MANAGER", salary: 2850, hiredateString: "2001-05-01", dept: dept3)
//let emp7 = Employee(no: 7782, name: "CLARK", job: "MANAGER", salary: 2450, hiredateString: "2001-09-06", dept: dept1)
//let emp8 = Employee(no: 7788, name: "SCOTT", job: "ANALYST", salary: 3000, hiredateString: "2003-04-19", dept: dept2)
//let emp9 = Employee(no: 7839, name: "KING", job: "PRESIDENT", salary: 5000, hiredateString: "2000-08-09", dept: dept1)
//
//let emp10 = Employee(no: 7844, name: "TURNER", job: "SALESMAN", salary: 1500, hiredateString: "2004-09-17", dept: dept3)
//let emp11 = Employee(no: 7876, name: "ADAMS", job: "CLERK", salary: 1100, hiredateString: "2001-05-23", dept: dept2)
//let emp12 = Employee(no: 7900, name: "JAMES", job: "CLERK", salary: 950, hiredateString: "2001-09-17", dept: dept3)
//let emp13 = Employee(no: 7902, name: "FORD", job: "ANALYST", salary: 3000, hiredateString: "2000-01-12", dept: dept2)
//let emp14 = Employee(no: 7934, name: "MILLER", job: "CLERK", salary: 1300, hiredateString: "2001-01-23", dept: dept1)
//
//let arrayEmployees = [emp1,emp2,emp3,emp4,emp5,emp6,emp7,emp8,emp9,emp10,emp11,emp12,emp13,emp14]

//let oldFilteredArray1 = NSMutableArray()
//for emp in arrayEmployees {
//    if emp.salary < 1000 {
//        oldFilteredArray1.add(emp)
//    }
//}
//
//for item in oldFilteredArray1 {
//    let emp = item as! Employee
//    print("no: \(emp.no) name: \(emp.name) salary: \(emp.salary)")
//}
//let oldFilteredArray2 = NSMutableArray()
//for emp in arrayEmployees where emp.salary < 1000 {
//    oldFilteredArray2.add(emp)
//}
//
//for item in oldFilteredArray2 {
//    let emp = item as! Employee
//    print("no: \(emp.no) name: \(emp.name) salary: \(emp.salary)")
//}

//let salaryPredicate = NSPredicate(format: "salary < 1000")

使用NSMutableArray
//let filteredArray = NSMutableArray(array: arrayEmployees)
//filteredArray.filter(using: salaryPredicate)
//
//for item in filteredArray {
//    let emp = item as! Employee
//    print("no: \(emp.no) name: \(emp.name) salary: \(emp.salary)")
//}
//
使用NSArray
//let array = NSArray(array: arrayEmployees)
//let filteredArray1 = array.filtered(using: salaryPredicate)
//
使用NSSet
//let set = NSSet(array: arrayEmployees)
//let filteredSet = set.filtered(using: salaryPredicate)
//
使用NSMutableSet
//let mutableSet = NSMutableSet(array: arrayEmployees)
//mutableSet.filter(using: salaryPredicate)
//
//print("")
//
//let predicate = NSPredicate(format:"salary BETWEEN {2000, 2900}")
//
//let array1 = NSArray(array: arrayEmployees)
//let fil = array1.filtered(using: predicate)
//
//for item in fil {
//    let emp = item as! Employee
//    print("no: \(emp.no) name: \(emp.name) salary: \(emp.salary)")
//}

//let array = NSArray(array: arrayEmployees)
BEGINSWITH CONTAINS
//var predicate = NSPredicate(format: "job IN {'SALESMAN', 'MANAGER'}")
//var filter = array.filtered(using: predicate)
//
//for item in filter {
//    let emp = item as! Employee
//    print("no: \(emp.no) name: \(emp.name) salary: \(emp.salary)")
//}


在NSPredicate中使用正则表达式
//let pattern = "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$"//验证邮箱的正则表达式
//
//let predicate = NSPredicate(format: "SELF MATCHES %@", pattern)
//
//let aString = "1229383755@qq.com"
//
//if predicate.evaluate(with: aString) {
//    print("格式有效")
//} else {
//    print("格式无效")
//}


NSRegularExpression
//let pattern = "^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$"
//
//let aString = "1229383755@qqm"
//
//do {
//    let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
//    //创建一个范围,包含全部的字符串
//    let range = NSRange(location: 0, length: aString.characters.count)
//    
//    let result = regex.firstMatch(in: aString, options: .withoutAnchoringBounds, range: range)
//    if result != nil {
//        print("匹配")
//    } else {
//        print("不匹配")
//    }
//    
//    let number = regex.numberOfMatches(in: aString, options: .withoutAnchoringBounds, range: range)
//    if number > 0 {
//        print("匹配")
//    } else {
//        print("不匹配")
//    }
//} catch let err as NSError {
//    print(err.description)
//}

源代码:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值