Swift is a general-purpose programming language developed by Apple Inc. It is a powerful language developed for iOS, iPadOS, macOS, watchOS, tvOS, Linux, and z/OS. Swift is one of the popular languages and has a huge scope if you want to develop apps for Apple products. So, today we will be checking out the 11 most asked Swift programming questions. 11 Most Asked Swift Programming Questions 1. How to call Objective-C code from Swift? Answer: Using Objective-C Classes in Swift If you have an existing class that you'd like to use, perform and then skip to . (For some cases, add an explicit Step 2 Step 5 #import <Foundation/Foundation.h to an older Objective-C File.) Add Objective-C Implementation -- .m Step 1: Add a file to your class, and name it . .m CustomObject.m Add Bridging Header Step 2: When adding your file, you'll likely be hit with a prompt that looks like this: .m Click ! Yes If you did not see the prompt or accidentally deleted your bridging header, add a new file to your project and name it < .h #YourProjectName#>-Bridging-Header.h. In some situations, particularly when working with Objective-C frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your file named as mentioned above, then make sure you link its path in your target's project settings like so: .h Note: It's best practice to link your project using the macro so that if you move your project, or work on it with others using a remote repository, it will still work. can be thought of as the directory that contains your .xcodeproj file. It might look like this: $(SRCROOT) $(SRCROOT) $(SRCROOT)/Folder/Folder/ -Bridging-Header.h < > #YourProjectName# dd Objective-C Header -- .h Step 3: A Add another file and name it . .h CustomObject.h Build your Objective-C Class Step 4: In CustomObject.h # <Foundation/Foundation.h> @interface CustomObject : NSObject @property (strong, nonatomic) id someProperty; - ( ) someMethod; @end import void In CustomObject.m # @implementation CustomObject - ( ) someMethod { NSLog(@ );} @end import "CustomObject.h" void "SomeMethod Ran" Add Class to Bridging-Header Step 5: In h: YourProject-Bridging-Header. # import "CustomObject.h" Use your Object Step 6: In : SomeSwiftFile.swift instanceOfCustomObject = CustomObject() instanceOfCustomObject.someProperty = print(instanceOfCustomObject.someProperty) instanceOfCustomObject.someMethod() var "Hello World" There is no need to import explicitly; that's what the bridging header is for. Using Swift Classes in Objective-C Create New Swift Class Step 1: Add a file to your project, and name it . .swift MySwiftObject.swift In : MySwiftObject.swift Foundation @objc(MySwiftObject) { @objc someProperty: AnyObject = NSString init() {} @objc func someFunction(someArg: Any) -> NSString { }} import : class MySwiftObject NSObject var "Some Initializer Val" as return "You sent me \(someArg)" Import Swift Files to ObjC Class Step 2: In : SomeRandomClass.m # import "<#YourProjectName#>-Swift.h" The file: should already be created automatically in your project, even if you can not see it. <#YourProjectName#>-Swift.h Use your class Step 3: MySwiftObject * myOb = [MySwiftObject ]; NSLog(@ , myOb.someProperty); myOb.someProperty = @ ; NSLog(@ , myOb.someProperty); NSString * retString = [myOb someFunctionWithSomeArg:@ ]; NSLog(@ , retString); new "MyOb.someProperty: %@" "Hello World" "MyOb.someProperty: %@" "Arg" "RetString: %@" Notes: If Code Completion isn't behaving as you expect, try running a quick build with to help Xcode find some of the Objective-C code from a Swift context and vice versa. ⌘⇧R If you add a file to an older project and get the error , try completely . .swift dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib restarting Xcode While it was originally possible to use pure Swift classes (Not descendents of ) which are visible to Objective-C by using the prefix, this is no longer possible. Now, to be visible in Objective-C, the Swift object must either be a class conforming to (easiest way to do this is to inherit from ), or to be an marked with a raw value of some integer type like . NSObject @objc NSObjectProtocol NSObject enum @objc Int 2. Is there a stand-in for #pragma mark in Swift? Answer: You can use : // MARK There has also been discussion that liberal use of class extensions might be a better practice anyway. Since extensions can implement protocols, you can e.g. put all of your table view delegate methods in an extension and group your code at a more semantic level than is capable of. #pragma mark Alternative Answer: Up to Xcode 5 the preprocessor directive existed. #pragma mark From Xcode 6 on, you have to use : // MARK These preprocessor features allow to bring some structure to the function drop down box of the source code editor. Some examples : // MARK: -> will be preceded by a horizontal divider // MARK: your text goes here -> puts 'your text goes here' in bold in the drop down list // MARK: - your text goes here -> puts 'your text goes here' in bold in the drop down list, preceded by a horizontal divider Added screenshot 'cause some people still seem to have issues with this : 3. How to get the length of a ? String Answer: As of Swift 4 It’s just: test1.count As of Swift 2: With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is: test1.characters.count As of Swift 1 Use the count characters method: let unusualMenagerie = "Koala &#128040;, Snail &#128012;, Penguin &#128039;, Dromedary &#128042;" println ( ) "unusualMenagerie has \(count(unusualMenagerie)) characters" // prints "unusualMenagerie has 40 characters" right from the Apple Swift Guide (Note: For versions of Swift earlier than 1.2, this would be instead) for your variable, it would be countElements(unusualMenagerie) length = count(test1) // was countElements in earlier versions of Swift Or you can use test1.utf16count Alternative Answer: For use . But, there are a few things you should know. So, read on. Swift 2.0 and 3.0, test1.characters.count Counting characters in Swift Before Swift 2.0, count was a global function. As of Swift 2.0, it can be called as a member function. test1.characters.count It will return the actual number of Unicode characters in a , so it’s the most correct alternative in the sense that, if you’d print the string and count characters by hand, you’d get the same result. String However, because of the way are implemented in Swift, characters don’t always take up the same amount of memory, so be aware that this behaves quite differently than the usual character count methods in other languages. Strings For example, you can also use test1.utf16.count But, as noted below, the returned value is not guaranteed to be the same as that of calling on . count characters From the language reference: Extended grapheme clusters can be composed of one or more Unicode scalars. This means that different characters—and different representations of the same character—can require different amounts of memory to store. Because of this, characters in Swift do not each take up the same amount of memory within a string’s representation. As a result, the number of characters in a string cannot be calculated without iterating through the string to determine its extended grapheme cluster boundaries. If you are working with particularly long string values, be aware that the characters property must iterate over the Unicode scalars in the entire string in order to determine the characters for that string. The count of the characters returned by the characters property is not always the same as the length property of an NSString that contains the same characters. The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string. An example that perfectly illustrates the situation described above is that of checking the length of a string containing a single emoji character. emoji = emoji.characters.count emoji.utf16.count var "👍" //returns 1 //returns 2 4. How to iterate a loop with index and element in Swift? Answer: As of Swift 3.0, if you need the index for each element along with its value, you can use the to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example: method enumerated() (index, element) list.enumerated() { print( )} for in "Item \(index): \(element)" Before Swift 3.0 and after Swift 2.0, the function was called : enumerate() (index, element) list.enumerate() { print( )} for in "Item \(index): \(element)" Prior to Swift 2.0, was a global function. enumerate (index, element) enumerate(list) { println( )} for in "Item \(index): \(element)" Alternative Answer: Swift 5 provides a method called for Array. has the following declaration: enumerated() enumerated() func enumerated() -> EnumeratedSequence< <Element>> Array Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence. In the simplest cases, you may use ) with a for loop. For example: enumerated( list = [ , , , ] (index, element) list.enumerated() { print(index, , element) } let "Car" "Bike" "Plane" "Boat" for in ":" /* prints: 0 : Car 1 : Bike 2 : Plane 3 : Boat */ However that you’re not limited to use with a for loop. In fact, if you plan to use with a for loop for something similar to the following code, you’re doing it wrong: Note: enumerated() enumerated() list = [Int]( . ) arrayOfTuples = [(Int, Int)]() (index, element) list.enumerated() { arrayOfTuples += [(index, element)]} print(arrayOfTuples) let 1. .5 var for in // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] A swiftier way to do this is: list = [Int]( . ) arrayOfTuples = (list.enumerated()) print(arrayOfTuples) let 1. .5 let Array // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2, element: 3), (offset: 3, element: 4), (offset: 4, element: 5)] As an alternative, you may also use with : enumerated() map list = [Int]( . ) arrayOfDictionaries = list.enumerated().map { (a, b) [a : b] } print(arrayOfDictionaries) let 1. .5 let in return // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]] Moreover, although it has some , can be a good replacement to a for loop: limitations forEach list = [Int]( . ) list.reversed().enumerated().forEach { print($ , , $ ) } let 1. .5 0 ":" 1 /* prints: 0 : 5 1 : 4 2 : 3 3 : 2 4 : 1 */ By using and , you can even iterate manually on your . For example: enumerated() makeIterator() Array UIKitimport PlaygroundSupport { generator = [ , , , ].enumerated().makeIterator() override func viewDidLoad() { .viewDidLoad() button = UIButton(type: .system) button.setTitle( , : .normal) button.frame = CGRect(x: , : , : , : ) button.addTarget(self, : #selector(iterate(_:)), : .touchUpInside) view.addSubview(button) } @objc func iterate(_ sender: UIButton) { tuple = generator.next() print( (describing: tuple)) } } PlaygroundPage.current.liveView = ViewController() import : class ViewController UIViewController var "Car" "Bike" "Plane" "Boat" super let "Tap" for 100 y 100 width 100 height 100 action for let String /* Optional((offset: 0, element: "Car")) Optional((offset: 1, element: "Bike")) Optional((offset: 2, element: "Plane")) Optional((offset: 3, element: "Boat")) nil nil nil */ 5. Is there a replacement/solution for #ifdef where you can define a macro using compiler preprocessors? Answer: In Swift, you can still use the "#if/#else/#endif" preprocessor macros (although more constrained), as per . Here's an example: Apple docs # DEBUG a = # a = #endif if let 2 else let 3 Now, you must set the "DEBUG" symbol elsewhere, though. Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line. You add the DEBUG symbol with the entry. -D DEBUG As usual, you can set a different value when in Debug or when in Release. It works, but it doesn't seem to be recognized in a playground though. doesn't work. Only works. Seems compiler is ignoring a flag with a specific value. Important Note: -DDEBUG=1 -D DEBUG Alternative Answer: As stated in Apple Docs The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift. By using custom Build Configurations: Go to your project / select your target / Build Settings / search for Custom Flags For your chosen target set your custom flag using -D prefix (without white spaces), for both Debug and Release Do above steps for every target you have Here's how you check for target: # BANANA print( ) #elseif MELONA print( ) # print( ) #endif if "We have a banana" "Melona" else "Kiwi" Tested using Swift 2.2 6. How to split a string into an array in Swift? Answer: The Swift way is to use the global split function, like so: fullName = fullNameArr = split(fullName) {$ == } firstName: = fullNameArr[ ] lastName: ? = fullNameArr.count > ? fullNameArr[ ] : nilW var "First Last" var 0 " " var String 0 var String 1 1 With Swift 2 In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols). .characters fullName = fullNameArr = fullName.characters.split{$ == }.map( .init) fullNameArr[ ] fullNameArr[ ] let "First Last" let 0 " " String // or simply: // let fullNameArr = fullName.characters.split{" "}.map(String.init) 0 // First 1 // Last Alternative Answer: Just call method. componentsSeparatedByString Foundation fullName: = fullNameArr = fullName.componentsSeparatedByString( ) firstName: = fullNameArr[ ] lastName: = fullNameArr[ ] import var String "First Last" let " " var String 0 var String 1 Update for Swift 3+ Foundation fullName = fullNameArr = fullName.components(separatedBy: ) name = fullNameArr[ ] surname = fullNameArr[ ] import let "First Last" let " " let 0 let 1 7. How to use @selector() in Swift? Answer: Swift doesn't use selectors — several design patterns that in Objective-C make use of selectors work differently in Swift. (For example, use optional chaining on protocol types or tests instead of , and use closures wherever you can instead of performSelector: for better type/memory safety.) itself is/as respondsToSelector: But there are still a number of important ObjC-based APIs that use selectors, including timers and the target/action pattern. Swift provides the type for working with these. (Swift automatically uses this in place of ObjC's type.) Selector SEL In Swift 2.2 (Xcode 7.3) and later (including Swift 3 / Xcode 8 and Swift 4 / Xcode 9): You can construct a from a Swift function type using the expression. Selector #selector timer = Timer(timeInterval: , : object, : #selector(MyClass.test), : nil, : ) button.addTarget(object, : #selector(MyClass.buttonTapped), : .touchUpInside) view.perform(#selector(UIView.insertSubview(_:aboveSubview:)), : button, : otherButton) let 1 target selector userInfo repeats false action for with with The great thing about this approach? A function reference is checked by the Swift compiler, so you can use the expression only with class/method pairs that actually exist and are eligible for use as selectors (see "Selector availability" below). You're also free to make your function reference only as specific as you need, as per . #selector the Swift 2.2+ rules for function-type naming (This is actually an improvement over ObjC's directive, because the compiler's - check verifies only that the named selector exists. The Swift function reference you pass to checks existence, membership in a class, and type signature.) There are a couple of extra caveats for the function references you pass to the expression: @selector() Wundeclared-selector #selector #selector Multiple functions with the same base name can be differentiated by their parameter labels using the aforementioned (e.g. vs . But if a function has no parameters, the only way to disambiguate it is to use an cast with the function's type signature (e.g. . syntax for function references insertSubview(_:at:) insertSubview(_:aboveSubview:)) as foo as () -> () vs foo(_:)) There's a special syntax for property getter/setter pairs in Swift 3.0+. For example, given a , you can use or . var foo: Int #selector(getter: MyClass.foo) #selector(setter: MyClass.foo) General notes: Sometimes you don't have a function reference to make a selector with (for example, with methods dynamically registered in the ObjC runtime). In that case, you can construct a from a string: e.g. — though you lose the compiler's validity checking. When you do that, you need to follow ObjC naming rules, including colons (:) for each parameter. Cases where #selector doesn't work, and naming: Selector Selector("dynamicMethod:" The method referenced by the selector must be exposed to the ObjC runtime. In Swift 4, every method exposed to ObjC must have its declaration prefaced with the attribute. (In previous versions you got that attribute for free in some cases, but now you have to explicitly declare it.) Selector availability: @objc Remember that symbols aren't exposed to the runtime, too — your method needs to have at least visibility. private internal These are related to but not quite the same as selectors. There's a special syntax for these in Swift 3, too: e.g. . See for details. And even more , so make sure you're using the right KeyPath-based API instead of selectors if appropriate. Key paths: chris.valueForKeyPath #keyPath(Person.friends.firstName)) SE-0062 KeyPath stuff in Swift 4 You can read more about selectors under in . Interacting with Objective-C APIs Using Swift with Cocoa and Objective-C Before Swift 2.2, conformed to , so you might find old code where bare strings are passed to APIs that take selectors. You'll want to run "Convert to Current Swift Syntax" in Xcode to get those using . Note: Selector StringLiteralConvertible #selector Alternative Answer: Here's a quick example of how to use the class on Swift: Selector override func viewDidLoad() { .viewDidLoad() rightButton = UIBarButtonItem(title: , : UIBarButtonItemStyle.Plain, : self, : Selector( )) self.navigationItem.rightBarButtonItem = rightButton } func method() { } super var "Title" style target action "method" // Something cool here Note that if the method passed as a string doesn't work, it will fail at runtime, not compile time, and crash your app. Be careful. 8. Do Swift-based applications work on OS X 10.9/iOS 7 and lower? Answer: Swift applications compile into standard binaries and can be run on OS X 10.9 and iOS 7. A simple Swift application used for testing: func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) controller = UIViewController() view = UIView(frame: CGRectMake( , , , )) view.backgroundColor = UIColor.redColor() controller.view = view label = UILabel(frame: CGRectMake( , , , )) label.center = CGPointMake( , ) label.textAlignment = NSTextAlignment.Center label.text = controller.view.addSubview(label) self.window!.rootViewController = controller self.window!.makeKeyAndVisible() } var var 0 0 320 568 var 0 0 200 21 160 284 "I'am a test label" return true 9. What is the proper usage of dispatch_once singleton model in Swift? Answer: Use the approach if you are using Swift 1.2 or above and the approach if you need to support earlier versions. class constant nested struct With Swift, there are three approaches to implement the Singleton pattern that support lazy initialization and thread-safety. Class constant { sharedInstance = Singleton() } class Singleton static let This approach supports lazy initialization because Swift lazily initializes class constants (and variables), and is thread safe by the definition of . This is now to instantiate a singleton. let officially recommended way Class constants were introduced in Swift 1.2. If you need to support an earlier version of Swift, use the nested struct approach below or a global constant. Nested struct { { struct Static { instance: Singleton = Singleton() } Static.instance } } class Singleton : class var sharedInstance Singleton static let return Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier and still works as a workaround for the lack of static constants and variables in functions. dispatch_once The traditional Objective-C approach ported to Swift. { { struct Static { onceToken: dispatch_once_t = instance: Singleton? = nil } dispatch_once(&Static.onceToken) { Static.instance = Singleton() } Static.instance! } } class Singleton : class var sharedInstance Singleton static var 0 static var return See this project for unit tests. GitHub 10. How to make a weak protocol reference in 'pure' Swift (without @objc)? Answer: You need to declare the type of the protocol as . AnyObject protocol ProtocolNameDelegate: AnyObject { } { weak delegate: ProtocolNameDelegate? } // Protocol stuff goes here class SomeClass var Using you say that only classes can conform to this protocol, whereas structs or enums can't. AnyObject Supplemental Answer: The purpose of using the keyword is to avoid (retain cycles). Strong reference cycles happen when two class instances have strong references to each other. Their reference counts never go to zero so they never get deallocated. weak strong reference cycles You only need to use if the delegate is a class. Swift structs and enums are value types (their values are copied when a new instance is made), not reference types, so they don't make strong cycles. weak reference references are always optional (otherwise you would use ) and always use (not ) so that the optional can be set to when it is deallocated. weak unowned var let nil A parent class should naturally have a strong reference to its child classes and thus not use the keyword. When a child wants a reference to its parent, though, it should make it a weak reference by using the keyword. weak weak should be used when you want a reference to a class that you don't own, not just for a child referencing its parent. When two non-hierarchical classes need to reference each other, choose one to be weak. The one you choose depends on the situation. See the answers to for more on this. weak this question because most delegates are referencing classes that they do not own. This is definitely true when a child is using a delegate to communicate with a parent. Using a weak reference for the delegate is what the recommends. (But see , too.) As a general rule, delegates should be marked as weak documentation this Protocols can be used for both (classes) and (structs, enums). So in the likely case that you need to make a delegate weak, you have to make it an object-only protocol. The way to do that is to add to the protocol's inheritance list. (In the past you did this using the keyword, but .) reference types value types AnyObject class is preferred now AnyObject protocol MyClassDelegate: AnyObject { } { weak delegate: MyClassDelegate? } // ... class SomeClass var 11. How to convert Int to String in Swift? Answer: Converting to : Int String x : Int = myString = (x) let 42 var String And the other way around - converting to : String Int myString : = x: Int? = myString.toInt() (x != nil) { } let String "42" let if // Successfully converted String to Int Or if you're using Swift 2 or 3: x: Int? = Int(myString) let Alternative Answer: Check the Below Answer: x : Int = stringValue = print(stringValue) let 45 var "\(x)" In Conclusion These are the 11 most commonly asked Swift programming questions. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you. Hope this article helped you. This post was first published on DevPost by Truemark .