gpt4 book ai didi

Swift 无法解开可选内容

转载 作者:行者123 更新时间:2023-11-30 10:02:19 24 4
gpt4 key购买 nike

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples: pattern = "abba", str = "dog cat cat dog" should return true.

pattern = "abba", str = "dog cat cat fish" should return false.

pattern = "aaaa", str = "dog cat cat dog" should return false.

pattern = "abba", str = "dog dog dog dog" should return false.

Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

class Solution
{
func wordPattern(pattern: String, _ str: String) -> Bool
{

let arr = str.characters.split{$0 == " "}.map(String.init)
if arr.count != pattern.characters.count
{
return false
}

var dict = [Character:String]()

for i in (0...arr.count-1)
{
let cha = pattern[pattern.startIndex.advancedBy(i)]

if dict.keys.contains(cha)
{
if dict[cha]! != arr[i]
{
return false
}
}
else
{
if dict.values.contains(dict[cha]!)
//fatal error: unexpectedly found nil while unwrapping an Optional value
{
return false
}

dict[cha] = arr[i]
}

}
return true
}
}


var test = Solution()
var result = test.wordPattern("abba", "dog cat cat dog")
print(result)

I do not know "fatal error: unexpectedly found nil while unwrapping an Optional value". Any help, I appreciate it. Thank you so much!

最佳答案

修改您的条件。

dict.keys.contains(cha)false 时,换句话说,当字典不存在时,将执行您的 else 分支包含cha。然后,您尝试访问您已经知道必须返回 nil 的 dict[cha] (因为 cha 不在字典中)。然后你尝试打开它。展开 nil 会使您的应用程序崩溃。

还要考虑该条件正在尝试检查从字典中获取的值是否包含在字典中。你想做什么?

您想要的可能只是(注意,没有令人讨厌的 !):

let arrayValue = arr[i]

if let value = dict[cha] {
if value != arrayValue {
return false
}
} else {
if dict.values.contains(arrayValue) { // maybe this? it's hard to guess
return false
}

dict[cha] = arrayValue
}

关于Swift 无法解开可选内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767296/

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