Swift 学习笔记第一天-变量常量,及数据类型

1.定义变量

 用关键字 var

比如 var i=2

2.定义常量用let

 如let c=3

 可见Swift 定义时不用指定类型。由编译器推断

  如果想指定类型

 var i:Int32=2

 练习

let apples=3

var h:Int32=32

h=32

let cs="i love (apples + h)as"

cs 得结果

会发现程序报错。a

could not find member ''convertfromstringInterpolationSegment"

 由此可见Swift  会将默认将类型推断为双精度

正确程序为

let apples:Int32=3

var h:Int32=32

h=32

let cs="i love (apples + h)as"

2 .定义数组

  

var shoppingList=["haha","as",3,32.00]

可见数组中得元素类型可以不同。

将数组元素赋给定义得一个变量

var s= shoppingList[0]


会发现报错
错误如下
prefix /postfix=is reserved
这个错误我开始以后是var只能定义值类型得原因
google才发现很有意思得一个错误

2down voteaccepted

Add a space after the =. (=[ looks too sad to be an operator.) It's probably seeing =value as a use of a (possible, but not implemented) prefix operator.

Swift isn't entirely whitespace-agnostic like C... in particular, it uses whitespace to distinguish prefix from postfix operators (because ++i++ in C is a grammar oddity). But it's not ridiculously strict about whitespace like Python either.

 =号前后空格是有一侧存在得是保留运算附

修改为

var s:String=shoppingList[0]

会发现报错

anyObject is not  转换成string 

可见数组是指针引用类型

正确写法是

var s:String=shoppingList[0] asNSString

定义字典

var occupations=[

    "Malcolm": "Captain",

    "Kaylee": "Mechanic",

]

occupations["Jayne"] = "Public Relations"

把字典中value得类型变化下

var occupations=[

    "Malcolm": "Captain",

    "Kaylee": 2,

]

occupations["Jayne"] = "Public Relations"

会发现报错

原文地址:https://www.cnblogs.com/zhang888/p/3776895.html