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 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

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 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 385

In Swift 2, many types that you would typically do this for have been updated to conform to the OptionSetType protocol. This allows for array like syntax for usage, and In your case, you can use the following.

And on a related note, if you want to check if an option set contains a specific option, you no longer need to use bitwise AND and a nil check. You can simply ask the option set if it contains a specific value in the same way that you would check if an array contained a value.

In Swift 3, the samples must be written as follows:

and

let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)

if settings.types.contains(.alert) {
    // stuff
}
flags |= .Alert?
flags = [flags, .Alert]

i.e Is this treated like a Set where values are unique or as an Array which could possibly lead to an incorrect final value?

@user3246173 It depends on how the flags variable is declared. If flag's type is explicitly declared as UIUserNotificationType, i.e. var flags: UIUserNotificationType = [.Alert, .Badge], then it will be treated like a set, and you could add an element either by using set instance methods like insert(), union(), unionInPlace(), or with the approach that you mentioned without worrying about duplicates.

If you don't explicitly declare flags as having the type UIUserNotificationType and use something like var flags = [UIUserNotificationType.Alert, UIUserNotificationType.Badge] in your declaration, then flag's type will be inferred to be [UIUserNotificationType], and adding elements to it via append() or other methods will result in duplicates. In the case of the latter, you can simply initialize an instance of UIUserNotificationType with the array as input and all will be well, but I recommend the set based approach for clarity.

ios - Swift 2.0 - Binary Operator "|" cannot be applied to two UIUserN...

ios swift swift2
Rectangle 27 385

In Swift 2, many types that you would typically do this for have been updated to conform to the OptionSetType protocol. This allows for array like syntax for usage, and In your case, you can use the following.

And on a related note, if you want to check if an option set contains a specific option, you no longer need to use bitwise AND and a nil check. You can simply ask the option set if it contains a specific value in the same way that you would check if an array contained a value.

In Swift 3, the samples must be written as follows:

and

let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil)

if settings.types.contains(.alert) {
    // stuff
}
flags |= .Alert?
flags = [flags, .Alert]

i.e Is this treated like a Set where values are unique or as an Array which could possibly lead to an incorrect final value?

@user3246173 It depends on how the flags variable is declared. If flag's type is explicitly declared as UIUserNotificationType, i.e. var flags: UIUserNotificationType = [.Alert, .Badge], then it will be treated like a set, and you could add an element either by using set instance methods like insert(), union(), unionInPlace(), or with the approach that you mentioned without worrying about duplicates.

If you don't explicitly declare flags as having the type UIUserNotificationType and use something like var flags = [UIUserNotificationType.Alert, UIUserNotificationType.Badge] in your declaration, then flag's type will be inferred to be [UIUserNotificationType], and adding elements to it via append() or other methods will result in duplicates. In the case of the latter, you can simply initialize an instance of UIUserNotificationType with the array as input and all will be well, but I recommend the set based approach for clarity.

ios - Swift 2.0 - Binary Operator "|" cannot be applied to two UIUserN...

ios swift swift2
Rectangle 27 5

Dictionary is struct Dictionary<Key : Hashable, Value>... Which means that Value could be anything you want, and Key could be any type you want, but Key must conform to Hashable protocol.

Dictionary<Any, Int>()
Dictionary<AnyObject, Int>()
Any
AnyObject

You can't create Dictionary<Hashable, Int>(), because Hashable is not a type it is just protocol which is describing needed type.

So Hashable inherited from Equatable but it does not conform to Equatable??? I don't understand...

But you are wrong in terminology. Original error is

type 'Hashable' does not conform to inherited protocol 'Equatable.Protocol' That means that Xcode assuming 'Hashable' as some type, but there is no such type. And Xcode treat it as some kind empty type, which obviously does not conform any protocol at all (in this case it does not conform to inherited protocol Equatable)

Something similar happens with KeyType.

A type alias declaration introduces a named alias of an existing type into your program.

existing type
protocol<Hashable, Equatable>
type 'KeyType' does not conform to protocol 'Equatable'
Dictionary<NSObject, Int>
NSObject
Hashable

Swift is strong typing language and you can't do some things like creating Dictionary that can hold anything in Key. Actually dictionary already supports any can hold anything in Key, which conforms Hashable. But since you should specify particular class you can't do this for native Swift classes, because there is no such master class in Swift like in Objective-C, which conforms air could conform (with a help of extensions) to Hashable

