All topics

Swift interview questions

12 questions with answers. 90 open jobs in India ask for Swift.

  1. Why are emoji characters like πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦ treated so strangely in Swift strings?

    This has to do with how the String type works in Swift, and how the contains(_:) method works.

    The 'πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦ ' is what's known as an emoji sequence, which is rendered as one visible character in a string. The sequence is made up of Character objects, and at the same time it is made up of UnicodeScalar objects.

    If you check the character count of the string, you'll see that it is made up of four characters, while if you check the unicode scalar count, it will show you a different result:

    print("πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦".characters.count)     // 4
    print("πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦".unicodeScalars.count) // 7
    

    Now, if you parse through the characters and print them, you'll see what seems like normal characters, but in fact the three first characters contain both an emoji as well as a zero-width joiner in their UnicodeScalarView:

    for char in "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦".characters {
        print(char)
        let scalars = String(char).unicodeScalars.map({ String($0.value, radix: 16) })
        print(scalars)
    }
    // πŸ‘©β€
    // ["1f469", "200d"]
    // πŸ‘©β€
    // ["1f469", "200d"]
    // πŸ‘§β€
    // ["1f467", "200d"]
    // πŸ‘¦
    // ["1f466"]
    

    As you can see, only the last character does not contain a zero-width joiner, so when using the contains(_:) method, it works as you'd expect. Since you aren't comparing against emoji containing zero-width joiners, the method won't find a match for any but the last character.

    To expand on this, if you create a String which is composed of an emoji character ending with a zero-width joiner, and pass it to the contains(_:) method, it will also evaluate to false. This has to do with contains(_:) being the exact same as range(of:) != nil, which tries to find an exact match to the given argument. Since characters ending with a zero-width joiner form an incomplete sequence, the method tries to find a match for the argument while combining characters ending with a zero-width joiners into a complete sequence. This means that the method won't ever find a match if:

    1. the argument ends with a zero-width joiner, and
    2. the string to parse doesn't contain an incomplete sequence (i.e. ending with a zero-width joiner and not followed by a compatible character).

    To demonstrate:

    let s = "\u{1f469}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}" // πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦
    s.range(of: "\u{1f469}\u{200d}") != nil                            // false
    s.range(of: "\u{1f469}\u{200d}\u{1f469}") != nil                   // false
    

    However, since the comparison only looks ahead, you can find several other complete sequences within the string by working backwards:

    s.range(of: "\u{1f466}") != nil                                    // true
    s.range(of: "\u{1f467}\u{200d}\u{1f466}") != nil                   // true
    s.range(of: "\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}") != nil  // true
    // Same as the above:
    s.contains("\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}")          // true
    

    The easiest solution would be to provide a specific compare option to the range(of:options:range:locale:) method. The option String.CompareOptions.literal performs the comparison on an exact character-by-character equivalence. As a side note, what's meant by character here is not the Swift Character, but the UTF-16 representation of both the instance and comparison string – however, since String doesn't allow malformed UTF-16, this is essentially equivalent to comparing the Unicode scalar representation.

    Here I've overloaded the Foundation method, so if you need the original one, rename this one or something:

    extension String {
        func contains(_ string: String) -> Bool {
            return self.range(of: string, options: String.CompareOptions.literal) != nil
        }
    }
    

    Now the method works as it "should" with each character, even with incomplete sequences:

    s.contains("πŸ‘©")          // true
    s.contains("πŸ‘©\u{200d}")  // true
    s.contains("\u{200d}")    // true
    

    From Stack Overflow: asked by Ky -, answered by xoudini (CC BY-SA 3.0)

  2. Why Choose Struct Over Class?

    According to the very popular WWDC 2015 talk Protocol Oriented Programming in Swift (video, transcript), Swift provides a number of features that make structs better than classes in many circumstances.

    Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple references to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

    With Structs, there is much less need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable. (For the more technically minded, the exception to that is when capturing a struct inside a closure because then it is actually capturing a reference to the instance unless you explicitly mark it to be copied).

    Classes can also become bloated because a class can only inherit from a single superclass. That encourages us to create huge superclasses that encompass many different abilities that are only loosely related. Using protocols, especially with protocol extensions where you can provide implementations to protocols, allows you to eliminate the need for classes to achieve this sort of behavior.

    The talk lays out these scenarios where classes are preferred:

    • Copying or comparing instances doesn't make sense (e.g., Window)
    • Instance lifetime is tied to external effects (e.g., TemporaryFile)
    • Instances are just "sinks"--write-only conduits to external state (e.g., CGContext)

    It implies that structs should be the default and classes should be a fallback.

    On the other hand, The Swift Programming Language documentation is somewhat contradictory:

    Structure instances are always passed by value, and class instances are always passed by reference. This means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that you need for a project, decide whether each data construct should be defined as a class or as a structure.

    As a general guideline, consider creating a structure when one or more of these conditions apply:

    • The structure’s primary purpose is to encapsulate a few relatively simple data values.
    • It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
    • Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
    • The structure does not need to inherit properties or behavior from another existing type.

    Examples of good candidates for structures include:

    • The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
    • A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
    • A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.

    In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.

    Read the rest at the sourceFrom Stack Overflow: asked by bluedevil2k, answered by drewag (CC BY-SA 4.0)

  3. What does an exclamation mark mean in the Swift language?

    What does it mean to "unwrap the instance"? Why is it necessary?

    As far as I can work out (this is very new to me, too)...

    The term "wrapped" implies we should think of an Optional variable as a present, wrapped in shiny paper, which might (sadly!) be empty.

    When "wrapped", the value of an Optional variable is an enum with two possible values (a little like a Boolean). This enum describes whether the variable holds a value (Some(T)), or not (None).

    If there is a value, this can be obtained by "unwrapping" the variable (obtaining the T from Some(T)).

    How is john!.apartment = number73 different from john.apartment = number73? (Paraphrased)

    If you write the name of an Optional variable (eg text john, without the !), this refers to the "wrapped" enum (Some/None), not the value itself (T). So john isn't an instance of Person, and it doesn't have an apartment member:

    john.apartment
    // 'Person?' does not have a member named 'apartment'
    

    The actual Person value can be unwrapped in various ways:

    • "forced unwrapping": john! (gives the Person value if it exists, runtime error if it is nil)
    • "optional binding": if let p = john { println(p) } (executes the println if the value exists)
    • "optional chaining": john?.learnAboutSwift() (executes this made-up method if the value exists)

    I guess you choose one of these ways to unwrap, depending upon what should happen in the nil case, and how likely that is. This language design forces the nil case to be handled explicitly, which I suppose improves safety over Obj-C (where it is easy to forget to handle the nil case).

    Update:

    The exclamation mark is also used in the syntax for declaring "Implicitly Unwrapped Optionals".

    In the examples so far, the john variable has been declared as var john:Person?, and it is an Optional. If you want the actual value of that variable, you must unwrap it, using one of the three methods above.

    If it were declared as var john:Person! instead, the variable would be an Implicitly Unwrapped Optional (see the section with this heading in Apple's book). There is no need to unwrap this kind of variable when accessing the value, and john can be used without additional syntax. But Apple's book says:

    Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.

    Update 2:

    The article "Interesting Swift Features" by Mike Ash gives some motivation for optional types. I think it is great, clear writing.

    Update 3:

    Another useful article about the implicitly unwrapped optional use for the exclamation mark: "Swift and the Last Mile" by Chris Adamson. The article explains that this is a pragmatic measure by Apple used to declare the types used by their Objective-C frameworks which might contain nil. Declaring a type as optional (using ?) or implicitly unwrapped (using !) is "a tradeoff between safety and convenience". In the examples given in the article, Apple have chosen to declare the types as implicitly unwrapped, making the calling code more convenient, but less safe.

    Perhaps Apple might comb through their frameworks in the future, removing the uncertainty of implicitly unwrapped ("probably never nil") parameters and replacing them with optional ("certainly could be nil in particular [hopefully, documented!] circumstances") or standard non-optional ("is never nil") declarations, based on the exact behaviour of their Objective-C code.

    From Stack Overflow: asked by Troy, answered by Ashley (CC BY-SA 3.0)

  4. Why create "Implicitly Unwrapped Optionals", since that implies you know there's a value?

    Before I can describe the use cases for Implicitly Unwrapped Optionals, you should already understand what Optionals and Implicitly Unwrapped Optionals are in Swift. If you do not, I recommend you first read my article on optionals

    When To Use An Implicitly Unwrapped Optional

    There are two main reasons that one would create an Implicitly Unwrapped Optional. All have to do with defining a variable that will never be accessed when nil because otherwise, the Swift compiler will always force you to explicitly unwrap an Optional.

    1. A Constant That Cannot Be Defined During Initialization

    Every member constant must have a value by the time initialization is complete. Sometimes, a constant cannot be initialized with its correct value during initialization, but it can still be guaranteed to have a value before being accessed.

    Using an Optional variable gets around this issue because an Optional is automatically initialized with nil and the value it will eventually contain will still be immutable. However, it can be a pain to be constantly unwrapping a variable that you know for sure is not nil. Implicitly Unwrapped Optionals achieve the same benefits as an Optional with the added benefit that one does not have to explicitly unwrap it everywhere.

    A great example of this is when a member variable cannot be initialized in a UIView subclass until the view is loaded:

    class MyView: UIView {
        @IBOutlet var button: UIButton!
        var buttonOriginalWidth: CGFloat!
        override func awakeFromNib() {
            self.buttonOriginalWidth = self.button.frame.size.width
        }
    }
    

    Here, you cannot calculate the original width of the button until the view loads, but you know that awakeFromNib will be called before any other method on the view (other than initialization). Instead of forcing the value to be explicitly unwrapped pointlessly all over your class, you can declare it as an Implicitly Unwrapped Optional.

    2. When Your App Cannot Recover From a Variable Being nil

    This should be extremely rare, but if your app can not continue to run if a variable is nil when accessed, it would be a waste of time to bother testing it for nil. Normally if you have a condition that must absolutely be true for your app to continue running, you would use an assert. An Implicitly Unwrapped Optional has an assert for nil built right into it. Even then, it is often good to unwrap the optional and use a more descriptive assert if it is nil.

    When Not To Use An Implicitly Unwrapped Optional

    1. Lazily Calculated Member Variables

    Sometimes you have a member variable that should never be nil, but it cannot be set to the correct value during initialization. One solution is to use an Implicitly Unwrapped Optional, but a better way is to use a lazy variable:

    class FileSystemItem {
    }
    class Directory : FileSystemItem {
        lazy var contents : [FileSystemItem] = {
            var loadedContents = [FileSystemItem]()
            // load contents and append to loadedContents
            return loadedContents
        }()
    }
    

    Now, the member variable contents is not initialized until the first time it is accessed. This gives the class a chance to get into the correct state before calculating the initial value.

    Note: This may seem to contradict #1 from above. However, there is an important distinction to be made. The buttonOriginalWidth above must be set during viewDidLoad to prevent anyone changing the buttons width before the property is accessed.

    2. Everywhere Else

    For the most part, Implicitly Unwrapped Optionals should be avoided because if used mistakenly, your entire app will crash when it is accessed while nil. If you are ever not sure about whether a variable can be nil, always default to using a normal Optional. Unwrapping a variable that is never nil certainly doesn't hurt very much.

    From Stack Overflow: asked by Johnston, answered by drewag (CC BY-SA 3.0)

  5. How does String substring work in Swift?

    All of the following examples use

    var str = "Hello, playground"
    

    Swift 4

    Strings got a pretty big overhaul in Swift 4. When you get some substring from a String now, you get a Substring type back rather than a String. Why is this? Strings are value types in Swift. That means if you use one String to make a new one, then it has to be copied over. This is good for stability (no one else is going to change it without your knowledge) but bad for efficiency.

    A Substring, on the other hand, is a reference back to the original String from which it came. Here is an image from the documentation illustrating that.

    No copying is needed so it is much more efficient to use. However, imagine you got a ten character Substring from a million character String. Because the Substring is referencing the String, the system would have to hold on to the entire String for as long as the Substring is around. Thus, whenever you are done manipulating your Substring, convert it to a String.

    let myString = String(mySubstring)
    

    This will copy just the substring over and the memory holding old String can be reclaimed. Substrings (as a type) are meant to be short lived.

    Another big improvement in Swift 4 is that Strings are Collections (again). That means that whatever you can do to a Collection, you can do to a String (use subscripts, iterate over the characters, filter, etc).

    The following examples show how to get a substring in Swift.

    Getting substrings

    You can get a substring from a string by using subscripts or a number of other methods (for example, prefix, suffix, split). You still need to use String.Index and not an Int index for the range, though. (See my other answer if you need help with that.)

    Beginning of a string

    You can use a subscript (note the Swift 4 one-sided range):

    let index = str.index(str.startIndex, offsetBy: 5)
    let mySubstring = str[..<index] // Hello
    

    or prefix:

    let index = str.index(str.startIndex, offsetBy: 5)
    let mySubstring = str.prefix(upTo: index) // Hello
    

    or even easier:

    let mySubstring = str.prefix(5) // Hello
    

    End of a string

    Using subscripts:

    let index = str.index(str.endIndex, offsetBy: -10)
    let mySubstring = str[index...] // playground
    

    or suffix:

    let index = str.index(str.endIndex, offsetBy: -10)
    let mySubstring = str.suffix(from: index) // playground
    

    or even easier:

    let mySubstring = str.suffix(10) // playground
    

    Note that when using the suffix(from: index) I had to count back from the end by using -10. That is not necessary when just using suffix(x), which just takes the last x characters of a String.

    Range in a string

    Again we simply use subscripts here.

    let start = str.index(str.startIndex, offsetBy: 7)
    let end = str.index(str.endIndex, offsetBy: -6)
    let range = start..<end
    let mySubstring = str[range]  // play
    

    Converting Substring to String

    Don't forget, when you are ready to save your substring, you should convert it to a String so that the old string's memory can be cleaned up.

    let myString = String(mySubstring)
    

    Using an Int index extension?

    Read the rest at the sourceFrom Stack Overflow: asked by Suragch, answered by Suragch (CC BY-SA 4.0)

  6. Static vs class functions/variables in Swift classes?

    static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods.

    class properties function in the same way (subclasses can override them).

    From Stack Overflow: asked by Senseful, answered by mipadi (CC BY-SA 4.0)

  7. What is the "some" keyword in Swift(UI)?

    some View is an opaque result type as introduced by SE-0244 and is available in Swift 5.1 with Xcode 11. You can think of this as being a "reverse" generic placeholder.

    Unlike a regular generic placeholder which is satisfied by the caller:

    protocol P {}
    struct S1 : P {}
    struct S2 : P {}
    func foo<T : P>(_ x: T) {}
    foo(S1()) // Caller chooses T == S1.
    foo(S2()) // Caller chooses T == S2.
    

    An opaque result type is an implicit generic placeholder satisfied by the implementation, so you can think of this:

    func bar() -> some P {
      return S1() // Implementation chooses S1 for the opaque result.
    }
    

    as looking like this:

    func bar() -> <Output : P> Output {
      return S1() // Implementation chooses Output == S1.
    }
    

    In fact, the eventual goal with this feature is to allow reverse generics in this more explicit form, which would also let you add constraints, e.g -> <T : Collection> T where T.Element == Int. See this post for more info.

    The main thing to take away from this is that a function returning some P is one that returns a value of a specific single concrete type that conforms to P. Attempting to return different conforming types within the function yields a compiler error:

    // error: Function declares an opaque return type, but the return
    // statements in its body do not have matching underlying types.
    func bar(_ x: Int) -> some P {
      if x > 10 {
        return S1()
      } else {
        return S2()
      }
    }
    

    As the implicit generic placeholder cannot be satisfied by multiple types.

    This is in contrast to a function returning P, which can be used to represent both S1 and S2 because it represents an arbitrary P conforming value:

    func baz(_ x: Int) -> P {
      if x > 10 {
        return S1()
      } else {
        return S2()
      }
    }
    

    Okay, so what benefits do opaque result types -> some P have over protocol return types -> P?

    1. Opaque result types can be used with PATs

    A major current limitation of protocols is that PATs (protocols with associated types) cannot be used as actual types. Although this is a restriction that will likely be lifted in a future version of the language, because opaque result types are effectively just generic placeholders, they can be used with PATs today.

    This means you can do things like:

    func giveMeACollection() -> some Collection {
      return [1, 2, 3]
    }
    let collection = giveMeACollection()
    print(collection.count) // 3
    

    2. Opaque result types have identity

    Because opaque result types enforce a single concrete type is returned, the compiler knows that two calls to the same function must return two values of the same type.

    This means you can do things like:

    //   foo() -> <Output : Equatable> Output {
    func foo() -> some Equatable { 
      return 5 // The opaque result type is inferred to be Int.
    }
    let x = foo()
    let y = foo()
    print(x == y) // Legal both x and y have the return type of foo.
    

    This is legal because the compiler knows that both x and y have the same concrete type. This is an important requirement for ==, where both parameters of type Self.

    protocol Equatable {
      static func == (lhs: Self, rhs: Self) -> Bool
    }
    

    This means that it expects two values that are both the same type as the concrete conforming type. Even if Equatable were usable as a type, you wouldn't be able to compare two arbitrary Equatable conforming values with each other, for example:

    Read the rest at the sourceFrom Stack Overflow: asked by Half, answered by Hamish (CC BY-SA 4.0)

  8. What is the difference between static func and class func in Swift?

    Is it simply that static is for static functions of structs and enums, and class for classes and protocols?

    That's the main difference. Some other differences are that class functions are dynamically dispatched and can be overridden by subclasses.

    Protocols use the class keyword, but it doesn't exclude structs from implementing the protocol, they just use static instead. Class was chosen for protocols so there wouldn't have to be a third keyword to represent static or class.

    From Chris Lattner on this topic:

    We considered unifying the syntax (e.g. using "type" as the keyword), but that doesn't actually simply things. The keywords "class" and "static" are good for familiarity and are quite descriptive (once you understand how + methods work), and open the door for potentially adding truly static methods to classes. The primary weirdness of this model is that protocols have to pick a keyword (and we chose "class"), but on balance it is the right tradeoff.

    And here's a snippet that shows some of the override behavior of class functions:

    class MyClass {
        class func myFunc() {
            println("myClass")
        }
    }
    class MyOtherClass: MyClass {
        override class func myFunc() {
            println("myOtherClass")
        }
    }
    var x: MyClass = MyOtherClass()
    x.dynamicType.myFunc() //myOtherClass
    x = MyClass()
    x.dynamicType.myFunc() //myClass
    

    From Stack Overflow: asked by Jean-Philippe Pellet, answered by Connor (CC BY-SA 4.0)

  9. Passing data between view controllers

    This question seems to be very popular here on Stack Overflow so I thought I would try and give a better answer to help out people starting in the world of iOS like me.

    Passing Data Forward

    Passing data forward to a view controller from another view controller. You would use this method if you wanted to pass an object/value from one view controller to another view controller that you may be pushing on to a navigation stack.

    For this example, we will have ViewControllerA and ViewControllerB

    To pass a BOOL value from ViewControllerA to ViewControllerB we would do the following.

    1. in ViewControllerB.h create a property for the BOOL

       @property (nonatomic, assign) BOOL isSomethingEnabled;
      
    2. in ViewControllerA you need to tell it about ViewControllerB so use an

       #import "ViewControllerB.h"
      

    Then where you want to load the view, for example, didSelectRowAtIndex or some IBAction, you need to set the property in ViewControllerB before you push it onto the navigation stack.

        ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
        viewControllerB.isSomethingEnabled = YES;
        [self pushViewController:viewControllerB animated:YES];
    

    This will set isSomethingEnabled in ViewControllerB to BOOL value YES.

    Passing Data Forward using Segues

    If you are using Storyboards you are most likely using segues and will need this procedure to pass data forward. This is similar to the above but instead of passing the data before you push the view controller, you use a method called

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    

    So to pass a BOOL from ViewControllerA to ViewControllerB we would do the following:

    1. in ViewControllerB.h create a property for the BOOL

       @property (nonatomic, assign) BOOL isSomethingEnabled;
      
    2. in ViewControllerA you need to tell it about ViewControllerB, so use an

       #import "ViewControllerB.h"
      
    3. Create the segue from ViewControllerA to ViewControllerB on the storyboard and give it an identifier. In this example we'll call it "showDetailSegue"

    4. Next, we need to add the method to ViewControllerA that is called when any segue is performed. Because of this we need to detect which segue was called and then do something. In our example, we will check for "showDetailSegue" and if that's performed, we will pass our BOOL value to ViewControllerB

       -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
           if([segue.identifier isEqualToString:@"showDetailSegue"]){
               ViewControllerB *controller = (ViewControllerB *)segue.destinationViewController;
               controller.isSomethingEnabled = YES;
           }
       }
      

    If you have your views embedded in a navigation controller, you need to change the method above slightly to the following

        -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
            if([segue.identifier isEqualToString:@"showDetailSegue"]){
                UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
                ViewControllerB *controller = (ViewControllerB *)navController.topViewController;
                controller.isSomethingEnabled = YES;
            }
        }
    

    This will set isSomethingEnabled in ViewControllerB to BOOL value YES.

    Passing Data Back

    To pass data back from ViewControllerB to ViewControllerA you need to use Protocols and Delegates or Blocks, the latter can be used as a loosely coupled mechanism for callbacks.

    Read the rest at the sourceFrom Stack Overflow: asked by Matt Price, answered by Matt Price (CC BY-SA 4.0)

  10. How do I call Objective-C code from Swift?

    Using Objective-C Classes in Swift

    If you have an existing class that you'd like to use, perform Step 2 and then skip to Step 5. (For some cases, I had to add an explicit #import <Foundation/Foundation.h to an older Objective-C File.)

    Step 1: Add Objective-C Implementation -- .m

    Add a .m file to your class, and name it CustomObject.m.

    Step 2: Add Bridging Header

    When adding your .m file, you'll likely be hit with a prompt that looks like this:

    Click Yes!

    If you did not see the prompt, or accidentally deleted your bridging header, add a new .h file to your project and name it <#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 .h file named as mentioned above, then make sure you link its path in your target's project settings like so:

    Note:

    It's best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repository, it will still work. $(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:

    $(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h
    

    Step 3: Add Objective-C Header -- .h

    Add another .h file and name it CustomObject.h.

    Step 4: Build your Objective-C Class

    In CustomObject.h

    #import <Foundation/Foundation.h>
    @interface CustomObject : NSObject
    @property (strong, nonatomic) id someProperty;
    - (void) someMethod;
    @end
    

    In CustomObject.m

    #import "CustomObject.h"
    @implementation CustomObject 
    - (void) someMethod {
        NSLog(@"SomeMethod Ran");
    }
    @end
    

    Step 5: Add Class to Bridging-Header

    In YourProject-Bridging-Header.h:

    #import "CustomObject.h"
    

    Step 6: Use your Object

    In SomeSwiftFile.swift:

    var instanceOfCustomObject = CustomObject()
    instanceOfCustomObject.someProperty = "Hello World"
    print(instanceOfCustomObject.someProperty)
    instanceOfCustomObject.someMethod()
    

    There is no need to import explicitly; that's what the bridging header is for.

    Using Swift Classes in Objective-C

    Step 1: Create New Swift Class

    Add a .swift file to your project, and name it MySwiftObject.swift.

    In MySwiftObject.swift:

    import Foundation
    @objc(MySwiftObject)
    class MySwiftObject : NSObject {
        @objc
        var someProperty: AnyObject = "Some Initializer Val" as NSString
        init() {}
        @objc
        func someFunction(someArg: Any) -> NSString {
            return "You sent me \(someArg)"
        }
    }
    

    Step 2: Import Swift Files to ObjC Class

    In SomeRandomClass.m:

    #import "<#YourProjectName#>-Swift.h"
    

    The file:<#YourProjectName#>-Swift.h should already be created automatically in your project, even if you can not see it.

    Step 3: Use your class

    MySwiftObject * myOb = [MySwiftObject new];
    NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
    myOb.someProperty = @"Hello World";
    NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
    NSString * retString = [myOb someFunctionWithSomeArg:@"Arg"];
    NSLog(@"RetString: %@", retString);
    

    Notes:

    Read the rest at the sourceFrom Stack Overflow: asked by David Mulder, answered by Logan (CC BY-SA 4.0)

  11. How to change Status Bar text color in iOS?
    1. Set the UIViewControllerBasedStatusBarAppearance to YES in the .plist file.

    2. In the viewDidLoad do a [self setNeedsStatusBarAppearanceUpdate];

    3. Add the following method:

      - (UIStatusBarStyle)preferredStatusBarStyle
      { 
          return UIStatusBarStyleLightContent; 
      }
      

    Note: This does not work for controllers inside UINavigationController, please see Tyson's comment below :)

    Swift 3 - This will work controllers inside UINavigationController. Add this code inside your controller.

    // Preferred status bar style lightContent to use on dark background.
    // Swift 3
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    

    Swift 5 and SwiftUI

    For SwiftUI create a new swift file called HostingController.swift

    import Foundation
    import UIKit
    import SwiftUI
    class HostingController: UIHostingController<ContentView> {
        override var preferredStatusBarStyle: UIStatusBarStyle {
            return .lightContent
        }
    }
    

    Then change the following lines of code in the SceneDelegate.swift

    window.rootViewController = UIHostingController(rootView: ContentView())
    

    to

    window.rootViewController = HostingController(rootView: ContentView())
    

    From Stack Overflow: asked by Oleksandr Veremchuk, answered by Peter B. Kramer (CC BY-SA 4.0)

  12. #pragma mark in Swift?

    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 #pragma mark is capable of.

    From Stack Overflow: asked by Arbitur, answered by Frank Schmitt (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.