Swift 初体验-简单值

来源:互联网 发布:南财网络教学平台 编辑:程序博客网 时间:2024/05/10 13:26
//: [Previous](@previous)/**    1. 第一行可执行程序就当做程序的入口    2. 不需要单独引用一个库    3. 不需要 main() 函数, 结尾也不需要 ';' */print("Hello world!")/**    1. 常量(值不能改变)用let表示    2. 变量(值可以被改变)用var 表示 */var myVariable = 42myVariable = 50let myConstant = 42/**    1. Swift编译器会自动推断类型    2. 默认的整形是 Int 类型    3. 默认的浮点型是 Double 类型    4. 推断不出的话,在变量后面声明类型 格式: 变量 : 类型    *. 可以使用 Option + 鼠标左键 查看类型 */let implicitInteger = 70let implicitDouble = 70.0let explicitDouble : Double = 70/**    1. Swift 中,永远不会存在隐式转换,如果需要转换成其他类型,需要显示转换, Double + Float 也不可以    2. 转换为字符串,可 \() 的方式 和 String() */let label = "The width is "let width = 94let widthLabel = label + String(width)let apples = 3let oranges = 5let appleSummary = "I have \(apples) apples"let fruitSummary = "I have \(apples + oranges) pieces of fruit"// 附加案例let doubleValue = 70.0let intValue = 70let floatValue : Float = 35.0let doubleSum = doubleValue + Double(intValue)let floatSum = Float(doubleValue) + floatValue/**    1. 数组和字典 都是可以使用 [] 来创建的    2. 数组可以使用下标来访问元素    3. 字典可以使用键(key)来访问元素 */var shoppingList = ["catfish", "water", "tulips", "blue paint"]shoppingList[1] = "bottle of water"shoppingListvar occupations = ["Malcolm": "Captain",                   "Kaylee": "Mechanic",]occupations["Jayne"] = "Public Relations"occupations/**    1. 创建空数组 & 空字典,需要指定对应的类型    2. 尽量使用Swift的自动推断功能 */// let emptyArray : [String] = [String]() 可以自动推导let emptyArray = [String]()let emptyDictionary = [String : Float]()//: [Next](@next)
0 0
原创粉丝点击