Rectangle 27 241

You have to make your class inherit from NSObject to conform to the NSObjectProtocol. Vanilla Swift classes do not. But many parts of UIKit expect NSObjects.

class CustomDataSource : NSObject, UITableViewDataSource {

}

Type 'CellDatasDataSource' does not conform to protocol 'UITableViewDataSource'

Is expected. You will get the error until your class implements all required methods of the protocol.

Thanks @Alex; you saved my day, since I've been struggling quite some time to get my Swift class conform to the UICollectionViewDataSource protocol. Adding the NSObject inheritance in my Class solved it!

Am I the only one who thinks a compile warning was sufficient?

@Magoo Surely you meant insufficient. 'Does not conform to protocol' does not mean 'inherit from NSObject' to me.

@RoyFalk I mean a compile warning was sufficient over an error... You might not need to implement the entire protocol in all cases and might want to build prior to doing so... it's not a big deal, but feels a bit unnecessary.

objective c - How to make a class conform to a protocol in Swift? - St...

objective-c swift
Rectangle 27 3

To better illustrate the problem with your current code, let's say you have a StructC : A.

Your protocol B says that you can assign StructC to a (as it conforms to A) but StructB says you cannot assign StructC to a StructA type. Therefore StructB doesn't conform to B.

The solution is either to change the type of a from StructA to A as Rahul says, or better yet, you could use generics.

The advantage of using generics is once you create your StructB with a given a that property's type will be inferred by Swift, giving you better type safety. For example, once you assign a StructA to it, its type will then be StructA. If you assign a StructC to it, its type will be StructC.

To do this, we just have to add an associatedtype to protocol B. This will define a 'placeholder' type that we can then implement in a type that conforms to B. We can then define the generic type T in StructB that will provide the 'implementation' of AType making sure it conforms to A. Therefore, we are now free to assign either StructA or StructC to a, without losing type safety.

protocol A {}
protocol B {

    // new associated type to hold the type of "a" which conforms to A
    associatedtype AType:A
    var a: AType { get }
}

struct StructA: A {}
struct StructC:A {}

// define the new generic T which conforms to A
struct StructB<T:A> {

    // define the type of a as the generic T, which conforms to A (and thus conforms with the protocol)
    var a : T
}

extension StructB: B {}

let s = StructB(a: StructA())
s.a // "a" is now of type StructA

let s1 = StructB(a: StructC())
s1.a // "a" is now of type StructC

swift2 - Swift: type does not conform to protocol - Stack Overflow

swift swift2 protocols
Rectangle 27 34

kCVPixelFormatType_32BGRA
var kCVPixelFormatType_32BGRA: Int { get } /* 32 bit BGRA */
var kCVPixelFormatType_32BGRA: OSType { get } /* 32 bit BGRA */

Actually the OSType is a UInt32 which can't implicit convert to a NSNumber:

When you write let ao: AnyObject = Int(1), it isnt really putting an Int into an AnyObject. Instead, its implicitly converting your Int into an NSNumber, which is a class, and then putting that in.

