Questions tagged [swift-protocols]
Protocols specific to the Swift language
1,142
questions
602
votes
8
answers
139k
views
How can I make a weak protocol reference in 'pure' Swift (without @objc)
weak references don't seem to work in Swift unless a protocol is declared as @objc, which I don't want in a pure Swift app.
This code gives a compile error (weak cannot be applied to non-class type ...
434
votes
19
answers
236k
views
How does one declare optional methods in a Swift protocol?
Is it possible in Swift? If not then is there a workaround to do it?
158
votes
6
answers
107k
views
Protocol can only be used as a generic constraint because it has Self or associatedType requirements
I have a protocol RequestType and it has associatedType Model as below.
public protocol RequestType: class {
associatedtype Model
var path: String { get set }
}
public extension ...
155
votes
3
answers
28k
views
Protocol doesn't conform to itself?
Why doesn't this Swift code compile?
protocol P { }
struct S: P { }
let arr:[P] = [ S() ]
extension Array where Element : P {
func test<T>() -> [T] {
return []
}
}
let ...
146
votes
8
answers
39k
views
Usage of protocols as array types and function parameters in swift
I want to create a class that can store objects conforming to a certain protocol. The objects should be stored in a typed array. According to the Swift documentation protocols can be used as types:
...
134
votes
2
answers
53k
views
What does "Protocol ... can only be used as a generic constraint because it has Self or associated type requirements" mean?
I am trying to create a Dictionary (actually a HashSet) keyed on a custom protocol in Swift, but it is giving me the error in the title:
Protocol 'myProtocol' can only be used as a generic ...
127
votes
3
answers
30k
views
Non-'@objc' method does not satisfy optional requirement of '@objc' protocol
Overview:
I have a protocol P1 which provides a default implementation of one of the Objective-C optional functions.
When I provide a default implementation of the optional function there is a ...
117
votes
8
answers
67k
views
Swift - class method which must be overridden by subclass
Is there a standard way to make a "pure virtual function" in Swift, ie. one that must be overridden by every subclass, and which, if it is not, causes a compile time error?
105
votes
15
answers
69k
views
How to make an enum conform to a protocol in Swift?
Swift documentation says that classes, structs, and enums can all conform to protocols, and I can get to a point where they all conform. But I can't get the enum to behave quite like the class and ...
105
votes
5
answers
44k
views
In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?
In Swift I can explicitly set the type of a variable by declaring it as follows:
var object: TYPE_NAME
If we want to take it a step further and declare a variable that conforms to multiple protocols ...
92
votes
4
answers
30k
views
Why I can't use let in protocol in Swift?
I have a doubt about protocols in Swift about the use of var and the keywords { get set }.
From Apple documentation:
If a protocol requires a property to be gettable and settable, that
property ...
92
votes
4
answers
13k
views
"fatal error: array cannot be bridged from Objective-C"—Why are you even trying, Swift?
I have declared a Swift protocol:
protocol Option {
var name: String { get }
}
I declare multiple implementations of this protocol—some classes, some enums.
I have a view controller with a ...
91
votes
9
answers
35k
views
Protocol func returning Self
I have a protocol P that returns a copy of the object:
protocol P {
func copy() -> Self
}
and a class C that implements P:
class C : P {
func copy() -> Self {
return C()
}
...
85
votes
2
answers
44k
views
Can I have an init func in a protocol?
When I try to implement my protocol this way:
protocol Serialization {
func init(key keyValue: String, jsonValue: String)
}
I get an error saying: Expected identifier in function declaration.
...
63
votes
5
answers
50k
views
Arrays of Generics in Swift
I've been playing around with arrays of generic classes with different types. It's easiest to explain my problem with some sample code:
// Obviously a very pointless protocol...
protocol MyProtocol {
...
49
votes
3
answers
43k
views
what is 'where self' in protocol extension
I saw so many examples with below format
extension Protocolname where Self: UIViewController
What is where Self in protocol extension. I couldn't find the documentation on this.
48
votes
5
answers
16k
views
When to use `protocol` and `protocol: class` in Swift?
I have setup a protocol to send some information back to the previous VC.
I define it like this:
protocol FilterViewControllerDelegate: class {
func didSearch(Parameters:[String: String]?)
}
...
47
votes
1
answer
12k
views
Swift 2 Error using mutating function in Protocol extension "Cannot use mutating member on immutable value: 'self' is immutable
Not sure what's going on here, this seems like it should be pretty straight forward. I have a protocol that mutable var, an extension with a mutating function. Things are crapping out in the ...
47
votes
3
answers
3k
views
Why can't a get-only property requirement in a protocol be satisfied by a property which conforms?
Why does the following code produce an error?
protocol ProtocolA {
var someProperty: ProtocolB { get }
}
protocol ProtocolB {}
class ConformsToB: ProtocolB {}
class SomeClass: ProtocolA { // ...
39
votes
8
answers
29k
views
How can I call a static function on a protocol in a generic way?
Is there a point to declaring a static function on a protocol? The client using the protocol has to call the function on a type conforming to the protocol anyway right? That breaks the idea of not ...
36
votes
2
answers
14k
views
SwiftUI: ViewModifier where content is an Image
I get an error "Type 'PlayButtonModifier' does not conform to protocol 'ViewModifier'" and I do not understand why and - even more important - how to do it right.
I simply try to create a ...
35
votes
1
answer
15k
views
Difference between Swift's hash and hashValue
The Hashable protocol in Swift requires you to implement a property called hashValue:
protocol Hashable : Equatable {
/// Returns the hash value. The hash value is not guaranteed to be stable
...
27
votes
3
answers
6k
views
Type CCC doesnt conform to protocol 'NSObjectProtocol'
I don't understand why my code doesn't work. Here it is:
class Test: NSURLSessionDataDelegate {
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?...
27
votes
1
answer
9k
views
Swift protocol with "where Self" clause
In addition to this syntax with a protocol extension:
protocol P {}
extension P where Self : UIView {}
... I discovered by accident that you can use the same where clause on the protocol itself:
...
26
votes
2
answers
3k
views
What is the in-practice difference between generic and protocol-typed function parameters?
Given a protocol without any associated types:
protocol SomeProtocol
{
var someProperty: Int { get }
}
What is the difference between these two functions, in practice (meaning not "one is ...
26
votes
3
answers
19k
views
Nested types inside a protocol
It is possible to have nested types declared inside protocols, like this:
protocol Nested {
class NameOfClass {
var property: String { get set }
}
}
Xcode says "Type not allowed ...
25
votes
2
answers
40k
views
How to conform to a protocol's variables' set & get?
I'm playing around with protocols and how to conform to them.
protocol Human {
var height: Int { get set }
}
struct Boy: Human {
var height: Int { return 5 } // error!
}
I'm trying ...
24
votes
4
answers
6k
views
A Swift protocol requirement that can only be satisfied by using a final class
I'm modeling a owner/ownee scheme on Swift:
class Owner<T: Ownee> {
// ...
}
protocol Ownee {
var owner: Owner<Self> { get }
}
Then I have a pair of classes professor/student ...
24
votes
2
answers
9k
views
Swift extension of a class ONLY when it conforms to a specific protocol
Hi there =) I was just faced with a design problem where I need to (essentially) do the following:
I want to inject a bit of code on viewWillAppear: of any UIViewController subclass that conforms to ...
23
votes
4
answers
8k
views
Can I extend Tuples in Swift?
I'd like to write an extension for tuples of (e.g.) two value in Swift. For instance, I'd like to write this swap method:
let t = (1, "one")
let s = t.swap
such that s would be of type (String, Int) ...
23
votes
1
answer
6k
views
Mark protocol method as deprecated
How do I make a protocol method appear as deprecated for someone implementing the protocol? I've tried using @available as shown below, but there is no warning shown in Xcode when implementing the ...
21
votes
1
answer
16k
views
Declare protocol function with default argument values
I want this function be in protocol:
func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())? = nil) {
// do some stuff
}
But when I write such ...
20
votes
4
answers
13k
views
Swift protocol nested in a class
I would like to nest a protocol in my class to implement the delegate pattern like so :
class MyViewController : UIViewController {
protocol Delegate {
func eventHappened()
}
...
20
votes
1
answer
15k
views
Make a swift protocol conform to Hashable
I'm going around in circles trying to get Hashable to work with multiple struct that conform to the same protocol.
I have a protocol SomeLocation declared like this:
protocol SomeLocation {
var ...
18
votes
3
answers
23k
views
Pass data between ViewController and ContainerViewController
I'm working on an app, and need to pass data between view and containerView. I need to send data and receive data from both Views.
Let me explain better:
I can change the Label Master (Touch the ...
18
votes
6
answers
2k
views
IBOutlet crashing with EXC_BAD_ACCESS even though not nil
In a UIViewController (rolePageController) I configure another UIViewController (drawerController) and pass it 2 UIViews from the role page that will be part of the drawerController's configuration. ...
16
votes
1
answer
3k
views
Why do Self and self sometimes refer to different types in static functions?
Recently I have been developing multiple heavily protocol-oriented application frameworks with Swift and noticed a few (seemingly) odd behaviors with static functions in protocol extensions, ...
15
votes
1
answer
8k
views
How do I conform to a protocol with an actor?
When I try to define an actor that conforms to a protocol, Xcode gives me the error Actor-isolated instance method 'foo()' cannot be used to satisfy nonisolated protocol requirement. I can make the ...
15
votes
1
answer
2k
views
KVObserving a protocol in Swift 4
I am struggling to use the new strongly-typed KVO syntax in Swift 4 to observe properties that are only visible through a protocol:
import Cocoa
@objc protocol Observable: class {
var bar: Int { ...
14
votes
3
answers
9k
views
Protocol function with generic type
I would like to create a protocol like the following:
protocol Parser {
func parse() -> ParserOutcome<?>
}
enum ParserOutcome<Result> {
case result(Result)
case parser(...
14
votes
2
answers
8k
views
Unable to use protocol as associatedtype in another protocol in Swift
I have a protocol, Address, which inherits from another protocol, Validator, and Address fulfills the Validator requirement in the extension.
There is another protocol, FromRepresentable, which has ...
14
votes
3
answers
13k
views
Swift Public protocols with Internal functions and properties
I am wondering what the best practice is when I want some functions to be public and some to me internal when working with protocols.I am writing an AudioManager in Swift 3 wrapping AVPlayer as a ...
13
votes
2
answers
5k
views
Self, protocol extension and non-final class
I tried write a static method for UIView which instantiates view of that class from the nib. Method should be generic and work on every UIView subclasses. Also I want to save the type information – so,...
12
votes
1
answer
6k
views
Do not understand "Member '<func>' cannot be used on value of type 'any <type>'; consider using a generic constraint instead" error
Having a problem with a protocol & generics that I am just not able to quite get a handle on.
In the code below, marked by ERROR HERE comment, I am getting the following error:
Member '...
12
votes
1
answer
3k
views
Generic Array of weak references to class bound protocol in Swift 4.1
I'm trying to create a generic WeakReference type that I can put into an array (and ultimately create a generic weak array type).
So far so good, but the following code:
class WeakReference<...
11
votes
2
answers
1k
views
Swift 4 JSON decoding when type is only known at runtime
Is it possible with the Decodable protocol in Swift 4 to decode a JSON object when the type to decode to is only known at runtime?
I have a registry of sorts which maps a String identifier to the ...
11
votes
2
answers
3k
views
Make property of type and also conform to protocol in Swift
I would like to make a property that is of a certain type and also conforms to a protocol, which I would have done in Objective-C like this:
@property (nonatomic) UIViewController<CustomProtocol&...
11
votes
2
answers
4k
views
Why 'there cannot be more than one conformance, even with different conditional bounds'?
I hoped that Swift gives me the ability to create an extension for type with specified conditions in where block. I imagined that I can extend the same generic type with different extensions dependent ...
11
votes
1
answer
5k
views
When to use protocol in Swift
I ask a question today because I’m little bit lost today. It’s about Swift and protocol and more about Protocol Oriented Programming (POP).
I read articles about it, even a book but I’m still ...
11
votes
2
answers
2k
views
How to visualize Protocols and Extensions in UML?
It seems reasonable to use UML Interfaces to visualize Swift Protocols in UML. But how should I visualize an extension that provides a default implementation for a specific protocol? Should I just use ...