在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Swift使用let关键字声明常量,var关键字声明变量。常量无需在编译时指定,但至少要被赋值一次。也就是说,赋值一次多次使用: 1 var myVariable = 42 2 myVariable = 50 3 let myConstant = 42
一个常量或变量的值与类型必须是一致的。不过,你不需要指明它的类型,因为编译器会根据你所赋的值推断它的类型,在上面的例子中,编译器会判断到myVariable是一个整型(integer),因为它的初始值是一个整数。 如果初始值的信息不够明确(以至于类型不好判断),可以在变量名后用冒号写明类型: 1 let implicitInteger = 70 2 let implicitDouble = 70.0 3 let explicitDouble: Double = 70
值永远不会隐含转换到其他类型。如果你需要转换一个值到其它不同类型,明确的构造一个所需类型的实例。 let label = "The width is " let width = 94 let widthLabel = label + String(width)
还有一种更简单的字符串中含值的方式:把值放在小括号里面,并以反斜线开头,如: let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit.
用[]创建数组或字典,并使用下标或键名访问: 1 “var shoppingList = ["catfish", "water", "tulips", "blue paint"] 2 shoppingList[1] = "bottle of water" 3 4 var occupations = [ 5 "Malcolm": "Captain", 6 "Kaylee": "Mechanic", 7 ] 8 occupations["Jayne"] = "Public Relations” 创建一个空数组或字典,使用初始化赋值语句: 1 “let emptyArray = String[]() 2 let emptyDictionary = Dictionary<String, Float>()” 如果类型信息无法推断,你可以写空的数组-- "[]" 或空的字典--"[:]",例如你为变量赋新值或为函数传参: shoppingList = [] //Went shopping and bought everything.
Swifter-QQ群:362232993,同好者进~ github地址:https://github.com/Joejo/Swift-lesson-for-chinese
|
请发表评论