videoDataOutput?.videoSettings = [kCVPixelBufferPixelFormatTypeKey: Int(kCVPixelFormatType_32BGRA)]
videoDataOutput?.videoSettings = [kCVPixelBufferPixelFormatTypeKey: NSNumber(unsignedInt: kCVPixelFormatType_32BGRA)

That solves indeed the problem. But your answer would be even more helpful with an explanation why this is necessary, in particular since OP's code worked in Swift 1.2.

@MartinR Hello, I have updated my answer I hope that it can explain more clearly.

swift2 - Type 'OSType' does not conform to protocol 'AnyObject' in Swi...

swift swift2 xcode7 avcaptureoutput
Rectangle 27 3

It looks that lockForConfiguration returns Void and throws, so return value does not conform to BooleanType.

I think that the following code should work for you:

if let device = captureDevice {
    do {
        try device.lockForConfiguration()
        device.focusPointOfInterest = focusPoint
        device.focusMode = AVCaptureFocusMode.ContinuousAutoFocus
        device.exposurePointOfInterest = focusPoint
        device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure
        device.unlockForConfiguration()
    }
    catch {
        print("Error")
    }
}

Yes you are right. I just realised if the try statement will fail it'll skip to the catch not executing code, otherwise will continue normally.

ios - Swift 2.0 Type '()' does not conform to protocol - Stack Overflo...

ios swift swift2
Rectangle 27 2

Because Swift is statically typed and does not depend on dynamic dispatch. You could do something like below.

import UIKit

protocol A {}
protocol B {
    var a: A { get }
}

struct StructA: A {}
struct StructB {
    var a: A = StructA()
}
extension StructB: B {}

just a note: it is not necessary that var a: A has some default value ...

swift2 - Swift: type does not conform to protocol - Stack Overflow

swift swift2 protocols
Rectangle 27 5

UPDATED for Swift Version 2.0 and above

As per Gregzo's answer, Swift 2.0+ allows methods to be declared as static in the protocol definition. These must be satisfied with static/class methods in objects that implement the protocol.

You cannot satisfy a protocol definition for a instance method with a static method or vice-versa, which makes this an incomplete answer for the question above.

If you want to try this just use the keyword "static" in your protocol definition for methods you will implement as static or class methods in your conforming objects:

protocol InstanceVsStatic {
    func someInstanceFunc()
    static func someStaticFunc()
}

enum MyConformingEnum: InstanceVsStatic {
    case someCase

    static func someStaticFunc() {
           // code
    }
    func someInstanceFunc() {
        // code
    }
}

class MyConformingClass: InstanceVsStatic {
    class func someStaticFunc() {
           // code
    }
    func someInstanceFunc() {
        // code
    }
}

struct MyConformingStruct: InstanceVsStatic {
    static func someStaticFunc() {
           // code
    }
    func someInstanceFunc() {
        // code
    }
}

You can have an instance method call a static/class method:

struct MyConformingStruct: InstanceVsStatic {
    static func doStuffStatically(){
        // code
    }

    static func someStaticFunc() {
           // code
    }

    func someInstanceFunc() {
        MyConformingStruct.doStuffStatically()
    }
}

Other than indirectly as above, there is no way to use static (class) methods to conform to a protocol in pure swift version 1.2 and below. It is a known bug / unimplemented feature: https://openradar.appspot.com/20119848

Wondering if there is possible will be a feature in the future?

ios - Make swift class conform to protocol - at static/class level - S...

ios swift protocols swift-protocols
Rectangle 27 5

UPDATED for Swift Version 2.0 and above

As per Gregzo's answer, Swift 2.0+ allows methods to be declared as static in the protocol definition. These must be satisfied with static/class methods in objects that implement the protocol.

You cannot satisfy a protocol definition for a instance method with a static method or vice-versa, which makes this an incomplete answer for the question above.

If you want to try this just use the keyword "static" in your protocol definition for methods you will implement as static or class methods in your conforming objects:

protocol InstanceVsStatic {
    func someInstanceFunc()
    static func someStaticFunc()
}

enum MyConformingEnum: InstanceVsStatic {
    case someCase

    static func someStaticFunc() {
           // code
    }
    func someInstanceFunc() {
        // code
    }
}

class MyConformingClass: InstanceVsStatic {
    class func someStaticFunc() {
           // code
    }
    func someInstanceFunc() {
        // code
    }
}

struct MyConformingStruct: InstanceVsStatic {
    static func someStaticFunc() {
           // code
    }
    func someInstanceFunc() {
        // code
    }
}

You can have an instance method call a static/class method:

struct MyConformingStruct: InstanceVsStatic {
    static func doStuffStatically(){
        // code
    }

    static func someStaticFunc() {
           // code
    }

    func someInstanceFunc() {
        MyConformingStruct.doStuffStatically()
    }
}

Other than indirectly as above, there is no way to use static (class) methods to conform to a protocol in pure swift version 1.2 and below. It is a known bug / unimplemented feature: https://openradar.appspot.com/20119848

Wondering if there is possible will be a feature in the future?

ios - Make swift class conform to protocol - at static/class level - S...

ios swift protocols swift-protocols
Rectangle 27 6

This worked for me. Try it for yourself and see if it works:

class MyEntity: NSManagedObject {

    @NSManaged var testAttribute: String
}

@objc
protocol MyProtocol {

    var testAttribute: String { get set }
}

extension MyEntity: MyProtocol { }

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let myContext = appDelegate.managedObjectContext!
        let entity: MyEntity = NSEntityDescription.insertNewObjectForEntityForName("MyEntity", inManagedObjectContext: myContext) as MyEntity
        foo(entity)
        println(entity.testAttribute)
    }

    func foo(var object: MyProtocol) {
        object.testAttribute = "bar"
    }
}

