Uploaded image for project: 'Swift'
  1. Swift
  2. SR-4375

Using Generic with Protocols causes Segmentation Fault

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Duplicate
    • Component/s: Compiler
    • Labels:
    • Environment:

      MacBook Pro
      Operating System: OS X El Capitan (10.11.6)
      RAM: 16GB
      Xcode: 8.2.1
      Swift Version: 3.0.2

      Description

      I will explain the issue with a sample example, that you can run on a playground project.

      import Foundation
      class IProtocol {
           func meth1(arg: Int){}
      }
      class IObserver: IProtocol {
          private var className: String
          init(name: String) {
              className = name
          }
          override func meth1(arg: Int) {
              print(className, ":", arg)
          }
      }
      class Notifier<T> {
          private var listOfObservers = NSMutableArray()
          func addObserver(observer: T) {
              listOfObservers.add(observer)
          }
          func callObservers<ARG, RET>(function: (T)->(ARG)->RET, arg: ARG) {
              for obj in listOfObservers {
                  let observer = obj as! T
                  _ = function(observer)(arg)
              }
          }
      }
      let a = IObserver(name: "First I Observer")
      let b = IObserver(name: "Second I Observer")
      let n = Notifier<IProtocol>()
      n.addObserver(observer: a)
      n.addObserver(observer: b)
      n.callObservers(function: IProtocol.meth1, arg: Int(1))
      

      OUTPUT:
      First I Observer: 1
      Second I Observer: 1

      Explanation:
      The above example fails and does not build giving Command failed due to signal: Segmentation Fault: 11, when I change IProtocol to protocol from class. I have different protocols and different observer classes confirming those protocols. I am trying to implement a Notifier class that notifies the observers by taking the method from the protocol and arguments to be passed for that method.

      Note:
      I remove the {} from meth1(arg: ) and also remove the override keyword from IObserver class, when I change IProtocol to a protocol

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              arup193 Arup Dandapat
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: