gpt4 book ai didi

ios - 为什么我收到警告 "Expression implicitly coerced from ' xx ?' to ' Any'”?

转载 作者:行者123 更新时间:2023-11-29 05:41:51 31 4
gpt4 key购买 nike

自从 swift5 以来,我收到了一个让我很困惑的警告......

当我的 View 中有应该可以修改的约束时,它通常看起来像这样:

class myView: UIView {

let titleLabel = UILabel()
let descriptionLabel = UILabel()

var titlePaddingConstraint: NSLayoutConstraint!

func setupConstraints() {
self.titlePaddingConstraint = self.titleLabel.bottomAnchor.constraint(equalTo: self.descriptionLabel.topAnchor, constant: -20)

NSLayoutConstraint.activate([
self.titlePaddingConstraint //warning here
])
}
}

在第四行最后一行 XCode 提示:

Expression implicitly coerced from 'NSLayoutConstraint?' to 'Any'

为了让它关闭,我必须添加“bang 运算符 (!)”来打开它。为什么现在需要这个? titlePaddingConstraint 在声明时被强制展开。这不是应该完全避免该对象的展开吗?

最佳答案

实际上,activate 方法接受一个 NSLayoutConstraints 数组,您在其中犯了错误。将您的类(class)更新为,

class MyView: UIView {

let titleLabel = UILabel()
let descriptionLabel = UILabel()

var titlePaddingConstraint: NSLayoutConstraint!

func setupConstraints() {
self.titlePaddingConstraint = self.titleLabel.bottomAnchor.constraint(equalTo: self.descriptionLabel.topAnchor, constant: -20)

NSLayoutConstraint.activate([self.titlePaddingConstraint])
}
}

关于ios - 为什么我收到警告 "Expression implicitly coerced from ' xx ?' to ' Any'”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56478438/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com