Namespaces and modules in the Swift language - xcode

I've been experimenting with Swift on my way home from WWDC. One of the most compelling new features of Swift, in my opinion, was namespacing. I haven't managed to get it to work as I expected it should though. Please see the attached screenshot and let me know if you have an idea of what I'm doing wrong.
EDIT: I have of course tried to remove the import statement.

Turns out that this is a known bug: https://devforums.apple.com/message/976286#976286

I am sorry, if I search for "namespace" or "namespacing" in the Swift-eBook there are no results. Maybe you can give me a link to an additional resource?
I would solve your problem simply with a struct and static functions.
ClassA
struct ClassA {
static func localize() {
println("Localized String")
}
}
ClassB
You can drop the import and execute the ClassA-function as follows:
ClassA.localize()
The second way
In your case you can also just make an extension of String like so:
extension String {
func localize() -> String {
return self+"-localized"
}
}
println("Test".localize()) // prints "Test-localized"

Related

How to handle tap events for an interactive watch faces with androidx.wear?

What is the correct way of handling tap events with the new androidx.wear.watchface libraries? I was doing this with the now deprecated android.support:wearable libraries without any problem with Java (using onTapCommand). Now, everything seems to be quite different, especially since the documentation and examples seem to be available only in Kotlin. Also, I can't find any example which properly shows how the functions are used.
The documentation mentions setTapListener, TapListener. And then there are the functions onTap, onTapEvent and onTapCommand. This seems very confusing.
Could somebody put here a small example? Or point me to a working example on the internet?
Any help much appreciated!
Implementing this seemed to work for me
https://developer.android.com/reference/androidx/wear/watchface/WatchFace.TapListener
My code:
class WatchFaceRenderer(...): Renderer.CanvasRenderer(...), WatchFace.TapListener {
override fun onTapEvent(tapType: Int, tapEvent: TapEvent, complicationSlot: ComplicationSlot?) {
if (tapType == TapType.UP)
// do something
invalidate()
}
}
class Service : WatchFaceService() {
override suspend fun createWatchFace(
surfaceHolder: SurfaceHolder,
watchState: WatchState,
complicationSlotsManager: ComplicationSlotsManager,
currentUserStyleRepository: CurrentUserStyleRepository
): WatchFace {
val renderer = WatchFaceRenderer(
context = applicationContext,
surfaceHolder = surfaceHolder,
watchState = watchState,
currentUserStyleRepository = currentUserStyleRepository,
canvasType = CanvasType.SOFTWARE,
)
return WatchFace(WatchFaceType.ANALOG, renderer).setTapListener(renderer)
}
}

How can an external package implement an interface implicitly?

I'm writing a piece of code that relies on some implementation.
I want to decouple the implementation from my code, and make the implementation as independent as possible.
I thought of achieving this approach by using interfaces instead of concrete types, like so:
package mypackage
type MyType interface {
Title() string
Price() int
}
type TypeGetter interface {
GetType() MyType
}
func MyHandler(tg TypeGetter) {
t := tg.GetType()
fmt.Printf("Title: %s, Price: %d", t.Title(), t.Price())
}
And an implementation might be something like this:
package external
// CustomType implicitly implements the MyType interface
type CustomType struct {
title string
price int
}
func (t CustomType) Title() string { return t.title }
func (t CustomType) Price() int { return t.price }
// CustomTypeGetter implicitly implements the TypeGetter interface. Or is it???
type CustomTypeGetter struct {
}
func (g CustomTypeGetter) GetType() CustomType {
return CustomType{"Hello", 42}
}
Then, the code would do something like this:
package main
import "mypackage"
import "external"
func main() {
tg := external.CustomTypeGetter{}
mypackage.MyHandler(tg) // <--- the compiler does not like this
}
I hope the example speaks for itself: I have no coupling between "mypackage" and the "external" package, which may be replaced, substituted my mocks for testing, etc.
The problem: the compiler complains that the call to MyHandler has an object that implements:
func GetType() CustomType, instead of:
func GetType() MyType
The only solution I found is to move the interface declarations (MyType and TypeGetter) to a third package, and then both "mypackage" and "external" packages can use it.
But I want to avoid that.
Isn't Go's concept of implicit implementation of interfaces contradict the idea of a third common package?
Is there a way to implement such thing, without binding the two packages together?
Isn't Go's concept of implicit implementation of interfaces contradict the idea of a third common package?
I think it does. Go authors introduced an implicit interface implementation to eliminate unnecessary dependencies between packages. That works well for simple interfaces like io.Reader, but you cannot apply it everywhere.
One of the language creators, Rob Pike, says that the non-declarative satisfaction of interfaces is not the essential part of the idea behind interfaces in Go. It's a nice feature, but not all elements of the language are practical or possible to use every time.
For complex interfaces, you need to import a package where the interface is defined. For example, if you want to implement an SQL driver that works with the sql package from the standard library, you must import the sql/driver package.
I would recommend not introducing interfaces at the beginning of your project. Usually, it leads to situations where you need to solve artificial problems like rewriting the interface each time you updates your understanding of the domain model. It is hard to come up with a good abstraction from the first attempt, and, in many cases, it is unnecessary, in my opinion.
I need to query external source for products. I don't care how the external sources store the data (db, file, network). I just need a "product" type. So it's either I define a Product type, forcing the external implementations to import and use it, or the Go way - define a Product interface and let the implementations implicitly implement this interface. Which apparently doesn't work
I see two loosely related goals here:
Define an interface to swap implementations of the product source.
A package that implements the product source should not import the package that defines the interface.
From my experience, I would recommend doing point 1 only when you have at least one working implementation of the product source service.
Point 2 is not always possible to achieve, and it is fine; please see the example from the standard Go library above.
P.S.
Please, consider not creating Product interface. While it does makes sense to come up with the PorductSource interface eventually, Product is most probably just a set of data; struct is a perfect way to represent such information. Please, see this very relevant code smaple and this article for inspiration.
The problem with your approach is that you want someone to implement an interface that refers to your type (MyType). This obviously cannot be done without the implementation referring to your type. This is the only thing that prevents the above code from working.
If you get rid of the MyType:
type TypeGetter interface {
GetType() interface {
Title() string
Price() int
}
}
And the implementation:
func (g CustomTypeGetter) GetType() interface {
Title() string
Price() int
} {
return CustomType{"Hello", 42}
}
Then this code will work:
func main() {
tg := external.CustomTypeGetter{}
mypackage.MyHandler(tg)
}
Yes, this requires repetition, but only because you don't want an unknown / future implementation to refer to your type (to not depend on it).
In this case you may change MyHandler() to take a value of type MyType (get rid of the "factory"):
func MyHandler(t MyType) {
fmt.Printf("Title: %s, Price: %d", t.Title(), t.Price())
}
And any value that implements MyType may be passed. Add a "factory" to the external package:
func NewCustomType(title string, price int) CustomType {
return CustomType{
title: title,
price: price,
}
}
And use it like this:
func main() {
t := external.NewCustomType("title", 1)
mypackage.MyHandler(t)
}
If you truly require the factory pattern, then yes, creating a 3rd package that will hold MyType is the way to go. Then both your app and the implementations may refer to this 3rd package.

