gpt4 book ai didi

swift - Swift 中的字典值

转载 作者:行者123 更新时间:2023-11-30 10:15:51 29 4
gpt4 key购买 nike

我正在尝试访问我在 Swift 字典中设置的值。字典有一个用于键和值的String。我的目的是在处理一系列 URL 时使用字典来设置字符串变量。在 Objective-C 中我理解它是如何工作的。我有一个名为 currentFeed 的字符串属性,我将字典的值传递给它。

self.currentFeed = [NSString stringWithString: [self.URLDictionary objectForKey: @"FLO Cycling"]];

在 Swift 中我遇到了困难。我尝试了以下代码并收到错误消息。

self.currentFeed = self.URLDictionary["FLO Cycling"]

Error Message: "Cannot subscript a value of type '[String:String]' with an index of type 'String'.

作为引用,字典是通过以下方式在 Swift 中创建的。常量是用 let 创建的。

let kFLOCyclingURL = "http://flocycling.blogspot.com/feeds/posts/default?alt=rss"
let kTriathleteURL = "http://triathlon.competitor.com/feed"
let kVeloNewsURL = "http://velonews.competitor.com/feed"
let kCyclingNewsURL = "http://feeds.feedburner.com/cyclingnews/news?format=xml"
let kRoadBikeActionURL = "http://www.roadbikeaction.com/news/rss.aspx"
let kIronmanURL = "http://feeds.ironman.com/ironman/topstories"

这些项目已通过键添加到字典中。

let URLTempDictionary = ["FLO Cycling" : kFLOCyclingURL, "Triathlete" : kTriathleteURL, "Velo News" : kVeloNewsURL, "Cycling News" : kCyclingNewsURL, "Road Bike Action" : kRoadBikeActionURL, "Ironman" : kIronmanURL]

感谢您的帮助。

保重,

乔恩

最佳答案

这对我来说编译得很好。我唯一注意到的是您的字典名为 URLTempDictionary 并且您正在访问 URLDictionary。 :)

选项a(最安全、最稳健)

if let dict = self.URLDictionary
{
self.currentFeed = dict["FLO Cycling"]
}

选项b(谨慎使用,可能出现运行时错误)

self.currentFeed = dict!["FLO Cycling"]

关于swift - Swift 中的字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30059494/

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