zoukankan      html  css  js  c++  java
  • swift 有道 翻译文档(1 定义变量常量,数组字典)

    使用let来创建常量,使用var来创建变量。一个常量的值在编译时不需要知道,但是您必须为它指定一个值一次。这意味着您可以使用常量来命名一个您确定一次的值,但是在许多地方使用它。
    var myVariable = 42
    myVariable = 50
    let myConstant = 42


    常量或变量的类型必须与要赋给它的值相同。然而,您不必总是显式地编写类型。在创建常量或变量时提供一个值,让编译器推断其类型。在上面的例子中,编译器推断myVariable是一个整数,因为它的初始值是一个整数。
    如果初始值没有提供足够的信息(或者没有初始值),可以在变量后面用冒号分隔的地方写类型。
    let implicitInteger = 70
    let implicitDouble = 70.0

    let explicitDouble: Double = 70

    “实验
    创建一个具有明确类型的浮点数和值为4的常量。
    值永远不会隐式转换为另一种类型。如果需要将值转换为不同的类型,请显式地创建所需类型的实例。
    let label = "The width is "
    let width = 94
    let widthLabel = label + String(width)


    实验
    试着从最后一行删除到字符串的转换。你会得到什么错误?
    在字符串中包含值有一种更简单的方法:将值写在圆括号中,并在圆括号前写反斜杠()。例如:“
    摘录来自:苹果(aapl . o:行情)”。快速编程语言(斯威夫特4)。“iBooks。

    let apples = 3
    let oranges = 5
    let appleSummary = "I have (apples) apples."
    let fruitSummary = "I have (apples + oranges) pieces of fruit.”

    实验
    使用()在字符串中包含浮点运算,并在问候中包含某人的名字。
    使用三个双引号(""")来表示包含多行内容的字符串。每个引用行开头的缩进被删除,只要它与结束引用的缩进匹配。例如:

    let quotation = """
    Even though there's whitespace to the left,
    the actual lines aren't indented.
    Except for this line.
    Double quotes (") can appear without being escaped.

    I still have (apples + oranges) pieces of fruit.
    ""

    使用方括号([])创建数组和字典,并通过在方括号中写入索引或键来访问它们的元素。最后一个元素后面允许有逗号。

    var shoppingList = ["catfish", "water", "tulips", "blue paint"]
    shoppingList[1] = "bottle of water"

    var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
    ]
    occupations["Jayne"] = "Public Relations

    要创建空数组或字典,请使用初始化器语法。

    let emptyArray = [String]()
    let emptyDictionary = [String: Float]()

    如果可以推断类型信息,您可以将空数组写为[],将空字典写为[:]——例如,为变量设置新值或向函数传递参数时。

    shoppingList = []
    occupations = [:]

  • 相关阅读:
    Java集合中迭代器
    java 基础归纳总结(三)
    java 基础归纳总结(二)
    java 基础归纳总结(一)
    python之hashlib模块
    python之configparser模块
    Python之time模块
    python之os模块
    python之random模块
    python generator(生成器)
  • 原文地址:https://www.cnblogs.com/ccw-congcong/p/9474572.html
Copyright © 2011-2022 走看看