V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
mwwfer
V2EX  ›  问与答

Swift 声明空数组问题

  •  
  •   mwwfer · Jun 5, 2014 · 7175 views
    This topic created in 4355 days ago, the information mentioned may be changed or developed.
    Swift中声明变量用var,声明常量用let。
    在苹果官方给的Swift教材中,A Swift Tour中在声明空数组的时候为什么要用let?

    5 replies    2014-06-07 13:09:01 +08:00
    orzfly
        1
    orzfly  
       Jun 5, 2014
    我觉得吧,这里他的 let,只是因为变量名是 emptyArray,按照字面意思,emptyArray 肯定是个常数啦……所以这里用了 let……

    其实这个,自己试试或者深入看看也就知道啦……你看比如后面……

    “Creating and Initializing an Array
    You can create an empty array of a certain type (without setting any initial values) using initializer syntax:

    var someInts = Int[]()
    println("someInts is of type Int[] with \(someInts.count) items.")
    // prints "someInts is of type Int[] with 0 items.”

    Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329
    ffffwh
        2
    ffffwh  
       Jun 5, 2014
    如果是Functional Progamming的话,let才是常用的,var是特别的/慎用的
    SoloCompany
        3
    SoloCompany  
       Jun 6, 2014
    可能是翻译的问题,这里的常量其实并不是我们常规理解的常量的意思,只是不可写的变量而已,相当于 C 的 const 修饰符或者说 java 的 final 修饰符,在 java 里面 public static final 的才是常量,C 的话其实是用 DEFINE 定义常量
    juicy
        4
    juicy  
       Jun 6, 2014
    如果不用let, 万一以后意外被改之后, 那它就不是空数组了, 这和emptyArray这个名字不符, 所以索性一开始就let使该量不能改变
    dagger
        5
    dagger  
       Jun 7, 2014
    @SoloCompany 不要随便误导别人好么,define出来的是宏,跟数据存储是无关的,跟常量变量根本是不同的概念。C里面const定义的是放在ELF的.rodata段里的,是真正的“常量”,java的public static final和swift的let估计也是这么做的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4400 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 05:30 · PVG 13:30 · LAX 22:30 · JFK 01:30
    ♥ Do have faith in what you're doing.