swift的类型推断
类型推断的前提是有待定类型和上下文。
1、由定义推断实现的类型;
2、由赋值推断声明的类型;
3、由实现推断泛型的类型;
Type inference refers to the automatic detection of the data type of an expression in a programming language.
Type inference is the ability to automatically deduce, either partially or fully, the type of an expression at compile time. The compiler is often able to infer the type of a variable or the type signature of a function, without explicit type annotations having been given. In many cases, it is possible to omit type annotations from a program completely if the type inference system is robust enough, or the program or language is simple enough.
https://www.cnblogs.com/feng9exe/p/9151219.html
Type inference is particularly useful when you declare a constant or variable with an initial value. This is often done by assigning a literal value (or literal) to the constant or variable at the point that you declare it. (A literal value is a value that appears directly in your source code, such as 42 and 3.14159 in the examples below.)
http://www.cnblogs.com/feng9exe/p/9102835.html
Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide. Swift 4 uses type inference to work out the appropriate type as follows.
https://www.tutorialspoint.com/swift/swift_data_types.htm
Swift Type Inference Closure Constraints
http://rosslebeau.com/2016/swift-type-inference-closure-constraints
It’s rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it’s defined, Swift can almost always infer the type to be used for that constant or variable, as described in Type Safety and Type Inference. In the welcomeMessage example above, no initial value is provided, and so the type of the welcomeMessage variable is specified with a type annotation rather than being inferred from an initial value.
https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html
Because of type inference, Swift requires far fewer type declarations than languages such as C or Objective-C. Constants and variables are still explicitly typed, but much of the work of specifying their type is done for you.
Type inference is particularly useful when you declare a constant or variable with an initial value. This is often done by assigning a literal value (or literal) to the constant or variable at the point that you declare it. (A literal value is a value that appears directly in your source code, such as 42 and 3.14159 in the examples below.)
https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID322
Inferring Type From Context
Because the sorting closure is passed as an argument to a method, Swift can infer the types of its parameters and the type of the value it returns. The sorted(by:) method is being called on an array of strings, so its argument must be a function of type (String, String) -> Bool. This means that the (String, String) and Bool types do not need to be written as part of the closure expression’s definition. Because all of the types can be inferred, the return arrow (->) and the parentheses around the names of the parameters can also be omitted:
- reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
It is always possible to infer the parameter types and return type when passing a closure to a function or method as an inline closure expression. As a result, you never need to write an inline closure in its fullest form when the closure is used as a function or method argument.
Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-free syntax in common scenarios. These optimizations include:
- Inferring parameter and return value types from context
- Implicit returns from single-expression closures
- Shorthand argument names
- Trailing closure syntax
If you use these shorthand argument names within your closure expression, you can omit the closure’s argument list from its definition, and the number and type of the shorthand argument names will be inferred from the expected function type. The in keyword can also be omitted, because the closure expression is made up entirely of its body:
- reversedNames = names.sorted(by: { $0 > $1 } )
Here, $0 and $1 refer to the closure’s first and second String arguments.
Operator Methods
There’s actually an even shorter way to write the closure expression above. Swift’s String type defines its string-specific implementation of the greater-than operator (>) as a method that has two parameters of type String, and returns a value of type Bool. This exactly matches the method type needed by the sorted(by:) method. Therefore, you can simply pass in the greater-than operator, and Swift will infer that you want to use its string-specific implementation:
- reversedNames = names.sorted(by: >)
https://docs.swift.org/swift-book/LanguageGuide/Closures.html
swift的类型推断的更多相关文章
- 浅谈Swift集合类型
Swift 的集合表现形式由数组和字典组成.它可以完美的存储任何呢想存储的东西. 数组是一个同类型的序列化列表集合,它用来存储相同类型的不同值.字典也是一个数组,但它的存值方式类似于Map,通过一对一 ...
- Swift语言指南(四)--类型安全和类型推断
原文:Swift语言指南(四)--类型安全和类型推断 Swift是一门类型安全语言,类型安全语言需要代码里值的类型非常明确.如果你的代码中有部分值需要String类型,你就不能错误地传递Int. 鉴于 ...
- WebKit Web Inspector增加覆盖率分析和类型推断功能
WebKit中的Web Inspector(Web检查器)主要用于查看页面源代码.实时DOM层次结构.脚本调试.数据收集等,日前增加了两个十分有用的新功能:覆盖率分析和类型推断.覆盖率分析工具能够可视 ...
- Swift基础类型
1.使用 let 来声明常量,使用 var 来声明变量. 注:你能够在一行中声明多个常量或者多个变量.用逗号隔开. 2.类型标注 假设初始值没有提供足够的信息(或者没有初始值),那你须要在变量后面声明 ...
- 6.Swift教程翻译系列——Swift集合类型
英文版PDF下载地址http://download.csdn.net/detail/tsingheng/7480427 Swift提供数组和字典两种集合类型.用来存储很多值的情况.数组有序的存储一组同 ...
- C++11特性——变量部分(using类型别名、constexpr常量表达式、auto类型推断、nullptr空指针等)
#include <iostream> using namespace std; int main() { using cullptr = const unsigned long long ...
- TypeScript Type Innference(类型推断)
在这一节,我们将介绍TypeScript中的类型推断.我们将会讨论类型推断需要在何处用到以及如何推断. 基础 在TypeScript中,在几个没有明确指定类型注释的地方将会使用类型推断来提供类型信息. ...
- Swift数字类型之间的转换
Swift数字类型之间的转换Swift是一种安全的语言,对于类型的检查非常严格,不同类型之间不能随便转换.一.整型之间的转换在C和Objective-C等其他语言中,整型之间有两种转换方法:从小范围数 ...
- C++11新特性:自动类型推断和类型获取
声明:本文是在Alex Allain的文章http://www.cprogramming.com/c++11/c++11-auto-decltype-return-value-after-functi ...
随机推荐
- MySQL的安装与维护
一.数据库的基本概念 数据库: 以一定方式储存在一起.能为多个用户共享.具有尽可能小的冗余度的特点.是与应用程序彼此独立的数据集合. DBMS(DataBase Management System,数 ...
- 桥接模式(Bridge)
1.概念 桥接模式将抽象部分与它的实现部分分离,使它们都可以独立地变化,属于结构性模式的一种. 2.模式结构 Abstraction(抽象类):定义抽象接口,拥有一个Implementor类型的对象引 ...
- HDU1114(KB12-F DP)
Piggy-Bank Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total ...
- Object of type 'ListSerializer' is not JSON serializable “listserializer”类型的对象不可JSON序列化
Object of type 'ListSerializer' is not JSON serializable “listserializer”类型的对象不可JSON序列化 一般原因为 序列化的对象 ...
- 正则表达式 ?P<name>
import re # 将匹配的数字乘以 2 def double(matched): value = int(matched.group('value')) return str(value * 2 ...
- div阴影
.box-shadow{ //Firefox4.0- -moz-box-shadow:投影方式 X轴偏移量 Y轴偏移量阴影模糊半径 阴影扩展半径 阴影颜色; //Safariand Google ch ...
- python学习之老男孩python全栈第九期_day008知识点总结
''''如何打开一个文件模特主妇护士老师.txt1. 文件路径:f:\模特主妇护士老师.txt2. 操作方式:只读:r ,rb ,只写: w, wb ,追加: a , ab,读写:r+ , r+b,写 ...
- 关于JavaScript原型对象那些事儿
①为什么要使用原型:为了实现继承. ②利用constructor属性可以让实例化对象轻松访问原型,实现实例化对象对原型对象的修改,但是原型对象是全局对象,一般不能随意修改原型对象的成员.该属性多用于调 ...
- POJO、JAVABEAN、*O、EJB
POJO: 全称:Plain Old Java Object 解释:纯洁老式的java对象.从任何类继承.也没有实现任何接口,更没有被其它框架侵入的java对象 理解:通常我们常说的实体类 BEAN: ...
- 设计模式(21)--Strategy(策略模式)--行为型
作者QQ:1095737364 QQ群:123300273 欢迎加入! 1.模式定义: 策略模式属于对象的行为模式.其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而 ...