【发布时间】:2020-03-07 14:32:42
【问题描述】:
自从我在 macOS 上做任何工作已经有几年了,自从我接触 Swift 以来已经有两年多了。我在这个圈子里跑来跑去:
我有两个函数,第一个包含一个 while 循环来检查第二个返回的字典中的值。 :
func checkPath(_ strPath:String) {
...
while bIsDesktop == false {
let dictResults:Dictionary<String, Any> = checkPath(arrPath)
if dictResults["isDesktop"] { //-->I'm getting crushed here
//do something with returned array
}
}
private func checkPath(_ arrPath:Array<String>) -> Dictionary<String, Any> {
var bIsDesktop = false
var arrPath = arrPath
if arrPath[0] != "Desktop" {
arrPath.removeFirst()
} else {
bIsDesktop = true
}
return ["paths":arrPath, "isDesktop":bIsDesktop]
}
arrPath 是一个字符串数组(文件路径项)
我知道返回的字典是这样的 [String:Any]
问题是无论我做什么都会遇到某种编译器错误,例如:
Optional type 'Any?' cannot be used as a boolean; test for '!= nil' instead
在更宏大的计划中,如果有更优雅的解决方案,我要做的是剥离 ///File:User/username/Desktop/.. 的用户选择的文件夹的路径。 . 并且只有桌面/... .
我试过了:
guard let bIsDesktop = dictResults["isDesktop" as Bool else { ...
if dictResults?["isDesktop"]...
和其他各种排列。我得到 nil 或编译器错误。
【问题讨论】:
-
查找“条件绑定”。更一般地,阅读 Swift 语言指南,从头到尾。 docs.swift.org/swift-book/LanguageGuide/TheBasics.html
-
老实说,仅通过阅读您的代码,我不知道您要做什么。所以你想删除
Desktop之前的所有内容?如果路径没有Desktop怎么办? -
您不应该使用
String路径来处理文件。请改用URLs,它具有辅助属性/方法,例如lastPathComponent,可以为您的目标派上用场。 -
@DávidPásztor 更好地获取 URL 资源值(本地化名称)stackoverflow.com/questions/28570627/…