Swift基本知識の15 swift符号化

3552 ワード

  Objective-C   @encode        ,        ,                 C    :

char *typeChar1 = @encode(int32_t);  
char *typeChar2 = @encode(NSArray);  
// typeChar1 = "i", typeChar2 = "{NSArray=#}"
                 。              Objective-C            ,      ,         ,                       。         ,         :   API   Apple      NSValue   valueWithBytes:objCType:      (   CIAffineClamp     ) ,    objCType          ;                        ,              。

Swift        Metatype      ,                ,   Swift             。                  ,    Cocoa           NSValue   objcType              :

class NSValue : NSObject, NSCopying, NSSecureCoding, NSCoding {  
    //...
    var objCType: UnsafePointer<Int8> { get }

    //...
}
             Swift     “   ”       ,           NSNumber (NSNumber   NSValue    ),      :

let int: Int = 0  
let float: Float = 0.0  
let double: Double = 0.0

let intNumber: NSNumber = int  
let floatNumber: NSNumber = float  
let doubleNumber: NSNumber = double

String.fromCString(intNumber.objCType)  
String.fromCString(floatNumber.objCType)  
String.fromCString(doubleNumber.objCType)

//      :
// {Some "q"}
// {Some "f"}
// {Some "d"}
//   ,fromCString      `String?`
             NSValue    ,                  ,             struct,   NSValue                    NSArray          :

let p = NSValue(CGPoint: CGPointMake(3, 3))  
String.fromCString(p.objCType)  
// {Some "{CGPoint=dd}"}

let t = NSValue(CGAffineTransform: CGAffineTransformIdentity)  
String.fromCString(t.objCType)  
// {Some "{CGAffineTransform=dddddd}"}
        ,                                 。

    ,        NSUserDefaults             ,                    ,                       NSNumber       ,    。   NSNumber           ,            ,         API,       。              objCType     ,                  。                      ,           ,        Int    Double          。