Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS SWIFT: Declaration is only valid at file scope

Tags:

ios

swift

iphone

Normally in C# I used to implement extension methods in a separate class (named 'ExtensionMethods') and used in the project.

Here in my first swift iphone App I need to implement some extension methods to 'String' class but providing me with this error

enter image description here

This works perfect with swift Playground but not sure how to use in a real project. really appreciate if someone can guide me with this. Thanks.

like image 619
JibW Avatar asked Jan 09 '23 00:01

JibW


1 Answers

The extension must be at the root level - don't embed them into a class or whatever. So just write:

import UIKit

extension String {
    var doubleValue: Double {
        ...
    }
}

extension String {
    func doubleValueT() -> Double {
        ...
    }
}

Note that you can also combine them into a single extension:

import UIKit

extension String {
    var doubleValue: Double {
        ...
    }

    func doubleValueT() -> Double {
        ...
    }
}
like image 196
Antonio Avatar answered Jan 15 '23 04:01

Antonio