综合编程

A Generic Swift Blog Post

I began investigating SwiftUI to see if it is indeed the shortest path to a great app. Since then, I committed an update to the MemeMaker project that makes the initial interface a list of examples. I was experimenting with passing a different View into each row as the destination of the row’s NavigationButton, rather than hard-coding the destination.


I found that you can’t just make a property of type View. I believe that is because it uses Self within its declaration of the body property. And so the compiler dutifully complained.

Seeing the type-erasing AnyView type in the documentation, I wrapped everything in AnyViews to get it all working.

I got some feedback from Matt Ricketson on Twitter suggesting I use generics here instead.

This is a great example for trying out generics instead of AnyView. It will make your NavigationButton even simpler, and in general will give better performance. AnyView should be a tool of last resort.

— Matt Ricketson (@ricketson_)
June 12, 2019

Of course it makes complete sense, with better code and less code. You can see the diff here.

With the SwiftUI and Combine frameworks using generics so heavily, I need to develop my intuition about generics beyond arrays and dictionaries. I also really need get better at reading declarations that are chock full of generics.

Fortunately, I think the two go hand in hand.

When Swift first arrived, I found reading optionals in code to be difficult. But AppKit and UIKit development meant using them immediately. I dug in to understand them as best I could. I even wrote a song about it. And now reading and writing code with question marks and exclamation points seems natural, not baffling.

I’m hopeful that as I use SwiftUI and Combine that I’ll refine how I think about generics as well.

I’m also curious. Are there ways that you think about genetics that have made them more understandable for you? (Not so much the syntax, more so the zen of generics) Any articles that you’ve found particularly useful?

I’d love to hear. Please send any of your generic thoughts or thoughts on genetics to @jamesdempsey at Micro.blog or Twitter .

Also, if you are ever writing about generics on an iPhone: BEWARE! Autocorrect really wants to replace ‘generics’ with ‘genetics’! •

展开阅读全文

微信扫一扫,分享到朋友圈

A Generic Swift Blog Post
0

三星Galaxy Fit健康和睡眠追踪器上市 售价不到100美元

上一篇

Host firebreath plugin in Node.js

下一篇

你也可能喜欢

评论已经被关闭。

插入图片
James Dempsey 投稿者
我还没有学会写个人说明!
最近文章
  • 1 A Kid in the June 2019 Candy Store
  • 2 SwiftUI: Almost Too Much Fun
  • 3 Where I’ll be at WWDC 2019
  • A Generic Swift Blog Post

    长按储存图像,分享给朋友