Skip to content

Instantly share code, notes, and snippets.

@cpatterson-lilly
Last active May 9, 2017 20:27
Show Gist options
  • Save cpatterson-lilly/44fc5cf822b43310058567488faf028a to your computer and use it in GitHub Desktop.
Save cpatterson-lilly/44fc5cf822b43310058567488faf028a to your computer and use it in GitHub Desktop.
Swift protocols don't enforce the `throws` keyword on methods? Is this a bug or a feature? Paste this code into a new Xcode 8.3.2 playground...
//: Playground - noun: a place where people can play
import Foundation
protocol CharacteristicValue {
func characteristicValue() throws -> Data
}
extension String: CharacteristicValue {
// Why does this compile without "throws"?
// Shouldn't it complain that it does not conform to the protocol?
func characteristicValue() -> Data {
return self.data(using: .utf8)!
}
}
let testData = "TEST DATA".characteristicValue()
let result = String(data: testData, encoding: .utf8)
// Now lets use the protocol in a structure
// and access the String object through it.
struct Test {
let charValue: CharacteristicValue
init(charValue: CharacteristicValue) {
self.charValue = charValue
}
}
let test = Test(charValue: "TEST DATA")
let str = test.charValue
// The compiler requires the "try?" here even though
// the specific implementation does not throw.
let foo = try? test.charValue.characteristicValue()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment