美文网首页
Type Inference with __auto_type

Type Inference with __auto_type

作者: flightlessBirdT | 来源:发表于2018-09-05 21:02 被阅读40次

    Objective-C的时候,因为要遵循驼峰命名法,所以写一个变量之前,首先要想如何优雅的为其命名,然后再用对应的类型去接收它。很多时候,这个类型需要重复的去写,非常麻烦。

    我们知道在Swift里面,有两种申明变量的方式:letvar
    let 用于定义常量,定义完后不能修改
    var 用于定义变量,定义完后可以修改

    申明常量或者变量的同时如果赋值的话,编译器会自动推断类型,列如
    let age0 = 10
    var age1 = "10"
    age0int型,age1String

    那在Objective-C中如何做到这样呢?

    得益于苹果在Xcode8中已经支持类型推倒,我们就可以用C__auto_typeC++auto来定义一个宏let 这样在项目了我们就可以用let来接收一切类型了

    #if !defined(var)
    #if defined(__cplusplus)
    #define var auto
    #else
    #define var __auto_type
    #endif
    #endif
    
    #if !defined(let)
    #define let const var
    #endif
    

    比如
    定义一个结构体类型 let trackFrame = self.trackLayer.frame;
    定义一个数组类型 let selected = [self indexPathsForSelectedItems];
    定义一个字符串类型 let title = @"i am a text";

    关于Type Inference with __auto_type的更多信息:
    https://intii.com/2017/write-objc-like-writing-swift/
    https://medium.com/@maicki/type-inference-with-auto-type-55a38ef56372

    相关文章

      网友评论

          本文标题:Type Inference with __auto_type

          本文链接:https://www.haomeiwen.com/subject/deuzwftx.html