Last active
May 9, 2017 20:27
-
-
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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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