一、常量与变量

1.常量与变量的表示

在Swift中实用let表示常量,使用var表示变量。Use let to make a constant and var to make a variable。一个常量的值在编译时不需要知道,但你必须一次赋值(The value of a constant doesn’t need to be kNown at compile time,but you must assign it a value exactly once.)

eg1:

  • var myVariable = "The width is "
  • myVariable = 50
  • let myConstant = 42
  • 在上面的eg1中,我们的变量myVariable并没有明确的给他一个数据类型,常量myConstant也是没有明确的给它一个数据类型。因为编译器会根据我们给的初始值区推断我们的常量或是变量是什么类型的数据。但是一个常量或是一个变量必须有一个同一类型的值。
  • A constant or variable must have the same type as the value you want to assign to it. However,you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above,the compiler infers that myVariable is an integer because its initial value is an integer.

但是在声明变量的时候,我们也可以这样给它一个明确的数据类型

eg2:

var welcomeMessage:String

“Declare a variable called welcomeMessage that is of type String.”

The welcomeMessage variable can Now be set to any string value without error:

  • welcomeMessage = "Hello"

2.什么时候使用常量和变量

NOTE

If a stored value in your code is not going to change,always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.

简单翻译就是在代码中需要改变的使用变量,不需要改变的使用常量。

eg3:

You can change the value of an existing variable to another value of a compatible type. In this example,the value of friendlyWelcome is changed from "Hello!" to "Bonjour!”:(简短理解就是,变量是可以修改的)

  • var friendlyWelcome = "Hello!"
  • friendlyWelcome = "Bonjour!"
  • // friendlyWelcome is Now "Bonjour!"

Unlike a variable,the value of a constant cannot be changed once it is set. (常量声明后就不能改变)Attempting to do so is reported as an error when your code is compiled:

  • let languageName = "Swift"
  • languageName = "Swift++"
  • // this is a compile-time error - languageName cannot be changed

3.常量与变量的命名规则

Constant and variable names can contain almost any character,including Unicode characters:


Constant and variable names cannot contain whitespace 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.

常量和变量的名称可以保函任何字符,包括Unicode字符。但是不能使用数字符号、空格、箭头和无效的Unicode代码或是线框绘制字符,不能使用数字开头。

Once you’ve declared a constant or variable of a certain type,you can’t redeclare it again with the same name,or change it to store values of a different type. nor can you change a constant into a variable or a variable into a constant.

变量和常量的名称是唯一的,且声明以后你不能修改数据类型。

二、打印输出print

The print(_:separator:terminator:) function is a global function that prints one or more values to an appropriate output. In Xcode,for example,the print(_:separator:terminator:) function prints its output in Xcode’s “console” pane. The separator and terminator parameter have default values,so you can omit them when you call this function. By default,the function terminates the line it prints by adding a line break. To print a value without a line break after it,pass an empty string as the terminator—for example,print(someValue,terminator: "").

eg4:

print("The current value of friendlyWelcome is \(friendlyWelcome)")

三、注释

注释部分Swift中是写了三种,个人感觉就是对/* Comments */注释做了扩展。

第一种://

// this is a comment

第二种:/* Comments*/

  • /* this is also a comment,
  • but written over multiple lines */

第三种:

Unlike multiline comments in C,multiline comments in Swift can be nested inside other multiline comments. You write nested comments by starting a multiline comment block and then starting a second multiline comment within the first block. The second block is then closed,followed by the first block:

  • /* this is the start of the first multiline comment
  • /* this is the second,nested multiline comment */
  • this is the end of the first multiline comment */

这个写法是不是感觉再也不用担心在写/**/注释的时候里面多写了/*或是*/了。

nested multiline comments enable you to comment out large blocks of code quickly and easily,even if the code already contains multiline comments.(嵌套多行注释使你注释掉大块的代码快速方便,即使代码已经包含多行注释。)

四、基本数据类型

1.整数

整数Integers分为signed(包括正数,零和负数)和unsigned(正数和零)。

Swift provides signed and unsigned integers in 8,16,32,and 64 bit forms. These integers follow a naming convention similar to C,in that an 8-bit unsigned integer is of type UInt8,and a 32-bit signed integer is of type Int32. Like all types in Swift,these integer types have capitalized names.

不同进制数据的表示方法:

Integer literals can be written as:

  • A decimal number,with no prefix 十进制
  • A binary number,with a 0b prefix 二进制
  • An octal number,128)"> 0o prefix 八进制
  • A hexadecimal number,128)"> 0x prefix 十六禁止

eg5:

All of these integer literals have a decimal value of 17:

  • let decimalInteger = 17
  • let binaryInteger = 0b10001 // 17 in binary notation
  • let octalInteger = 0o21 // 17 in octal notation
  • let hexadecimalInteger = 0x11 // 17 in hexadecimal notation

2.浮点数

在Swift中,提供了两种signed的浮点数:

  • Double represents a 64-bit floating-point number.
  • Float represents a 32-bit floating-point number.

数据的强制转换:

eg6:

  • let three = 3
  • let pointOneFourOneFiveNine = 0.14159
  • let pi = Double(three) + pointOneFourOneFiveNine
  • // pi equals 3.14159,and is inferred to be of type Double
  • let integerPi = Int(pi)
  • // integerPi equals 3,and is inferred to be of type Int

3.布尔类型

在Swift中,提供了true and false

4. Tuples(元组)

Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.

元组中的值可以是任何类型的而且不必是同一类型的。感觉比OC里面的数组还要强大。

eg7:

  • let http404Error = (404,"Not Found")
  • // http404Error is of type (Int,String),and equals (404,"Not Found")


  • let (statusCode,statusMessage) = http404Error
  • print("The status code is \(statusCode)")
  • // prints "The status code is 404"
  • print("The status message is \(statusMessage)")
  • // prints "The status message is Not Found"

如果我们只需要元组中得部分值,我们可以把不需要的使用”_”代替。

eg8:

  • let (justTheStatusCode,_) = http404Error
  • print("The status code is \(justTheStatusCode)")
  • // prints "The status code is 404"

如果我们需要其中的某一个元素我们也可以使用下标索引的形式取值:

eg9:

  • print("The status code is \(http404Error.0)")
  • print("The status message is \(http404Error.1)")
  • // prints "The status message is Not Found"

元组也可以定义为单个元素名:

eg10:

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

  • print("The status code is \(http200Status.statusCode)")
  • // prints "The status code is 200"
  • print("The status message is \(http200Status.description)")
  • // prints "The status message is OK"

Swift 基础知识的更多相关文章

  1. ios – Swift相当于`[NSDictionary initWithObjects:forKeys:]`

    Swift的原生字典是否与[NSDictionaryinitWithObjects:forKeys:]相当?假设我有两个带键和值的数组,并希望将它们放在字典中.在Objective-C中,我这样做:当然我可以通过两个数组迭代一个计数器,使用vardict:[String:Int]并逐步添加东西.但这似乎不是一个好的解决方案.使用zip和enumerate可能是同时迭代两者的更好方法.然而,这种方法

  2. ios – 如何从变量访问属性或方法?

    是否可以使用变量作为Swift中方法或属性的名称来访问方法或属性?在PHP中,您可以使用$object->{$variable}.例如编辑:这是我正在使用的实际代码:解决方法你可以做到,但不能使用“纯粹的”Swift.Swift的重点是防止这种危险的动态属性访问.你必须使用Cocoa的Key-ValueCoding功能:非常方便,它完全穿过你要穿过的字符串到属性名称的桥,但要注意:这里是龙.

  3. iOS >>块>>更改块外部的变量值

    我不是在处理一个Object并改变它,就像我的mString一样.我希望’center’属性的行为类似于myInt,因为它是直接访问的C结构,而不是指向对象的指针.我希望’backgroundColor’的行为类似于我的imstring,因为它是一个指向一个新对象的对象的指针,不是吗?

  4. ios – Xcode Bot:如何在post触发器脚本上获得.ipa路径?

    我正在使用机器人来存档iOS应用程序,我需要获取.ipa产品路径才能将其发布到我们的分发系统中.机器人设置:并使用脚本打印所有env变量,其中不包含ipa文件的路径.此外,一些变量指向不存在的目录,即:XCS_OUTPUT_DIR这里的env变量输出:除此之外,我还能够确认.ipa文件是在另一个文件夹中创建的(/IntegrationAssets//

  5. ios – 使用附加字符串本地化Info.plist变量

    我正在尝试本地化应用程序的名称,同时仍然能够根据构建配置追加字符串.所以目前它被设置为:该设置定义为:通过这种方式,我们可以为应用程序添加后缀以用于不同的beta版本.问题是,当我们尝试本地化本地化的InfoPlist.strings中的应用程序显示名称时,就像这样我们覆盖存储在Info.plist中的值,并丢失后缀字符.这有什么好办法吗?

  6. ios – 在Swift中获取Cocoa Touch Framework项目版本字符串

    有谁知道这是否是我的项目设置中的缺陷,Xcode中的一个错误,或者是否有一种方法可以将Swift中的框架版本作为String或数组获取,这样我可以提供比major.minor更精细的版本控制?

  7. ios – 搜索数组swift中的对象

    我正在尝试使用UISearchController创建搜索功能.但是,我似乎无法使其与我的团队对象一起工作.我首先创建了一个包含id,name和shortname的TeamObject.然后我从一个url中检索teamData,并将TeamObjects添加到一个填充到tableView中的数组中.这个tableView包含一个searchController,它假设过滤数据,但没有任何反应.阵列

  8. iOS – 开始iOS教程 – 变量之前的下划线?

    这是正确的还是我做错了什么?

  9. ios – 静态计算变量被多次实例化

    我有一个日期格式化程序,我试图在UITableViewCell子类中创建一个单例,所以我创建了一个这样的计算属性:问题是我不止一次看到print语句,这意味着它不止一次被创建.我已经找到了其他方法,但我很想知道这里发生了什么.有任何想法吗?解决方法您的代码段相当于只获取属性,基本上它与以下内容相同:如果你只想运行一次,你应该像定义一个惰性属性一样定义它:

  10. ios – UIApplication.delegate必须仅在主线程中使用[复制]

    我应该在主调度中的viewControllers中声明这些)变量位置声明定义了它的范围.您需要确定这些变量的范围.您可以将它们声明为项目或应用程序级别(全局),类级别或特定此功能级别.如果要在其他ViewControllers中使用这些变量,则使用公共/开放/内部访问控制将其声明为全局或类级别.

