0
0
Swiftprogramming~10 mins

Protocol conformance via extension in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to make the struct conform to the protocol by adding the required property.

Swift
protocol Describable {
    var description: String { get }
}

struct Car: Describable {
    var make: String
    var model: String
    var description: String {
        return [1]
    }
}
Drag options to blanks, or click blank then click option'
Adescription
Bprint(make)
Cmake + model
D"\(make) \(model)"
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a print statement instead of a string.
Using the property name 'description' inside itself causing recursion.
2fill in blank
medium

Complete the extension to make Int conform to the protocol by implementing the required method.

Swift
protocol Squarable {
    func squared() -> Int
}

extension Int: Squarable {
    func squared() -> Int {
        return [1]
    }
}
Drag options to blanks, or click blank then click option'
Aself * self
Bself + self
Cself / self
Dself - self
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or subtraction instead of multiplication.
Dividing the number by itself which always returns 1.
3fill in blank
hard

Fix the error in the extension to correctly conform to the protocol by implementing the required computed property.

Swift
protocol Identifiable {
    var id: String { get }
}

struct User {
    var name: String
}

extension User: Identifiable {
    var [1]: String {
        return name
    }
}
Drag options to blanks, or click blank then click option'
Aid
Bidentifier
Cname
DuserId
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different property name than the protocol requires.
Not implementing the property at all.
4fill in blank
hard

Fill both blanks to complete the extension that makes Array conform to the protocol by implementing the required method.

Swift
protocol Summable {
    func sum() -> Int
}

extension Array: Summable where Element == Int {
    func sum() -> Int {
        return self.[1](0) { $0 [2] $1 }
    }
}
Drag options to blanks, or click blank then click option'
Areduce
B+
C*
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using * or - instead of + for summing.
Using map or filter instead of reduce.
5fill in blank
hard

Fill all three blanks to complete the extension that makes String conform to the protocol by implementing the required computed property and method.

Swift
protocol TextRepresentable {
    var text: String { get }
    func shout() -> String
}

extension String: TextRepresentable {
    var [1]: String {
        return self
    }
    func [2]() -> String {
        return self.[3]()
    }
}
Drag options to blanks, or click blank then click option'
Atext
Bshout
Cuppercased
Dlowercased
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong property or method names.
Using 'lowercased()' instead of 'uppercased()' for shout.