swift(1)The Basics

前端之家收集整理的这篇文章主要介绍了swift(1)The Basics前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

文档地址:https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309

1、int for integers,Double and Float for floating-point value,Bool for Boolean values,and String For textual data.Swift also provides powerful versions of the three primary collection types,Array,Set and Dictionary,as described in Collection Types.

2、in addition to familiar types,Swift introduces advanced types not found in Objective-c,such as tuples.

除了熟悉的类型,swift还提供了一些在oc中没有发现的类型,像tuples.

3、Swift also introduces optional types.which handle the absence(没有,缺乏,缺失) of a value.

swift也提供了一些选择类型,这是用来处理值没有的那种情形的。

4、Not only are opationls safer and more expensive than nil pointer in Objective-c,they are at the heart of many of Swift’s powerful features.

选择类型不仅比oc里面的nil指针安全,他们也是swift许多富有力量的特性的核心。

5、swift is a type-safe language,which means the language helps you to be clear about the types of values your code can work with.If part of your code expects a String,type safety prevents you from passing in an Int by mistake.Likewise,Type safety prevents you from accidentally passing an optional String to a piece of code that expects a nonoptional Sting.Type safety helps you catch and fix errors as early as possible in the development process.

swift是一种类型安全的语言,这种情况意味着这种语言帮助你明白你的码工作的值的类型。如果你的码期盼一个sting,类型安全将会阻止你错误的传递一个int值,同样的,类型安全会阻止你故意传递一个选择的sting给一个期盼一个非选择的值的string.类型安全在程序开发中尽可能帮助你捕捉和修复错误

6、constants and variables must be declared before they are used.You declare constants with the let keyword and variables with the var keyword.

常量和变量必须在他们使用前声明。通过let声明常量,通过var声明变量。

7、let maxinumNumberOfLoginAttempts = 10; var = currentLoginAttempt = 0; Declare a new constant called maxinumNumberOfloginAttempts,and give it a value of 10. Then,declare a new variable called currentLoginAttempt,and give it an initial value of 0

声明一个常量叫max.....,然后给它赋值10,声明一个变量var,给它附一个初始值0

8、you can declare multiple constants or multiple variables on a single line.var x = 0.0,y = 0.0,z= 0.0

你可以通过上面的的形式声明多个常量或者变量。

9、type annotation类型释文

write a type annotation by placing a colon(冒号) after the constant or variable name,followed by a space,followed by the name of type to use.

写下一个类型说明通过在一个常量或者变量添加一个冒号,接着再添加一个空格,然后 再添加一个类型的名字。

var welcomeMessage: String

10、the colon in the declaration means” … of type…”冒号相当于声明一个某某的类型。

11、you can define multiple related variables of the same type on a single line,separated by commas,with a single type annotion after the final variable name

你能定义多个相关的变量在一条线上,用逗号分开,在最后一个变量名字上加上一个简单的类型释文

var a,b,c,d:String;

12、it is rare that you need to write type annomations in practice.If you provide an initial value for a constant or variable at the point that it is defined,swift can almost always infer(判断) the type to be used for that constant or variable.

在实践中很少见写类型释文的,如果你给一个常量或者变量在它定义的点提供一个初始值。Swift 能总是能推断给这个常量或者变量将使用的类型。好智能啊

13、constant and variable names can contain almost any character.

注意almost常量和变量的名字能包含任何字符。

14、constant and variable names cannot containwhitespace characters,mathematical symbols,arrows,private-use(or invalid) Unicode code points,or line-and Box-drawing characters.Nor can they begin with a number,although numbers may be included elsewhere within the name;

(这里说的不好)常量和变量不能包含空格,数学符号,箭头,私有使用用来画点、线、盒子的的特征字符,也不能用一个数字,尽管数字可以包含在名字里面,也可以在名字后面,但是不能放在名字的前面。

15、once you’ve declared a constant or variable of a certain type,you can’t redeclare with the same name,or change it to store values of a different type.Nor can you change a constant into variable or a variable into a constant.

一旦你已经声明一个确切类型的常量或者变量,你就不能再一次用相同的名字重新声明它,或者改变他用来储存不能类型的值,也不能将一个常量变成变量或者将一个变量变为常量。