The below also worked, but I think the above is a better way to do it:

@objc
protocol MyProtocol {

    var testAttribute: String { get set }
}

class MyEntity: NSManagedObject, MyProtocol {

    @NSManaged var testAttribute: String
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let myContext = appDelegate.managedObjectContext!
        let entity: MyEntity = NSEntityDescription.insertNewObjectForEntityForName("MyEntity", inManagedObjectContext: myContext) as MyEntity
        foo(entity)
        println(entity.testAttribute)
    }

    func foo(var object: MyProtocol) {
        object.testAttribute = "bar"
    }
}

Thanks a lot.When I put the extension and NSManagedObject class code together in a swift file, it still shows the same error.But If I move the extension code to another file.It works well.So weird

@objc wouldn't work for me due to CLLocationCoordinate2D. What did work was simply moving my protocol to the extension class that is auto generated via CoreData - before I had it in the class (which is also auto generated)

There is a problem in these approaches when you try to express in the protocol a relation between two managed objects.

ios - NSManagedObject Can't conform to protocol in Swift - Stack Overf...

ios swift
Rectangle 27 2

If a protocol func is static, the implementer should implement it as a static method, and if it isn't, as an instance method:

protocol MixedProtocol
{
    static func staticFoo()
    func instanceBar()
}

class ExampleClass : MixedProtocol
{
    // implementing static func as class func is fine.
    // class funcs are overridable, not static ones
    class func staticFoo()
    {
        println( "I'm a class func" )
    }

    func instanceBar()
    {
        println( "I'm an instance func" )
    }
}

There's no straight way around it: conforming to a protocol means just that, and 'static' is very much a key feature of a protocol member declaration that implementers must respect.

ios - Make swift class conform to protocol - at static/class level - S...

ios swift protocols swift-protocols
Rectangle 27 2

If a protocol func is static, the implementer should implement it as a static method, and if it isn't, as an instance method:

protocol MixedProtocol
{
    static func staticFoo()
    func instanceBar()
}

class ExampleClass : MixedProtocol
{
    // implementing static func as class func is fine.
    // class funcs are overridable, not static ones
    class func staticFoo()
    {
        println( "I'm a class func" )
    }

    func instanceBar()
    {
        println( "I'm an instance func" )
    }
}

There's no straight way around it: conforming to a protocol means just that, and 'static' is very much a key feature of a protocol member declaration that implementers must respect.

ios - Make swift class conform to protocol - at static/class level - S...

ios swift protocols swift-protocols
Rectangle 27 7

Found the solution, in Swift you shouldn't use NSString, but the String type.

class ConversationParticipant: NSObject, ATLParticipant {

    var firstName: String!
    var lastName: String!
    var fullName: String!
    var participantIdentifier: String!
    var avatarImage: UIImage!

    override init() {
        super.init()
    }
}

Do you know how to do this for other delegate properties and NSDictionaries, such as this: property (strong, nonatomic) id<SomeOtherDelegate> delegate; property (strong, nonatomic) NSDictionary *blogSocialNetworkUserNames;

ios - Make swift class conform to objective c protocol that defines pr...

ios objective-c swift
Rectangle 27 3