Of course you can use some wrapper like chrisco suggested. But I really can't imagine why you need it. It is great that you have strong typing in Swift so you don't need to worry about types casting as you did in Objective-C

swift - How to create Dictionary that can hold anything in Key? or all...

swift
Rectangle 27 5

Dictionary is struct Dictionary<Key : Hashable, Value>... Which means that Value could be anything you want, and Key could be any type you want, but Key must conform to Hashable protocol.

Dictionary<Any, Int>()
Dictionary<AnyObject, Int>()
Any
AnyObject

You can't create Dictionary<Hashable, Int>(), because Hashable is not a type it is just protocol which is describing needed type.

So Hashable inherited from Equatable but it does not conform to Equatable??? I don't understand...

But you are wrong in terminology. Original error is

type 'Hashable' does not conform to inherited protocol 'Equatable.Protocol' That means that Xcode assuming 'Hashable' as some type, but there is no such type. And Xcode treat it as some kind empty type, which obviously does not conform any protocol at all (in this case it does not conform to inherited protocol Equatable)

Something similar happens with KeyType.

A type alias declaration introduces a named alias of an existing type into your program.

existing type
protocol<Hashable, Equatable>
type 'KeyType' does not conform to protocol 'Equatable'
Dictionary<NSObject, Int>
NSObject
Hashable

Swift is strong typing language and you can't do some things like creating Dictionary that can hold anything in Key. Actually dictionary already supports any can hold anything in Key, which conforms Hashable. But since you should specify particular class you can't do this for native Swift classes, because there is no such master class in Swift like in Objective-C, which conforms air could conform (with a help of extensions) to Hashable

Of course you can use some wrapper like chrisco suggested. But I really can't imagine why you need it. It is great that you have strong typing in Swift so you don't need to worry about types casting as you did in Objective-C

swift - How to create Dictionary that can hold anything in Key? or all...

swift
Rectangle 27 5

Unfortunately, it's currently not possible for metatype types to conform to protocols (see this related question on the matter) so CellThing.Type does not, and cannot, currently conform to Hashable. This therefore means that it cannot be used directly as the Key of a Dictionary.

However, you can create a wrapper for a metatype, using ObjectIdentifier in order to provide the Hashable implementation. For example:

/// Hashable wrapper for a metatype value.
struct Metatype<T> : Hashable {

    static func ==(lhs: Metatype, rhs: Metatype) -> Bool {
        return lhs.base == rhs.base
    }

    let base: T.Type

    init(_ base: T.Type) {
        self.base = base
    }

    var hashValue: Int {
        return ObjectIdentifier(base).hashValue
    }
}


class CellThing {

    // convenience static computed property to get the wrapped metatype value.
    static var metatype: Metatype<CellThing> {
        return Metatype(self)
    }
}

class A : CellThing {}
class B : CellThing {}

var recycle: [Metatype<CellThing>: [CellThing]] = [:]

recycle[A.metatype] = [A(), A(), A()]
recycle[B.metatype] = [B(), B()]

print(recycle[A.metatype]!) // [A, A, A]
print(recycle[B.metatype]!) // [B, B]

This should also work fine for generics, you would simply subscript your dictionary with T.metatype instead.

So to recap, looking at the question title (1) the metatype there would in fact be: CellThing.Type (2) however, actually in Swift you cannot make a metatype hashable: so that's that. Who knew?

@JoeBlow CellThing.Type is the metatype type, which is the type of a type (and CellThing.self is a metatype value, an instance of that). You cannot currently directly conform a metatype type to a protocol. See this related question on the matter.

Is ObjectIdentifier a sort of injection of NSObject-like behavior here? i.e., is its job to make up for the fact that we didn't inherit from NSObject?

@matt Metatype values are just pointers to the underlying metatype information for a given type ObjectIdentifier simply uses those pointer values (you can see in the source that it just does a cast to Builtin.RawPointer) to give you a hashValue implementation (and equality through a simple identity comparison).

Right, and I'm saying: If this were Objective-C we wouldn't have this problem because Class inherits from NSObject, so ObjectIdentifier is sort of giving us a way to make a Swift metatype act just enough like that...?

Make a Swift dictionary where the key is "Type"? - Stack Overflow

swift dictionary types
Rectangle 27 20

You have probably extended NSDate to conform to comparable protocol in Swift 2. Just remove it because Date now conforms to Comparable protocol in Swift3.

The exact same scenario here: two Dates compared; < complains about being ambiguous, while > works. Indeed, NSDate was previously extended and made to adhere to Comparable (by whoever wrote the Swift2.x version of the app) and the < operator was overwritten. JUST the < operator :-) Leo Dabus, how on earth did you know ??? :-)

ios - Swift 3 - Ambiguous use of < operator when comparing two dates -...

ios swift nsdate swift3
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 1

The action methods invoked must conform to one of the following signatures:

Yet, all your action methods have signatures with two arguments. I am unsure how you were able to get one gesture recognizer to work.

i get just this error in the appDelegate.swift file:

What about the top of the output in Xcode's debug area, i.e. where print() statements are output?

ios - Error while Assigning Multiple Gesture Recognizers to AnyObject ...

ios swift uigesturerecognizer
Rectangle 27 2

You can use index(of to check if the currNrexists in your array. (The class must conform to the Equatable protocol)

var arrayNr = ["1", "32", "100"]
let currNr = "32"
// Check to remove the existing element
if let index = arrayNr.index(of: currNr) {
    arrayNr.remove(at: index)
}
arrayNr.append(currNr)

thanks for advice, but there is no argument with index(of: ) in here. What should it be?

index(of: )
Equatable

Oh i see, i declare the array with [Any], i change it into [String] . Its work thanks

Swift 3 : Remove value in Array with Unknown index - Stack Overflow

arrays swift
Rectangle 27 6

From the Swift Docs: "Any: The protocol to which all types implicitly conform."

typealias Any = protocol<>

So when you declare String?, you could think of that as Optional<String>, where Optional<T> can be implemented as:

enum Optional<T> {
  case Some(T), None
}

And enums are Types, so they conform to the Any protocol. As stated in the comments, nil is not a type (and thus does not conform to Any, it is the absence of a value (and in this case no value has no type).

Optionals are baked into the language, and are not regular enums, but it still stands that they conform to Any while a typeless nil does not.

Exactly what I was just commenting. :) +1

@DanBeaulieu I'm sorry to steal the SO karma, I'm on a roll >:) credit goes to you

@AlexPopov: Thanks for the great answer.

swift - Why non optional Any can hold nil? - Stack Overflow

swift optional
Rectangle 27 1

The < and > are not for conforms to protocol. It is for Types with generics like Array:

Array<T>
var a: Array<String>

You want something else, a variable should be a Type String and conform to the protocol

You can extend String with the protocol and add the needed functions yourself.

Optional
extension NSString: Optional {} // you can use String if you like

To create the protocol write in Swift:

protocol Optional {}

You can Objective-C create the protocol, too.

You should not use Optional, because there is already one, but because Swift has namespacing, it works. You could of course write something like that:

extension NSString: JsonOptProtocol {}

protocol JsonOptProtocol {} // or create that in Objective-C like you did
extension NSString: Optional{}
Reference to generic type Optional requires arguments in <...>

Haha, oh that is funny, you should not use Optional, because there is already one in the docs. You have to create the protocol of course, added to answer.

It works with Optional, because it knows you are using your self created protocol named Optional. But you could also use another name for your protocol of course.

ios - Swift instance variable with protocol - Stack Overflow

ios objective-c swift jsonmodel
Rectangle 27 2

Array is defined as Array<T>, which means that an Array can hold any type T, and T does not necessarily conform to the Hashable protocol. Therefore, you cannot apply methods that require this constraint. Unfortunately, you can also not check against or downcast to this protocol, because Hashable was not declared with the @objc attribute.

It is possible to remove duplicates by using a Dictionary, but you cannot use T for keys, for the same reason mentioned above. However, if T is uniquely representable as a String, this should work:

extension Array {
    func unique()->Array<T> {
        var buffer = Dictionary<String,T>()
        for it in self {
            buffer["\(it)"] = it
        }
        return Array(buffer.values)
    } 
}

swift type constraints on generic extensions - Stack Overflow

generics swift swift-extensions
Rectangle 27 10

Swift structs are not classes, therefore they don't conform to AnyObject protocol. You have to rethink your approach. Here are some suggestions:

  • Convert your struct to final class to enforce immutability final class MyStruct { let start : NSDate = NSDate() let stop : NSDate = NSDate() } encoder.encodeObject(mystructs)
  • Map them as an array dictionaries of type [String: NSDate] let structDicts = mystructs.map { ["start": $0.start, "stop": $0.stop] } encoder.encodeObject(structDicts)
let structDicts = mystructs.map { ["start": $0.start, "stop": $0.stop] }

ios - Save struct in class to NSUserDefaults using Swift - Stack Overf...

ios uiimageview swift nsuserdefaults nscoding