Is it possible to make an Array extension in Swift that is restricted to one class?

后端 未结 4 778
暖寄归人
暖寄归人 2020-11-27 21:39

Can I make an Array extension that applies to, for instance, just Strings?

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 21:51

    You still haven't given a use case, despite many requests in comments, so it's hard to know what you're after. But, as I've already said in a comment (and Rob has said in an answer), you won't get it literally; extensions don't work that way (at the moment).

    As I said in a comment, what I would do is wrap the array in a struct. Now the struct guards and guarantees the string's type, and we have encapsulation. Here's an example, though of course you must keep in mind that you've given no indication of the kind of thing you'd really like to do, so this might not be directly satisfying:

    struct StringArrayWrapper : Printable {
        private var arr : [String]
        var description : String { return self.arr.description }
        init(_ arr:[String]) {
            self.arr = arr
        }
        mutating func upcase() {
            self.arr = self.arr.map {$0.uppercaseString}
        }
    }
    

    And here's how to call it:

        let pepboys = ["Manny", "Moe", "Jack"]
        var saw = StringArrayWrapper(pepboys)
        saw.upcase()
        println(saw)
    

    Thus we have effectively insulated our string array into a world where we can arm it with functions that apply only to string arrays. If pepboys were not a string array, we couldn't have wrapped it in a StringArrayWrapper to begin with.

提交回复
热议问题