16、avoid using keywords as names unless you have absolutely no choice.if necessary,surround the keyword with back-ticks(‘)

反引号避免使用与swift的相同的关键字除非你完全没有选择

17、wrap the name in parentheses and escape it with a backslash before the opening parenthesis

包裹这个名字在括号里,用一个反斜线划开那个打开的插入。

18the function terminates the line it prints by adding a line break???????????????

19、Multiline comments start with a forward-slash followed by an asterisk(/*)and end with an asterisk followed by a forward-slash(*/).

如果有很多的评论我们可以这么写

20、Nested multiline comments enable you to comment out large blocks of code quickly and easily,even if the code already contains multiline comments

嵌套的大量注释确保你能在大块代码更容易更快。????

21、semicolons分号Unlike many other languages,Swift does not require you to write a semicolon after each statement your code,although you can do if you wish. However,semicolons are required if you want to write multiple separate statements on a single line;

如果你想写多个分开的陈述在一行,那么你就需要添加上分号

22、let minValue = UInt8.min; let maxValue = UInt8.max;

通过这种方法可以获得最大值最小值。也叫Integer Bounds整数的边界

23、The values of these properties are of the appropriate-sized number type(such as UInt8 in the example above) and can therefore be used in expressions alongside other values of the same type.这句话怎么理解???????、

24、In most cases,you don’t need to pick a specific size of integer to use in your code.Swift provides an additional integer type,Int .On a 32-bit platform,Int is the same size as Int32;On a 64-bit platform,Int is the same size as Int64

在大多数情形,你不需要设置一个整数的尺寸用在你的代码里面。Swift提供一个额外的整数类型int ?????查询这两个平台有什么区别

25、UInt无符号的整型。it has the same size as the current platform’s native word size.她又目前平台本地单词尺寸相同的尺寸。On a 32-bit platform,UInt is the same size as UInt32On a 64-bit platform,UInt is the same size as UInt64

26、问题??????小数是怎么存储的???Double represents a 64-bit floating-point number.Float represents a 32-bit floating-point number.Floating-point types can store numbers that are much larger or smaller than can be stored in an Int.

浮点数能存储比Int更大的数。

27、Double has a precision of at least 15 decimal digits,whereas the precision of Float can be as little as 6 decimal digit.

双浮点型至少有15个小数点的精确度,float型能至少有6个小数点精确度。

28、Swift is a type-safe languageswift是一中类型安全的语言。

29、It performs type checks when compiling your code and flags any mismatched types as errors

当编译的时候它执行类型的核对,并对任何没有匹配的类型做标记

30、Because of type inference,Swift requires far fewer type declarations than languages such as C or Objective-C

因为类型推断,Swift 跟c语言或者oc语言相比需要更少的类型声明。

31、Swift always chooses Double (rather than Float)when inferring the type of floating-point numbers.swift

语言当在推断浮点数的类型时习惯选择double而不是float

32、 . let anotherPi = 3 + 0.14159The literal value of 3 has no explicit type in and of itself,and so an appropriate output type of Double is inferred from the presence of a floating-point literal as part of the addition. ????这里完全理解没

33、a binary number,with a Ob prefix

一个二进制的数字,有一个Ob开头an octal number,with a 0o prefix一个八进制的数字,有一个0o开头a hexadecimal number,with a 0x prefix一个十六进制的数字,有一个0x开头for example

let decimalInteger = 17

let binaryInteger = 0b10001

let octalInteger = 0o21

let hexadecimalInteger = 0x11

34、Decimal floats can also have an optional exponent,indicated by an uppercase or lowercase e; hexadecimal floats must have an exponent,indicated by an uppercase or lowercase p.小数也能写成选择性的指数,用一个大写字母e或者小写字母e,十六进制的浮点数也必须有一个指数,用大写或者小写字母p.

35、for hexadecimal numbers with an exponent of exp,the base number is multiplied by 2exp.0xFp-2 means 15×2(-2)

36、Numeric literals can cantain extra formatting to make them easier to read.Both integers and floats can be padded with extra zeros and can cantain underscores to help with readability.数字文字能包含额外的格式使他们容易读,整数和小数都能用额外的零填充,也能包含下划线来提高可读性。

