I am new to swift and I am trying to figure out how to add a function that could be usable throughout the entire project. A simple function like
func globalFunction() {
println("Global function!")
}
Then be able to call this function on any swift file within my project. Where would I declare this function?
Its just like in any programming language - declaring the function outside the class, something like:
class A
{
var a:Int
// you can call your global function here
}
class B
{
var b:Int
// and here
}
func flobalFunction()
{
println("Hello, I am a global function!")
}
Use static functions if you still want to bind the method to a class:
class myClass{
static func globalFunc() -> Void {
println("This is it")
}
}
myClass.globalFunc()
You can add a .swift file in your project and declare your functions. Functions declared in this file will be available in the same module.
By default, variables, constants, and other named declarations that
are declared at the top-level of a source file are accessible to code
in every source file that is part of the same module.
Taken from The Swift programming language, see section on Top-Level Code.
If it is a helper function, you can create a new Swift file, and place the function in it else place it in any class as:
Class HelperFunctionsClass() {
func anyFunction () {
//Your implementation of the function here
}
}
To use this, create an instance of the class in the place you would like to use it as:
var instanceOfHelperFunctionClass = HelperFunctionClass()
Now simply use this instance variable to use the function as:
insttanceOfHelperFunctionClass.anyFunction()
Related
In my project i have many swift classes that extend generic classes. And Now i'm in a need to send data from objective-c class to these swift classes. Is there any possible way to do this ?
I have tried using #objc before class as shown below
but it didn't allow me to do this.
I followed this answer stack link. But i checked when i run my app with this code it dint create the variable in the Project-swift class as shown in below image
as the variable is not created here so it gives error while calling the variable in objective-c class.
Kindly help out with better solution.
I got my solution by creating another class which contain a protocol and i indirectly call the generic extended class.
class EntityDataTable :BaseData<EntitySw> {
}
this is the generic extended class
and the another class i made to indirectly access this class in objective-c is
#objc class EntityService : NSObject {
var entityProtocol:EntityDataProtocol?
override init() {
super.init()
entityProtocol = returnDataObject()
}
func returnDataObject() -> EntityDataTable {
return EntityDataTable()
}
}
#objc protocol EntityDataProtocol{
func addFromService(source: CWEntity)
func getAll() -> [EntitySw]
}
Then i imported the Project-swift.h file in objective c class and made the object of swift class
I can't use private property in extension. My extension is in another file.
How can I use private property in extension?
Update
Starting with Swift 4, extensions can access the private properties of a type declared in the same file. See Access Levels.
If a property is declared private, its access is restricted to the enclosing declaration, and to extensions of that declaration that are in the same file.
If the property is declared fileprivate, it can only be used within the file it is declared (and by anything in that file).
If the property is declared internal (the default), it can only be used within the module it is declared (and by anything in that file).
If the property is declared public or open, it can be used by anything within the module as well as outside of the module by files that import the module it is declared in.
While #nhgrif is correct about how painful is that protected is missing in Swift, There is a way around.
Wrap your object with protocol, and declare only about the methods and properties that you wish to expose.
For Example
MyUtiltyClass.swift
protocol IMyUtiltyClass {
func doSomething()
}
class MyUtiltyClass : IMyUtiltyClass {
static let shared : IMyUtiltyClass = MyUtiltyClass()
/*private*/
func doSomethingPrivately() {
}
}
MyUtiltyClass+DoSomething.swift
extension MyUtiltyClass {
func doSomething() {
self.doSomethingPrivately()
print("doing something")
}
}
And then you treat the object as the interface type and not the class/struct type directly.
MyViewController.swift
class MyViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
MyUtiltyClass.shared.doSomething()
/*
//⚠️ compiler error
MyUtiltyClass.shared.doSomethingPrivately()
*/
}
}
Happy Coding 👨💻
It's not a good practice to write a private variable in extensions (even if we can). It will introduce unexpected bugs.
If you want to access the variable, you can use private(set) for that variable to make it read only for outside world.
Ex.
private(set) var myPrivateVariable:Int
I learn the Swift Language and i need to create a manager like a Parse sdk.
For exemple when you initialize your Parse in app you write
Parse.setApplication("...", applicationId:"...")
And later you can write code like this
Parse.doSomething()
The method doSomething() use initial context.
Can you show me in my class should look like? I try some singleton exemple, but a have MyClass.sharedAttribute.doSomething() in case
What you have shown is no indication of singletons whatsoever, it sounds and looks more like a static class with static members and properties:
class MyStatic {
static var appIdA : String?
class func setApplicationId(a : String) {
appIdA = a
}
class func doSomething() {
print(appIdA)
}
}
MyStatic.setApplicationId("blabla")
MyStatic.doSomething() // prints Optional("blabla")
Of course there is the possibility that internally the class is a singleton, but Parse does not seem to be one, just looking at the functions it exposes.
The code comments even state
/*!
The `Parse` class contains static functions that handle global configuration
for the Parse framework.
*/
How possibility to run object globally that I call from Objective C library in swift? I don't want to call it more than once each time I switch the view controller. Is it I need to call it from appDelegate() ?
var instanceOfUMCrypto: UMCrypto = UMCrypto()
If you need a global singleton object, you can declare it globally in any .swift file (not in any class or function), like that:
import UIKit
let instanceOfUMCrypto = UMCrypto()
class SomeClass {
someFunction() {
}
}
After that, you can call instanceOfUMCrypto from anywhere and it won't be initialized more than once.
Exploring Swift headers I'm seeing this pattern used by Apple, in particular the init declaration of the following struct HAS NO IMPLEMENTATION.
Obviously the init() implementation is hidden somehow, since it's Apple stuff, but I was trying to understand how.
This is only an example, but it seems a common behavior in the headers
struct AutoreleasingUnsafePointer<T> : Equatable, LogicValue {
let value: Builtin.RawPointer
init(_ value: Builtin.RawPointer) // <---- how is it possible? where is the implementation?
func getLogicValue() -> Bool
/// Access the underlying raw memory, getting and
/// setting values.
var memory: T
}
I know that it is possible to declare a protocol plus a class extension, doing this it's possible to "hide" the implementation from the class declaration and moving it elsewhere
class TestClass :TestClassProtocol
{
// nothing here
}
protocol TestClassProtocol
{
func someMethod() // here is the method declaration
}
extension TestClass
{
func someMethod() // here is the method implementation
{
println("extended method")
}
}
But it's different from what I have seen in the Apple Headers, since the method "declaration" is inside the "class", not inside the "protocol". if I try to put the method declaration inside the class TestClass, however, I have two errors (function without body on the class, and invalid redeclaration on the extension)
In Objective C this was "implicit", since the method declaration was in the .h and the implementation in the .m
How to do the same in Swift?
I think the explanation is very simple. What you see in Xcode is not actually a valid Swift
code.
It's a result from an automatic conversion of an Obj-C header into Swift-like code but it's not compilable Swift.