随机推荐

  1. Swift UITextField,UITextView,UISegmentedControl,UISwitch

    下面我们通过一个demo来简单的实现下这些控件的功能.首先,我们拖将这几个控件拖到storyboard,并关联上相应的属性和动作.如图:关联上属性和动作后,看看实现的代码:

  2. swift UISlider,UIStepper

    我们用两个label来显示slider和stepper的值.再用张图片来显示改变stepper值的效果.首先,这三个控件需要全局变量声明如下然后,我们对所有的控件做个简单的布局:最后,当slider的值改变时,我们用一个label来显示值的变化,同样,用另一个label来显示stepper值的变化,并改变图片的大小:实现效果如下:

  3. preferredFontForTextStyle字体设置之更改

    即:

  4. Swift没有异常处理,遇到功能性错误怎么办?

    本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  5. 字典实战和UIKit初探

    ios中数组和字典的应用Applicationschedule类别子项类别名称优先级数据包contactsentertainment接触UIKit学习用Swift调用CocoaTouchimportUIKitletcolors=[]varbackView=UIView(frame:CGRectMake(0.0,0.0,320.0,CGFloat(colors.count*50)))backView

  6. swift语言IOS8开发战记21 Core Data2

    上一话中我们简单地介绍了一些coredata的基本知识,这一话我们通过编程来实现coredata的使用。还记得我们在coredata中定义的那个Model么,上面这段代码会加载这个Model。定义完方法之后,我们对coredata的准备都已经完成了。最后强调一点,coredata并不是数据库,它只是一个框架,协助我们进行数据库操作,它并不关心我们把数据存到哪里。

  7. swift语言IOS8开发战记22 Core Data3

    上一话我们定义了与coredata有关的变量和方法,做足了准备工作,这一话我们来试试能不能成功。首先打开上一话中生成的Info类,在其中引用头文件的地方添加一个@objc,不然后面会报错,我也不知道为什么。

  8. swift实战小程序1天气预报

    在有一定swift基础的情况下,让我们来做一些小程序练练手,今天来试试做一个简单地天气预报。然后在btnpressed方法中依旧增加loadWeather方法.在loadWeather方法中加上信息的显示语句:运行一下看看效果,如图:虽然显示出来了,但是我们的text是可编辑状态的,在storyboard中勾选Editable,再次运行:大功告成,而且现在每次单击按钮,就会重新请求天气情况,大家也来试试吧。

  9. 【iOS学习01】swift ? and !  的学习

    如果不初始化就会报错。

  10. swift语言IOS8开发战记23 Core Data4

    接着我们需要把我们的Rest类变成一个被coredata管理的类,点开Rest类,作如下修改:关键字@NSManaged的作用是与实体中对应的属性通信,BinaryData对应的类型是NSData,CoreData没有布尔属性,只能用0和1来区分。进行如下操作,输入类名:建立好之后因为我们之前写的代码有些地方并不适用于coredata,所以编译器会报错,现在来一一解决。

返回
顶部