Search code examples
swiftswift-extensions

Extension with a receive value


I'm learning about extension in swift and I want to create a extension for String like the command .hasPrefix(), in that command we send a String, for test it I try this code:

extension String{

    var teste:(String) { return "\(self) - \($1)" }

}

texto.teste("other String")

But not working, all I want to do is create a extension that we can send other values like .hasPrefix (that send a string inside) .hasSufix (send a string too), How can i do this?


Solution

  • var teste: String { ... } is a computed property, and computed properties cannot take parameters.

    You'll want to define an extension method:

    extension String {
    
        func teste(arg : String) -> String {
            return "\(self) - \(arg)"
        }
    }
    
    println("foo".teste("bar"))
    // foo - bar