37、Using explicitly-sized typed in these situation helps to catch any accidental value overflows and implicitly documents the nature of the data being used.

应用明确尺寸的类型帮助获取任何突发的值的外露,以及数据的本性正在使用过的暗含的文件

38、integer Conversion A number that will not fit into a constant or variable of a sized integer type is reported as an error when your code is compiled.一个数组如果没有适合一个常量或者变量的尺寸那么当编译时就会报错。

39、let twoThousand :UInt16 = 2_000

let one:UInt8 = 1

let twoThousandAndOne = twoThousand + UInt16(one)

Because both sides of the addition are now of type UInt16,addition is allowed.

因为两边都是UInt16,加法被允许

SomeType(ofInitialValue) is the default way to call the initializer of a Swift type and pass in an initial value.

这个方法SomeType(ofInitialValue) 是一个默认的方法调用swift类型的初始器然后传递一个初始值。

Behind the scenes,UInt16 has an initializer that accepts a UInt8 value,and so this initializer is used to make a new UInt16 from an existing UInt8

在幕后,UInt16 有一个接受UInt8值的初始器,这个初始器被用来从UInt8造一个UInt16值40、integer and floating-Point Conversion 整数和浮点型转换

41、truncate缩短let three = 3

let pointOneFourOneFiveNine = 0.14159

let pi = Double(three) + poitOneOneFiveNivelet

integer Pi = Int(Pi)

Floating-point values are always truncated when used to initialize a new integer value in this way

浮点数当用来初始化一个整数的时候总是被缩短。

43、typealias AudioSample = UInt16定义一个别名

44、Swift’s type safety prevents non-Boolean values from being substituted for Boolswift

安全类型禁止非bool值替换bool值

for:

let i = 1

if i {

//this example will not compile,and will report an error

}

let i= 1