How to implement and use the `buildIf` function in the #functionBuilder structure correctly?

i what to know more about SwiftUI, so i decided to make my own functionBuilder.
I made something like this:
public static func buildBlock<Content>(_ contents: Content...) -> Content {
return CombinedContent(with: contents)
}
And it works as expected
But i can't understand what should i do with buidIf function.
Does it should takes optional content and if it's nil return empty View or something?
I would also like to know how does it works under all this abstractions.
Thanks

Why to call private function from a public one, instead of implemente code in public one?

I see a lot of codes like this in the golang src:
func Open(path string) (*Plugin, error) {
return open(path)
}
func open() {
// etc
}
A private function been called from a public. Why not just:
func Open(path string) (*Plugin, error) {
// code of open here
}
ref: https://golang.org/src/plugin/plugin.go?s=1065:1104#L21
I do understand that sometimes it makes sense, especially if there are more functions using open. But that's not the case.
Is this some kind of Golang way of organizing things?
In this case, it appears to be because the actual implementation is OS dependent.
The plugin implementation plugin_dlopen.go is used only for OSX and Linux, and the alternative plugin_stubs.go is for everything else(which just contains dummy functions as there is no implementation for other systems yet.)
This allows you to keep OS dependent code in one file using build tags, while keeping general code, the public API and documentation for the public API in a single place.

Does Processing 3 have class declarations?

Our school project has us make a game using Processing 3. After some studying with the language, our team is pretty confident we can work with the project, though we do have certain reservations of the chosen language.
However, there is one major question we are wondering and could not find an answer. In C++ and many others, when you create a new class in a new file you also create a header file you can include. Does Processing 3 have something similar? I know you can "include" files by adding more tabs, which is still weird but whatever. We would like to have some sort of declarations in advance so we can comment/describe classes and their methods, rather than force each member go through lots of code to find the proper point.
In short, we want to be able to do something like this:
Example.pde
class Example {
//Description
Example();
//Description
void doSomething(int variable);
}
//Other team members don't have to worry past this,
//as they have already seen the public interface
Example::Example()
{
//Constructor
}
void Example::doSomething(int variable)
{
//Function
}
Or do we have to always to like this:
Example.pde
class Example {
//Description
Example()
{
//Constructor
}
//Description
void doSomething(int variable)
{
//Function
}
}
Processing is written in Java, so you can only do things that Java supports. Java does not support header files, so no, you can't use header files in Processing.
However, it sounds like what you're really looking for is an interface.
interface Example {
void doSomething(int variable);
}
class MyExample implements Example{
public MyExample(){
//Constructor
}
void doSomething(int variable){
//Function
}
}
With this, you would only need to show other team members the interface, not the class. As long as they program to the interface, they don't need to ever see the class implementation.
More info on interfaces can be found in the Processing reference.

Resources