• Swift提供了两种特殊的类型:Any、AnyObject Any:可以代表任意类型(枚举、结构体、类,也可以包括函数类型) 范围更广,代表除函数外任何类型的实例。不仅包含object对象,还包含基本类型。 AnyObject:可以代表...

    关键字Any、AnyObject

    • Swift提供了两种特殊的类型:Any、AnyObject

    Any:可以代表任意类型(枚举、结构体、类,也可以包括函数类型)
    范围更广,代表除函数外任何类型的实例。不仅包含object对象,还包含基本类型。
    AnyObject:可以代表任意类类型(在协议后面写上:AnyObject代表只有类能遵守这个协议)
    代表任何class类型的对象实例


    关键字is、as?、as!、as

    • Swift提供了两种特殊的类型:Any、AnyObject
    • is用来判断是否为某种类型,as用来做强制类型转换
            protocol Runnable { func run() }
            class Person {}
            class Student : Person, Runnable {
                func run() {
                    print("student run")
                }
                func study() {
                    print("student study")
                }
            }
    
        var stu: Any = 10
        print(stu is Int) //true
        stu = "Jack"
        print(stu is String) //true
        stu = Student()
        print(stu is Person) //true
        print(stu is Student) //true
        print(stu is Runnable) //true
    
        var stu: Any = 10
        (stu as? Student)?.study() //没有调用study
        stu = Student()
        (stu as? Student)?.study() //student study
        (stu as! Student).study()  //student study
        (stu as? Runnable)?.run()  //student run
    
        var data = [Any]()
        data.append(Int("123") as Any)
    
        var d = 10 as Double
        print(b)  //10.0在这里插入代码片
    

    关键字X.self、X.Type、AnyClass

    • X.self是一个元类型(metadata)的指针,metadata存放着类型相关信息
    • X.self属于X.Type类型
    class Person {}
    class Student : Person {}
    var perType: Person.Type = Person.self
    var stuType: Student.Type = Student.self
    perType = Student.self
    
    var anyType: AnyObject.Type = Person.self
    anyType = Student.self
    
    public typealias AnyClass = AnyObject.Type
    var anyType2: AnyClass = Person.self
    anyType2 = Student.self
    
    var per = Person()
    var perType = type(of:per)  //Person.self
    print(Person.self == type(of:per))  //true
    

    应用:父类必须用required修饰初始化器,保证子类也有对应的初始化器

    class Animal { required init() {} }  
    class Cat : Animal {}
    class Dog : Animal {}
    class Pig : Animal {}
    func create(_ clses: [Animal.Type]) -> [Animal] {
        var arr = [Animal]()
        for cls in clses {
            arr.append(cls.init())
        }
        return arr
    }
    print(create([Cat.self, Dog.self, Pig.self]))
    

    runtime:swift还有一个隐藏的基类:Swift_SwiftObject

    class Person {}
    class Student : Person {}
    class_getInstanceSize(Person.self)
    class_getSuperclass(Person.self)  //
    class_getSuperclass(Student.self)
    

    关键字Self

    • Self一般用作返回值类型,限定返回值跟方法调用者必须是同一类型(也可以作为参数类型)
    protocol Runnable {
        func test() -> Self
    }
    class Person : Runnable {
        required init() {}
        func test() -> Self { type(of:self).init() }
    }
    class Student: Person { }
    
    var p = Person()
    print(p.test()) //Person
    var stu = Student()
    print(stu.test()) //Student
    

    如果Self用在类中,要求返回时调用的初始化器是required

    展开全文
  • 这是Dictionary转Data 的方法 源码: func jsonToData(jsonDic:Dictionary<String, Any>) -> Data? { if (!JSONSerialization.isValidJSONObject(jsonDic)) { print("is not a valid json object") ....

    这是Dictionary转Data 的方法

    源码:

    func jsonToData(jsonDic:Dictionary<String, Any>) -> Data? {
    
        if (!JSONSerialization.isValidJSONObject(jsonDic)) {
    
            print("is not a valid json object")
    
            return nil
    
    }
    
        //利用自带的json库转换成Data
    
        //如果设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读
    
        let data = try? JSONSerialization.data(withJSONObject: jsonDic, options: [])
    
        //Data转换成String打印输出
    
        let str = String(data:data!, encoding: String.Encoding.utf8)
    
        //输出json字符串
    
        print("Json Str:\(str!)")
    
        return data
    
    }
    
    复制代码

    这是Data转Dictionary, 上面是首先判断能否转换成功,下面用的do catch。

    源码:

    func dataToDictionary(data:Data) ->Dictionary<String, Any>?{
    
        do{
    
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    
            let dic = json as! Dictionary<String, Any>
    
            return dic
    
        }catch _ {
    
            print("失败")
    
            return nil
    
        }
    
    }
    复制代码

    首先因为是自己写的Demo,所以先定义Dictionary,转为Data,然后再转成Dictionary。 定义好你需要的变量,也就是成员,然后将解析出来的Dictionary的key定义为一个数组(例子中就是我定义的Dictionary的key,实际项目中就是你得到的返回值对应的key),再将你与之相对应的变量定义为一个数组,顺序要对应上。然后遍历数组并赋值

    Model源码:

    class testModel:NSObject{
    
        var name:String!
    
        var age:String!
    
        var sex:String!
    
        convenience init(dic:Dictionary<String, Any>){
    
            self.init()    
    
            let arr1 = ["姓名","年龄","性别"]
    
            let arr2 = ["name","age","sex"]
    
            for (index, value) in arr1.enumerated() {
    
                self.setValue(dic[value], forKey: arr2[index])
    
            }
    
        }
    
    }
    
    复制代码

    处理这些之后调用就很简单了,传入Dictionary就搞定了所有的赋值。这样子的Model同样适用于第三方库解析出来的数据,例如SwiftJSON,区别只是传入的字典类型改为JSON。

      let dic = dataToDictionary(data:data)
      let model = testModel.init(dic: dic!)
    复制代码
    展开全文
  • // Data转JSON字符串 func DataToJSONString(data: Data) -> String? { let JSONString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)); return JSONString; }...
    // Data转JSON字符串
    func DataToJSONString(data: Data) -> String? {
        let JSONString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue));
        return JSONString;
    }
    
    // JSON字符串转Data
    func JSONStringToData(json: String) -> Data? {
        let jsonData = json.data(using: String.Encoding.utf8, allowLossyConversion: false);
        return jsonData;
    }
    
    // Data转JSON(对象)  知道JSON对象是什么类型时可以强转为字典和数组
    func DataToJSONObject(data: Data) -> Any? {
        do {
            return try JSONSerialization.jsonObject(with: data , options: .mutableContainers) as AnyObject;
        } catch {
            print(error);
        }
        return nil;
    }
    
    // JSON(对象)转Data
    func JSONObjectToData(json: Any) -> Data? {
        do {
            return try JSONSerialization.data(withJSONObject: json, options: []);
        } catch {
            print(error);
        }
        return nil;
    }
    
    // 字典|数组 转JSON字符串
    func ObjectToJSONString(object: Any) -> String? {
        do {
            let data = try JSONSerialization.data(withJSONObject: object, options: []);
            let JSONString = String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue));
            return JSONString;
        } catch {
            print(error);
        }
        return nil;
    }
    
    // 字典|数组 转Data
    func ObjectToData(object: Any) -> Data? {
        do {
            return try JSONSerialization.data(withJSONObject: object, options: []);
        } catch {
            print(error);
        }
        return nil;
    }

     

    展开全文
  • raywenderlich 的 Data Structures and Algorithms in Swift pdf 格式。 更新到最新的 swift 4 版本。
  • *An NSArray is heterogeneous, meaning that it can contain Cocoa objects of different types. Swift arrays are homogeneous, meaning that each Swift Array is guaranteed to contain only one type of object

    *An NSArray is heterogeneous, meaning that it can contain Cocoa objects of different types. Swift arrays are homogeneous, meaning that each Swift Array is guaranteed to contain only one type of object. 

    However, you can still define a single Swift Array so it stores various types of Cocoa objects by specifying that the one type is AnyObject, since every Cocoa type is also a subtype of this. 


    *Dictionaries are strongly typed, and you must have known key and value types. NSDictionary objects are able to take any NSObject as a key and store any object as a value.


    *Note that subscripting syntax on dictionaries returns an optional. If the dictionary doesn't contain a value for a particular key, the optional is nil; if it does contain a value for that key you could get the wrapped value.

    if let ellensCat = cats["Ellen"] {
    	println("Ellen's cat is named \(ellensCat).")
    } else {
    	println("Ellen's cat's name not found!")
    }

    Because of that, it's a good idea to use the if let optional-unwrapping syntax to access values in a dictionary.


    *Swift sets are type-specific -- all the items in a Swift Set must be of the same type.


    *Creating Swift dictionaries is significantly slower than creating NSMutableDictionaries -- but both degrade at roughly the same O(n) rate.


    *Set creation is considerably slower -- that's the price you pay for checking if every single item in a data structure is unique. 


    *Removing and looking up are both around O(1) performance degradations across Swift and Foundation. This is largely because set structures use hashes to check for equality, and the hashes can be calculated and stored in sorted order. This makes set lookup considerably faster than array lookup.


    *NSCountedSet tracks how many times you've added an object to a mutable set. It inherits from NSMutableSet, so if you try to add the same object again, it's only in the set once. 


    *NSOrderedSet inherits from NSObject.


    *You can use ordered sets as an alternative to arrays when element order matters and performance while testing whether an object is contained in the set is a consideration -- testing for membership of an array is slower than testing for membership of a set. 


    *An NSIndexSet is an immutable collection of unique unsigned integers intended to represent indexes of an array. 


    展开全文
  • func toolsChangeToJson(info: Any) -> String{ //首先判断能不能转换 guard JSONSerialization.isValidJSONObject(info) else { PrintLog(“json转换失败”) return “” } //如果设置options为JSON
    func toolsChangeToJson(info: Any) -> String{
        //首先判断能不能转换
        guard JSONSerialization.isValidJSONObject(info) else {
            PrintLog("json转换失败")
            return ""
        }
        //如果设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读
        let jsonData = try? JSONSerialization.data(withJSONObject: info, options: [])
    
        if let jsonData = jsonData {
            let str = String(data: jsonData, encoding: String.Encoding.utf8)
            return str ?? ""
        }else {
           return ""
        }
    }
    展开全文
  • Core Data是苹果官方提供的一套框架,用来解决对象生命周期管理、对象关系图管理和持久化等方面相关的问题。Core Data是模型层的技术,Core Data帮助你构建代表程序状态的模型层。Core Data也是一种持久化技术,它...
  • MD5的全称是MessageDigest Algorithm 5,即消息摘要算法第五版,是计算机安全领域广泛...在90年代初由MIT Laboratory for Computer Science 和RSA Data Security Inc的Ronald L.Rivest开发,经MD2、MD3和MD4发展而来。
  • Swift-异常处理

    2016-12-20 00:11:54
    1.什么是异常如果你对Swift有过使用,你就会发现有的方法会出现关键词throws,比如我们解析JSON文件时,会使用以下方法: open class func jsonObject(with data: Data, options opt: JSONSerialization....
  • 使用NSKeyedUnarchiver类来进行相互转换 ...var dictionaryExample : [String:AnyObject] = ["user":"UserName", "pass":"password", "token":"0123456789", "image":0] let dataExample :
  • 上一话中实现了两个控制器间的传值,最终效果如图: 这是我们的主页面: 在ViewController中我们主页显示的内容是放到不同的数组中的: var restaurantNames = ["cg1","cg2","cg3","cg4","cg5","cg6","cg7","cg8...
  • // Swift3.0将Foundation中的NS前缀去掉 func parseJSONData() { // 1.config对象 let sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default // 自定义设置属性 // 指定客户端
  • 以前使用过OC版本的CoreData应该很好理解Swift方式,所以这里简单的展示一下,增删改查的方法使用,同时给大家说一下创建步骤,方便大家的使用,转载请注明出处,谢谢~步骤一:创建一个Swift的新项目,记得勾选对应...
  • 本文演示如何实现 Data 类型的数据存取。 1,实现原理 (1)首先我们建表的时候,用于保存 Data 数据的字段要使用大数据类型,比如:BLOB(二进制数据) (2)读取操作同其他数据类型的
  • Swift 数据类型转换

    2019-01-28 17:34:59
    /** array 转 jsonString */  private func stringFromArray(_ array:Array&...Any&gt;?)-&gt;String{  if array != nil {  if JSONSerialization.isValidJSONObject(array!) == false {  ...
  • swift 3, swift2

    2016-12-28 00:38:43
    Swift3:DispatchQueue.main.async(execute: { }) Swift2: dispatch_async(dispatch_get_main_queue(), { }) TimeInterval–swift3 NSTimeInterval–swift2fileprivate-swift3 private-swift2D
  • Swift3.0 类型转换 示例

    2017-03-14 19:27:46
    // ViewController.swift // test_Swift3.0_type_casting // // Created by jeffasd on 17/3/14. // Copyright © 2017年 jeffasd. All rights reserved. // import UIKit class ViewController: UIViewContr
  • //读本地 转换成json do catch是抓错 let path = Bundle.main.url(forResource: "productDetailInfo", withExtension: "txt") let data = try! Data(contentsOf: path!) do { let dict = try!...
  • 今天在写代码的时候,发现以前在OC中对象可以判断是否为nil,且OC中的通用类型使用id表示,而swift中有一个Any和AnyObject类型,而我今天在用AnyObject类型的时候,发现作为变量使用的时候,它可以进行判断是否为nil...
1 2 3 4 5 ... 20
收藏数 5,050
精华内容 2,020