Swift 在警卫声明之后,还有其他的,但还有其他的,为什么它会抱怨?

Swift 在警卫声明之后,还有其他的,但还有其他的,为什么它会抱怨?,swift,Swift,我正在尝试执行PropertyListSerialization,而不是只使用NSDictionary(contentsOfFile:),因此我为此更改了代码。现在使用guard,我必须给出else。我正在提供其他。我在这行代码中犯了什么错误 它说: “防护”条件后应为“其他” 使用NSDictionary(contentsOfFile:)时,这行代码运行正常。但是对PropertyListSerialization的更改对我不起作用 guard let

我正在尝试执行
PropertyListSerialization
,而不是只使用
NSDictionary(contentsOfFile:)
,因此我为此更改了代码。现在使用
guard
,我必须给出
else
。我正在提供
其他
。我在这行代码中犯了什么错误

它说:

“防护”条件后应为“其他”

使用
NSDictionary(contentsOfFile:)
时,这行代码运行正常。但是对
PropertyListSerialization
的更改对我不起作用

        guard
            let filePathValue = filePath,
//            let fileContentDictionary:NSDictionary = NSDictionary(contentsOfFile: filePathValue)
        let data = try? Data(contentsOf: filePathValue as URL),

        let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String:Any]]
            print(result!)

        else{
            return
        }

您的
打印(结果!)
是一个问题

移除它

更新:

guard let filePathValue = filePath,
      //let fileContentDictionary: NSDictionary = NSDictionary(contentsOfFile: filePathValue)
      let data = try? Data(contentsOf: filePathValue as URL),
      let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String:Any]]
else {
    return
}

print(result!)

如果您的响应是
dictionary
,那么您需要将
propertyList(from:options:format:)
的结果强制转换为
[String:Any]
而不是
[[String:Any]
,因为它是dictionary

guard let filePathValue = filePath,
    //let fileContentDictionary: NSDictionary = NSDictionary(contentsOfFile: filePathValue)
    let data = try? Data(contentsOf: filePathValue as URL),
    let result = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String:Any] //not [[String:Any]]
else {
    return
}
//Result is still optional
print(result!)
现在,您已经使用了
try?
您的结果仍然是可选的,所以如果您希望结果是非可选的,那么像这样使用
()
try?

guard let filePathValue = filePath,
    //let fileContentDictionary: NSDictionary = NSDictionary(contentsOfFile: filePathValue)
    let data = try? Data(contentsOf: filePathValue as URL),
    let result = (try? PropertyListSerialization.propertyList(from: data, options: [], format: nil)) as? [String:Any] //not [[String:Any]]
else {
    return
}
//Now result is non-optional
print(result)

基本
guard else
块如下所示:

guard `condition` else {
    `statements`
}
例如:

guard let name = optionalName else {
    // Value requirements not met, do something.
    // name isn't available here
    return
}
// Value requirements met, do something with name
// name is available here
// Rest of the code goes here
<>你必须考虑<代码>守护者> /COD>作为一个单一的程序控制语句。他们之间没有任何声明。只检查条件。您可能有多个条件,以逗号(,)分隔

它说:

从可选绑定中指定值的任何常量或变量 guard语句条件中的声明可用于 guard语句的封闭范围


你在中间写了print(result!)是的,请你解释一下为什么print(result!)没有给出问题。我想打印结果,我应该怎么做?请解释,为什么这是一个问题,如果我想,我如何打印结果。