最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】swift代码提示:Initialization of variable was never used consider replacing with assignment to _ or removing it

Swift crifan 4091浏览 0评论

【背景】

一个swift文件中代码:

  var cmp1:NSDateComponents = calendar.components(unitFlags, fromDate:lastUpdateTime)

提示:

RefreshHeaderView.swift:81:13: Initialization of variable ‘cmp1’ was never used; consider replacing with assignment to ‘_’ or removing it

 

Initialization of variable was never used consider replacing with assignment to _ or removing it

 

【解决过程】

1.然后点击行首的黄色警告箭头,可以自动建议提醒如何改正:

tip fix it replace with _ in xcode

点击了之后,修改为:

   _:NSDateComponents = calendar.components(unitFlags, fromDate:lastUpdateTime)

2.但是自己要去搞清楚,到底是为什么这么修改,具体是什么含义。

再去根据建议修改。

3.搜:

Initialization of variable was never used; consider replacing with assignment to ‘_’ or removing it

参考:

ios – When trying to convert a UITextField text to Int Xcode 7 gives me an error – Stack Overflow

swift – static protocol extensions generates Illegal Instruction compiler error – Stack Overflow

还是没人说清楚:

为何要换成一个 下划线 _ ?

4.所以再去研究:

swift 下划线 _ 含义

参考:

Swift中下划线和"#"的妙用 – CocoaChina 苹果开发中文站 – 最热的iPhone开发社区 最热的苹果开发社区 最热的iPad开发社区

看懂了:

忽略,不需要关系的值,就用下划线

->和之前折腾过的GO语言中的下划线,完全是同一个意思。

5.Swift中下划线和"#"的妙用 – CocoaChina 苹果开发中文站 – 最热的iPhone开发社区 最热的苹果开发社区 最热的iPad开发社区

好像又和GO中不完全一样:

此处swift中,可以在变量前面 用一个空格隔开,加上一个下划线,变成:

忽略函数中第二个参数,让其不作为外部参数

6.第 3 章 Swift基本语法

好像又不是。感觉没有说透。

7.去搜:

swift underscore meaning

参考:

objective c – What’s the _ underscore representative of in Swift References? – Stack Overflow

还是这里解释的清楚。

 

【总结】

Swift中的下划线的含义,分两种:

(1)下划线对于普通变量:

用于忽略变量的

The underscore is a general token used to indicate a discarded value.

举例:

for _ in 0..<5 { ... }

let (result, _) = someFunctionThatReturnsATuple()

(2)用于函数function和方法method,可以忽略第二个之后的参数的外部名称

举例:

class Bar{
    func foo(s1: String, s2: String) -> String {
        return s1 + s2;
    }
}

调用是:

bar.foo("Hello", s2: "World")

加上下划线的话:

func foo(s1: String, _ s2: String) -> String{
    return s1 + s2;
}

调用方式可以不加第二个函数的外部函数名:

bar.foo("Hello", "World")

详见:

Local and External Parameter Names for Methods

The Swift Programming Language (Swift 2): Methods

至此,基本明白下划线的含义了。

所以去修改为 :

根据提示,换成下划线_即可。

转载请注明:在路上 » 【已解决】swift代码提示:Initialization of variable was never used consider replacing with assignment to _ or removing it

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.161 seconds, using 22.08MB memory