• 【Swift 60秒】09 - Arrays


    0x00 Lesson

    Arrays are collections of values that are stored as a single value. For example, John, Paul, George, and Ringo are names, but arrays let you group them in a single value called The Beatles.
    In code, we write this:

    let john = "John Lennon"
    let paul = "Paul McCartney"
    let george =  "George Harrison"
    let ringo = "Ringo Starr"
    let beatles = [john, paul, george, ringo]
    
    • 1
    • 2
    • 3
    • 4
    • 5

    That last line makes the array: it starts and ends with brackets, with each item in the array separated by a comma.

    You can read values from an array by writing a number inside brackets. Array positions count from 0, so if you want to read “Paul McCartney” you would write this:

    beatles[1]
    
    • 1

    Be careful:
    Swift crashes if you read an item that doesn’t exist. For example, trying to read beatles[9] is a bad idea.

    Note:
    If vou’re using type annotations, arrays are written in brackets: [String], [Int], [Double] and [Bool]


    0x01 Tips

    If your array is empty, even reading array[0] will cause your app to crash. Be careful!


    0x02 Test

    Which of these lines create arrays?

    01

    let status = false, true, true, false
    
    • 1

    02

    let characters: [Int] = ["Doctor Who"]
    
    • 1

    03

    let playlistSizes = (100, 200, 300)
    
    • 1

    04

    let height = "14.0"
    
    • 1

    05

    let age = 26
    
    • 1

    06

    let breeds = {"Labrador", "Chihuahua"}
    
    • 1

    07

    var scores: [Int] = [12,23,24]
    
    • 1

    Answer:
    01 - false: Arrays start and end with square brackets.
    02 - false: This attempts to place a string array into an integer array, which is invalid in Swift.
    03 - false: Arrays start and end with square brackets, [ and ], rather than parentheses.
    04 - false: This creates s string.
    05 - false: This creates an integer.
    06 - false: Arrays start and end with square brackets, [ and ], rather than braces.
    07 - true: This creates an array of three integers.


    0x03 我的小作品

    欢迎体验我的作品之一:小五笔 86 版
    五笔学习好帮手
    App Store 搜索即可~


  • 相关阅读:
    强缓存和协商缓存的理解
    【C语言】空指针&野指针学习小结
    C语言:数组的插入
    Easymesh前言介绍
    Android 组件化 组件上下依赖关系实现
    设计模式:桥接器模式(C++实现)
    go如何读取或设置os的环境变量
    刷题记录:牛客NC51170石子合并
    <Android开发> Android vold - 第二篇 vold 的main()函数简介
    信息学奥赛一本通:1311:【例2.5】求逆序对
  • 原文地址:https://blog.csdn.net/xjh093/article/details/126776740