Xcode 6 beta 7 changed the protocol slightly for UITableViewDataSource to match the following syntax on the two required implementations:

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell

Of key difference is that UITableView, NSIndexPath and UITableViewCell are no longer 'Implicitly Unwrapped Optionals'

ios - How do I make a class conform to a delegate in swift? - Stack Ov...

ios swift
Rectangle 27 3

Xcode 6 beta 7 changed the protocol slightly for UITableViewDataSource to match the following syntax on the two required implementations:

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell

Of key difference is that UITableView, NSIndexPath and UITableViewCell are no longer 'Implicitly Unwrapped Optionals'

ios - How do I make a class conform to a delegate in swift? - Stack Ov...

ios swift
Rectangle 27 1

type.characters.count
//the Pasteboard is nil if full access is not granted
        let pbWrapped: UIPasteboard? = UIPasteboard.generalPasteboard()
        if let pb = pbWrapped {
            var type = UIPasteboardTypeListImage[0] as! String
            if (type.characters.count > 0) && (image != nil) {
                pb.setData(UIImagePNGRepresentation(image!)!, forPasteboardType: type)
                var readDataWrapped: NSData? = pb.dataForPasteboardType(type)
                if let readData = readDataWrapped {
                    var readImage = UIImage(data: readData, scale: 2)
                    print("\(image) == \(pb.image) == \(readImage)")
                }
            }
        }

swift2 - 'String' does not conform to protocol 'CollectionType' Error ...

error-handling swift2 xcode7
Rectangle 27 1

let enumerator = manager.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: .SkipsHiddenFiles, errorHandler: nil)
let options: NSDirectoryEnumerationOptions = [.SkipsHiddenFiles, .SkipsPackageDescendants]
let enumerator = manager.enumeratorAtURL(url, includingPropertiesForKeys: keys, options: options, errorHandler: nil)

swift2 - changing code from Swift 1 to 2, Error: Type 'NSDirectoryEnum...

swift2
Rectangle 27 1

I implemented this solution and still got an error:

"Type 'ConversationParticipant' does not conform to protocol 'ATLAvatarItem'"

var avatarImageURL: NSURL!
var avatarImage: UIImage!
var avatarInitials: String!

ios - Make swift class conform to objective c protocol that defines pr...

ios objective-c swift
Rectangle 27 0

It looks like your issue may be that you are using the wrong types. Your return value seems to be returning a Double in your override function when the declaration specifies a CGFloat. As well, I believe the function should start out with the same words that the declared method does. You wrote heightForBarViewAtIndex( when I believe it would translate to what it looks like below.

override func barChartView(barChartView: JBBarChartView, heightForBarViewAtIndex index: UInt) -> CGFloat { 
    return 0.0 
}

I have change a bit your code and not working, func barChartView(barChartView : JBBarChartView!, heightForBarViewAtIndex index: Int) -> CGFloat{ return 0.0 }

ios - Swift - Objective C - "Controller" Does not conform to Protocol ...

ios objective-c swift
Rectangle 27 0

var delegate: protocol <timerProtocol>
var delegate: timerProtocol?

swift - Type 'className -> () -> className!' does not conform to proto...

protocols swift
Rectangle 27 0

makeNoise(number: Int) and eat() are both instance methods for your class Pets. As such, in order to call these methods, we must instantiate an object of this class.

let dog = Pet()
dog.makeNoise(4)
dog.eat()

swift - Type 'Pets' does not conform to protocol 'IntegerLiteralConver...

swift
Rectangle 27 0

I noticed the protocol method of UITableViewDataSource changed a little bit and sounded the same conform to protocol error which worked fine in beta6.

These are the required methods to be implemented according to the UITableViewDataSource protocol:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // insert code}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // insert code
}

You might want to re-check the difference or re-implement the delegate method that you thought you just implement.

If anyone has implemented these methods and still gets the error, I got rid of it doing a Clean. It was annoying me for a while but got the error go to away

ios - Conform to protocol in ViewController, in Swift - Stack Overflow

ios protocols swift