How to convert this Swift syntax into Objective-C?

user5622777

I am converting a Swift Library into Objective-C as an exercise.

How to convert this into Objective-C ?

let formatter = NSDate.formatter(format: dateFormat)

I tried:

NSDateFormatter *formatter = [NSDate formatterWithFormat : dateFormat];

Also tried this:

NSDateFormatter *formatter = [NSDate formatterWithFormat : dateFormat : [NSTimeZone localTimeZone] : [NSLocale currentLocale]];

Also tried this:

NSDateFormatter *formatter = [NSDate formatter : dateFormat : [NSTimeZone localTimeZone] : [NSLocale currentLocale]];

Error: no know class method for selector "formatterWithFormat:" or "formatter :::"

More context:

+ (NSDateFormatter *) formatter : (NSString *) format  : (NSTimeZone*) timeZone  : (NSLocale *) locale {
    format = DefaultFormat;
    timeZone = [NSTimeZone localTimeZone];
    locale = [NSLocale currentLocale];
    NSString *hashKey = [NSString stringWithFormat:@"%lu%lu%lu", (unsigned long)format.hash, (unsigned long)timeZone.hash, (unsigned long)locale.hash];
    NSMutableDictionary *formatters = [NSDate sharedDateFormatters];
    NSDateFormatter *cachedDateFormatter = formatters[hashKey];
    if (cachedDateFormatter != nil) {
        return cachedDateFormatter;
    }
    else {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = format;
        formatter.timeZone = timeZone;
        formatter.locale = locale;
        formatters[hashKey] = formatter;
        return formatter;
    }
}

Some random text in-between so SO will let me add more code...

+ (NSDateFormatter *)formatter:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle relativeDateFormatting:(BOOL)doesRelativeDateFormatting timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale {
    timeZone = [NSTimeZone localTimeZone];
    locale = [NSLocale currentLocale];
    NSString *hashKey = [NSString stringWithFormat:@"%lu%lu%lu%lu%lu", (unsigned long)dateStyle, (unsigned long)timeStyle, (unsigned long)doesRelativeDateFormatting, (unsigned long)timeZone.hash, (unsigned long)locale.hash];
    NSMutableDictionary *formatters = [NSDate sharedDateFormatters];
    NSDateFormatter *cachedDateFormatter = formatters[hashKey];
    if (cachedDateFormatter != nil) {
        return cachedDateFormatter;
    }
    else {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateStyle = dateStyle;
        formatter.timeStyle = timeStyle;
        formatter.doesRelativeDateFormatting = doesRelativeDateFormatting;
        formatter.timeZone = timeZone;
        formatter.locale = locale;
        formatters[hashKey] = formatter;
        return formatter;
    }
}

Original Swift code:

private class func formatter(format format:String = DefaultFormat, timeZone: NSTimeZone = NSTimeZone.localTimeZone(), locale: NSLocale = NSLocale.currentLocale()) -> NSDateFormatter {
            let hashKey = "\(format.hashValue)\(timeZone.hashValue)\(locale.hashValue)"
            var formatters = NSDate.sharedDateFormatters()
            if let cachedDateFormatter = formatters[hashKey] {
                return cachedDateFormatter
            } else {
                let formatter = NSDateFormatter()
                formatter.dateFormat = format
                formatter.timeZone = timeZone
                formatter.locale = locale
                formatters[hashKey] = formatter
                return formatter
            }
        }

Some random text in-between so SO will let me add more code...

private class func formatter(dateStyle dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle, doesRelativeDateFormatting: Bool, timeZone: NSTimeZone = NSTimeZone.localTimeZone(), locale: NSLocale = NSLocale.currentLocale()) -> NSDateFormatter {
        var formatters = NSDate.sharedDateFormatters()
        let hashKey = "\(dateStyle.hashValue)\(timeStyle.hashValue)\(doesRelativeDateFormatting.hashValue)\(timeZone.hashValue)\(locale.hashValue)"
        if let cachedDateFormatter = formatters[hashKey] {
            return cachedDateFormatter
        } else {
            let formatter = NSDateFormatter()
            formatter.dateStyle = dateStyle
            formatter.timeStyle = timeStyle
            formatter.doesRelativeDateFormatting = doesRelativeDateFormatting
            formatter.timeZone = timeZone
            formatter.locale = locale
            formatters[hashKey] = formatter
            return formatter
        }
    }
rmaddy

Based on all your updates, the key difference between your Objective-C code and Swift code is that the Swift function provides default values for the parameters. This allows you to call the function (in this case) with zero or more arguments.

Since Objective-C doesn't support default parameter values, you need to pass a value for every parameter.

The method:

+ (NSDateFormatter *) formatter : (NSString *) format  : (NSTimeZone*) timeZone  : (NSLocale *) locale {
}

Needs to be called as:

[WhateverClassThisIs formatter:someFormat :someTimeZone :someLocale];

Note the ugly syntax due to you not naming all of the parameters (like I showed in your previous question.

You also need to remove the lines you added to assign values to those parameters at the start of the method.

Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.

En caso de infracción, por favor [email protected] Eliminar

Editado en
0

Déjame decir algunas palabras

0Comentarios
Iniciar sesiónRevisión de participación posterior

Artículos relacionados

How to use Objective-C enum in Swift

How to call an Objective C class method in Swift

Как я могу отправлять (и получать) чрезвычайно большие плавающие массивы из Swift в Objective c ++ в c ++, а затем выполнять резервное копирование в Swift?

Разница между перечислителем и итератором в Swift или Objective C

Увеличивает ли добавление библиотек Objective-C в проект Swift размер приложения?

Как преобразовать строку кода из Objective-C в Swift в массиве сортировки?

Невозможно вызвать некоторые функции Swift из Objective-c (другие работают)

Как вы вызываете вариативный метод Swift из Objective-C?

преобразование objective-c в синтаксис swift: @ ()

Используйте классы Swift в файлах Bridging Objective C

Свойство, определенное в файле Objective C, не отображается в Swift (та же цель)

How to use a swift module in an objective-c module with SwiftPM?

How to make a Swift String enum available in Objective-C?

How to access a private objective C variable in Swift View Controller?

How can method in Swift with inout parameter be used in Objective-C?

How to use Objective-C framework in Swift without Bridging Header?

How rewrite Objective-C Macro expand with swift

Different result for objective-c syntax and C syntax

Ошибка сборки при использовании как библиотеки objective-c, так и библиотеки swift с Cocoapods

iOS Swift to Objective-C как передавать слабые ссылки на массивы?

Объявите строку с типом данных char в файле Objective c .m и используйте ее в Swift

Фреймворк Typhoon: Swift или Objective-C

Как вызвать код Swift из Objective-C в целевой платформе Framework?

Извлечение значения из SwiftDeferredNSDictionary по ключу в Objective C, где ключ - это Swift enum

Можно ли использовать модуль, написанный на Swift, в проекте Objective-C, если классы не имеют префикса `@ objc`?

Вызов функции Objective-C, определенной в файле .h из Swift

How to convert lambda syntax to regular syntax?

Convert an iOS objective c object to a JSON string

How to convert english numbers inside a string to Persian/Arabic numbers in Objective-C?

TOP Lista

CalienteEtiquetas

Archivo