Swift Generics Tutorial

*Swift has typed arrays and dictionaries. An array of Ints can only hold Ints and can never (for example) contain a String. This means you can document code by writing code, allowing the compiler to do the type checking for you. 


*Generics provide types as parameter to the class. All arrays act the same way, storing values in a list, but generic arrays parameterize value type. You might find it helpful to think of it like this: The algorithms you'll use on arrays are non-type-specific, so all arrays, with all types of values, can share them.


*Value semantics is a fancy way of saying "copy/paste behavior", rather than "shared reference behavior". Value semantics brings a number of benefits, such as not having to worry about some other piece of code modifying  your data unexpectedly. 


*

struct OrderedDictionary<KeyType: Hashable, ValueType>
typealias DictionaryType = [KeyType: ValueType]

This declares two properties, as described, and also two type aliases, which are a way to give a new name to an existing type. Here, you give aliases to the array and dictionary types for the backing array and dictionary, respectively. Type aliases are a great way to take a complex type and give it a much shorter name. 

The Hashable after the semicolon declares that the type passed for KeyType must conform to the Hashable protocol. This is because Dictionary needs to be able to hash keys for its implementation.


**Structs are designed to be immutable by default, meaning you ordinarily can't mutate struct member variables in an instance method. Since that is quite limiting, you can add the mutating keyword to tell the compiler that the method is allowed to mutate state in the struct. This helps the compiler make decisions about when the take copies of structs (they are copy-on-write) and also helps document the API.


*You may have used assertions in OC with the assert function; assert is available in Swift too, but precondition is active in release builds so your shipped apps will terminate if the preconditions fails. 


*In this example, the dictionary has an Int key, so the compiler will look at the type of the variable being assigned to determine which subscript to use. Since byIndex is an (Int, String) tuple, the compiler knows to use the array style index version of the subscript which matches the expected return type. 


*For type inference to work, the compiler requires that the type of an expression be unambiguous. When multiple methods exist with the same argument types but different return types, the caller needs to be specific. 






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值