Tejas Ardeshna
Tejas Ardeshna

Reputation: 4371

Method 'fontWithName(_:size:)' conflict with Objective-C selector

I am trying to create an extension for UIFont. But that show error describe below

Method 'fontWithName(_:size:)' with Objective-C selector 'fontWithName:size:' conflicts with previous declaration with the same Objective-C selector

Extension class code:

import UIKit
import Foundation

extension UIFont {

    class func fontWithName(fontName: String, size fontSize: CGFloat) -> UIFont {
        return UIFont(name: fontName, size: fontSize + 5)!
    }
}

See Image *enter image description here*

Upvotes: 0

Views: 539

Answers (2)

UIResponder
UIResponder

Reputation: 983

This method name is not agreed because, there is already an init method present in UIFont class.

// Returns a font using CSS name matching semantics.
    public /*not inherited*/ init?(name fontName: String, size fontSize: CGFloat)

Now, Swift parses your method and finds it similar to default init method in UIFont.

// Returns a font using CSS name matching semantics.
+ (nullable UIFont *)fontWithName:(NSString *)fontName size:(CGFloat)fontSize;

Try changing your method name without losing its purpose (name telling purpose.) You'll get your method working.

Example:

func fontName(fontName: String, size fontSize: CGFloat) -> UIFont {
    return UIFont(name: fontName, size: fontSize + 5)!
}

Upvotes: 1

Jelly
Jelly

Reputation: 4522

Objective C does not support method overloading and since NSFont is a Objective C class which already has a method with that name it results in a conflict. However if you still want to use that name for the method you could check out this solution: https://stackoverflow.com/a/31500740/1949494 .Otherwise just rename the method.

Upvotes: 0

Related Questions