【问题标题】:Trouble with NSDictionary functions in SwiftSwift 中 NSDictionary 函数的问题
【发布时间】:2014-06-13 10:36:28
【问题描述】:

我有以下imageMap 在名为ClassClass 中返回NSDictionary,称为WXCondition

+ (NSDictionary *)imageMap {
    // 1
    static NSDictionary *_imageMap = nil;
    if (! _imageMap) {
        // 2
        _imageMap = @{
          @"01d" : @"weather-clear",
          @"02d" : @"weather-few",
          @"03d" : @"weather-few",
          @"04d" : @"weather-broken",
          @"09d" : @"weather-shower",
          @"10d" : @"weather-rain",
          @"11d" : @"weather-tstorm",
          @"13d" : @"weather-snow",
          @"50d" : @"weather-mist",
          @"01n" : @"weather-moon",
          @"02n" : @"weather-few-night",
          @"03n" : @"weather-few-night",
          @"04n" : @"weather-broken",
          @"09n" : @"weather-shower",
          @"10n" : @"weather-rain-night",
          @"11n" : @"weather-tstorm",
          @"13n" : @"weather-snow",
          @"50n" : @"weather-mist",
      };
    }
    return _imageMap;
}

然后我有以下方法返回 imageMap 方法:

- (NSString *)imageName {
    return [WXCondition imageMap][self.icon];
}

我正在尝试将这些方法转换为 Swift,到目前为止我有以下内容:

func JSONKeyPathsByPropertyKey() -> NSDictionary {
    return {
        "date": "dt",
        "locationName": "name",
        "humidity": "main.humidity",
        "temperature": "main.temp",
        "tempHigh": "main.temp_max",
        "tempLow": "main.temp_min",
        "sunrise": "sys.sunrise",
        "sunset": "sys.sunset",
        "conditionDescription": "weather.description",
        "condition": "weather.main",
        "icon": "weather.icon",
        "windBearing": "wind.deg",
        "windSpeed": "wind.speed"
    }
}

func imageName() -> NSString {
    return "" //[WXCondition imageMap][self.icon];
}

不太清楚如何正确返回NSDictionary

【问题讨论】:

    标签: objective-c nsdictionary swift


    【解决方案1】:

    + 方法称为class 方法。在 Swift 中,您使用关键字 class。如果您需要NSDictionary,您可以创建一个普通字典,然后只需使用as 关键字(您也可以将其桥接到目标c,但这更明确)。所以这就是你最终会得到的:

    class func blah() -> NSDictionary {
        return [
            "date": "dt",
            "locationName": "name"
            // ...
        ] as NSDictionary
    }
    

    您的第二个函数(虽然我没有看到太多关于它的信息)可能只是修改为:return WXCondition.imageMap()[self.icon](您可能需要包含as NSString,具体取决于信息的来源和您的内容正在尝试使用它)

    【讨论】:

      【解决方案2】:

      试试这个:

      class A {
          class func myDict() -> NSDictionary {
              var occupations = [
                  "Malcolm": "Captain",
                  "Kaylee": "Mechanic",
              ]         
              return NSDictionary(dictionary: occupations)
          }
      }
      println("Test = \(A.myDict())")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 2020-06-25
        • 1970-01-01
        • 2014-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多