2
\$\begingroup\$

I want to reduce boiler-plate code and write like this when developing in iOS:

let imgView: UIImageView = "share_fareware_text_bg"

Here is implementation code:

class ImageView: UIImageView, ExpressibleByStringLiteral{
    public convenience required init(stringLiteral value: String) {
        self.init(image: UIImage(named: value))
    }
}

Then I can call:

let imgView: ImageView = "share_fareware_text_bg"

Is there any better way to do it more naturally?

\$\endgroup\$
  • \$\begingroup\$ Do you create all image views programmatically, and not in the Storyboard? \$\endgroup\$ – Martin R Sep 16 at 6:18
  • \$\begingroup\$ Storyboard is nice. Our team mainly build UI programmatically. This is the main code style in Shanghai \$\endgroup\$ – black_pearl Sep 16 at 7:08
  • 1
    \$\begingroup\$ A convenience initializer from String would be more appropriate/make more sense to me. Plus, using string literals all over your code is prone to error, and isn't ideal for teamwork, better use a resources Struct. Have a look here github.com/mac-cain13/R.swift \$\endgroup\$ – ielyamani Sep 17 at 8:24
  • \$\begingroup\$ R is wonderful \$\endgroup\$ – black_pearl Sep 17 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.