gpt4 book ai didi

ios - 选项的 Swift 问题

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:12 26 4
gpt4 key购买 nike

我是一个敏捷的新手,一直在兜圈子,试图让可选项发挥作用。我已经做了很多谷歌搜索,阅读了 Apple Docs 等,但我正在为我的 ViewController 中的这个(简化的)片段而苦苦挣扎:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "segueToWebView") {
// check what we're passing around
print(sender!.urlString) // Optional("http://www.bbc.co.uk")

// do some url validation etc
var destUrl:String
if sender!.urlString == nil{
destUrl = "http://www.google.com"
} else {
destUrl = sender!.urlString // *** Error here ***
}

let targetWebViewController:GDWebViewController = segue.destinationViewController as! GDWebViewController
targetWebViewController.loadURLWithString(destUrl)
targetWebViewController.showsToolbar = true
targetWebViewController.title = sender!.busName // this works correctly too (so isn't that a String?)
}
}

错误是 Cannot assign value of type 'String?!'在上面标记的行中键入“String”。我试过以不同的方式打开它,但就是想不通。

更多代码

发送者是一个自定义的 UIButton 子类,具有以下结构:

import UIKit

class TestButton: UIButton {
var urlString: String?
var busName: String?
}

我已将变量设置为可选,因为我不知道按钮是否具有这些属性。

点击按钮时调用的方法是这样的:

func tapTap(sender: TestButton) {
print(sender.busName, sender.urlString) // Optional("My Button") Optional("http://www.bbc.co.uk")
self.performSegueWithIdentifier("segueToWebView", sender: sender)
}

我知道 Swift 可选值对于像我这样的新手来说是一个常见的绊脚石,并且有很多关于它们的文档,但我无法弄清楚所以任何帮助都会很棒。

最佳答案

有三个层次的可选:

  • sender: AnyObject? 参数是可选的。
  • AnyObject 发送任意消息的行为类似于可选的链接并返回一个隐式解包的可选(比较 The strange behaviour of Swift's AnyObject )。
  • var urlString: String? 属性是可选的。

要解析前两个可选值,请使用可选绑定(bind)/转换到具体按钮类:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "segueToWebView") {
if let button = sender as? TestButton {
// The type of `button` is `TestButton`
// ...
}
}
}

现在

var destUrl: String
if button.urlString == nil {
destUrl = "http://www.google.com"
} else {
destUrl = button.urlString!
}

会编译,但最好用零合并运算符:

let destUrl = button.urlString ?? "http://www.google.com"

请注意,不再有强制解包 ! 运算符!

关于ios - 选项的 Swift 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37592976/

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