if i == 1 {

//this examle will compile successfully

the resulit of the i == 1 comparison is o f type Bool

45、tupes元组let http404Error = (404,“Not Found”)

The values within a tuple can be of any type

在元组里面的值能是任何类型

you can create tuples from any permutation of types

你能创建元组用任意顺序

46、you can decompose a tuple’s contents into separate constants or variables.

你能将元组的内容进行分解成常量或者变量

47、let http404Error = (404,”Not Found”)

let (statusCode,statusMessage) = http404Error

print (“The status code is \(statusCode)”)

let (justTheStatusCode,_) = http404Error

print (“The status code is \(JustTheStatusCode)”)

这种写法值需要元组的一部分值,忽视元组的其他值

48、元组的另外一种取值方式

print (“The status code is \(http404Error.0))

print(“The status message is \(http404Error.1)”)

49、元祖的的另外一种写法

let http200Status = (statusCode:200,description:”OK”)

print (“The status code is \(http200Status.statusCode)”)

50、元组对于有联系的值的临时数组是有用的,他们不适合一个复杂的数据结构的创建,如果你的数据结构可能超出一个临时的范围,用一个类或者结构模型化它,而不是一个元组

51、The concept of optionals doesn’t exist in C or Objective-C.The nearest thing in Objective-C is the ability to return nil from a method that would otherwise return an object一般情况下返回一个对象的注意:otherwise( 在其他方面)

52、The concept of optionals doesn’t exist in C or Objective-C. The nearest thing in Objective-C is the ability to return nil from a method that would otherwise return an object,with nil meaning “the absence of a valid object.” However,this only works for objects—it doesn’t work for structures,basic C types,or enumeration values. For these types,Objective-C methods typically return a special value (such as NSNotFound) to indicate the absence of a value. This approach assumes that the method’s caller knows there is a special value to test against and remembers to check for it. Swift’s optionals let you indicate the absence of a value for any type at all,without the need for special constants.

选择类型在c或者oc里面不存在,在oc里面最接近的东西是返回一个nil,这个方法一般情况下是返回一个对象的,nil就意味着一个有效对象的缺失。但是这个情形只对对象有用,它对结构,基本C,或者枚举值没用,对于这些类型,oc方法一般返回一个特殊的值来显示一个值的缺失,例如NSNotFound,这种设置方法假定方法的叫唤者知道有一个特殊的值要测定,记得要核对一下,swift optinal 让你显示一个值的缺失,任何类型,而不需要特殊的常量。

53、let possibleNumber = “123”

let convertedNumber = Int(possibleNumber)

Because the initializer might fail,it returns an optional Int,rather than an Int.An optional Int is written as Int?因为初始器可能失败,它返回一个可选的值(Int?),而不是一个Int.

54、you set an optional variable to a valueless state by assigning it the special value nil:你可以将一个可选择的值设置为一个nil值serverResponseCode = nilnil cannot be used with nonoptional canstants and varibales.If a constant or variable in your code needs to work with the absence of a value under certain conditions,always declare it as an optional value of the appropriate type.nil

不能用在飞选择性常量或者变量上,如果在你的代码中的你的变量需要在一些情形下使用一个可能确实的值,只能用optional

55、if you define an optional variable without providing a default value,the variable is automatically set to nil for you.

如果你定义一个选择值,却又没赋值,那么变量会被自动地设为nil

56、Swift’s nil is not the same as nil in Objective-C.In Objective-C,nil is a pointer to a nonexistent object.In Swift,nil is not a pointer—it is the absence of a value of a certain type.Optionals of any type can be set to nil,not just object types.

swift的nil跟oc里面的nil不相同.in oc,nil是一个指向不存在对象,但是在swift中,nil不是指针,它是很多类型的值的缺失的情况,任何类型的optional都可以设置为nil

57、将选择类型的值跟nil比较by == or !=

58、一旦你确定一个选择的值包含一个值,我们可以在一个选择的值后面加一个!

The exclamation mark effectively says:”I know that this optional definitely has a value; please use it”

这个解释高效的说:我知道这个选择类型明确的有一个值,请使用它。

This is known as forced unwapping of the optional’s value

这就是著名的选择性值的强制拆包。

if converedNumber != nil {

print (“converedNumber has an integer value of \(convertedNumber!)”)//注意后面的感叹号❗️

59、Trying to use ! to access a nonexistent optional value triggers a runtime error.Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

尝试给一个非存在的选择的值添加一个!会引起一个运行时错误

60、Optional Binding write an optional binding for an if statement as follows

if let contantName = someOptional {

statements

for :if let acturalNumber = Int(possibleNumber) {

print (“\”\(possibleNumber)\” has an integer value of \(actualNumber)”)

}else {

print (“\”\(possibleNumber)\” could not be converted to an integer)

you can include as many optional bindings and Boolean conditions in a single if statement as you need to,separated by commas

如果你需要,你能包含很多的选择性bingding 和bool值情形,通过逗号分开

if let firstNumber = Int(“4”),let secondNumber = Int(“42”,firstNuber < secondNumber && secondNumber < 100) {

print(“dddddd”)

}

61、implicitly unwrapped optionals

模糊拆包

You write an implicitly unwarpped optional by placing an exclamation mark(String!) rather than a question mark(String?)after the type that you want to make optional.

62、An implicitly unwrapped optional is a normal optional behind the scenes,but can also be used like a nonoptional value,without the need to unwrap the optional value each time it is accessed.

一个模糊拆包其实在幕后就是一个正常选择,但是它能被用在一个非选择的值,没有没要每次都拆包。

for exa:

let possobleString:String? = “An optional string.”

let forcedString:String = possibleString!


let assumedString:String! = “An implicity unwrapped optional string.”

let implicitString :String = assumedString

总结:如果我们知道它是普通的optional,并且有值,那我们就选择模糊拆包,如果进一步我们知道是模糊拆包,我们可以直接赋值,无需感叹号❗️

你可以理解为assumedString自动拆包,无需再调用感叹号

63、 Error Handling错误处理

  • do {
  • trymakeASandwich()
  • eatASandwich()
  • }catchSandwichError.outOfCleanDishes {
  • washDishes()
  • }catchSandwichError.missingIngredients(letingredients) {
  • buyGroceries(ingredients)
  • }

64、Assertions

断言

assert(age >= 0,“A person’s age cannot be less than zero)

如果age > 0,code execution will continue

如果age < 0 assert将会触发。

Error Handling 和assertions这两个section没有处理好

猜你在找的Swift相关文章