介绍 Fedora 上的 Swift
Swift
![](/data/attachment/album/201810/20/093525ccnxl3l5zxqwwpsj.jpg)


Swift 是一种使用现代方法构建安全性、性能和软件设计模式的通用编程语言。它旨在成为各种编程项目的最佳语言，从系统编程到桌面应用程序，以及扩展到云服务。继续阅读了解它以及如何在 Fedora 中尝试它。


### 安全、快速、富有表现力


与许多现代编程语言一样，Swift 被设计为比基于 C 的语言更安全。例如，变量总是在使用之前初始化。检查数组和整数是否溢出。内存自动管理。


Swift 将意图放在语法中。要声明变量，请使用 `var` 关键字。要声明常量，请使用 `let`。


Swift 还保证对象永远不会是 `nil`。实际上，尝试使用已知为 `nil` 的对象将导致编译时错误。当使用 `nil` 值时，它支持一种称为 **optional** 的机制。optional 可能包含 `nil`，但使用 `?` 运算符可以安全地解包。


更多的功能包括：


* 与函数指针统一的闭包
* 元组和多个返回值
* 泛型
* 对范围或集合进行快速而简洁的迭代
* 支持方法、扩展和协议的结构体
* 函数式编程模式，例如 `map` 和 `filter`
* 内置强大的错误处理
* 拥有 `do`、`guard`、`defer` 和 `repeat` 关键字的高级控制流


### 尝试 Swift


Swift 在 Fedora 28 中可用，包名为 **swift-lang**。安装完成后，运行 `swift` 并启动 REPL 控制台。



```
$ swift
Welcome to Swift version 4.2 (swift-4.2-RELEASE). Type :help for assistance.
 1> let greeting="Hello world!"
greeting: String = "Hello world!"
 2> print(greeting)
Hello world!
 3> greeting = "Hello universe!"
error: repl.swift:3:10: error: cannot assign to value: 'greeting' is a 'let' constant
greeting = "Hello universe!"
~~~~~~~~ ^


 3>
```

Swift 有一个不断发展的社区，特别的，有一个[工作组](https://swift.org/server/)致力于使其成为一种高效且有力的服务器端编程语言。请访问其[主页](http://swift.org)了解更多参与方式。


图片由 [Uillian Vargas](https://unsplash.com/photos/7oJpVR1inGk?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) 发布在 [Unsplash](https://unsplash.com/search/photos/fast?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) 上。




---


via: <https://fedoramagazine.org/introducing-swift-fedora/>


作者：[Link Dupont](https://fedoramagazine.org/author/linkdupont/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[geekpi](https://github.com/geekpi) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns. It aims to be the best language for a variety of programming projects, ranging from systems programming to desktop applications and scaling up to cloud services. Read more about it and how to try it out in Fedora.


## Safe, Fast, Expressive

Like many modern programming languages, Swift was designed to be safer than C-based languages. For example, variables are always initialized before they can be used. Arrays and integers are checked for overflow. Memory is automatically managed.

Swift puts intent right in the syntax. To declare a variable, use the *var* keyword. To declare a constant, use *let*.

Swift also guarantees that objects can never be *nil*; in fact, trying to use an object known to be *nil* will cause a compile-time error. When using a *nil* value is appropriate, it supports a mechanism called **optionals**. An optional may contain *nil*, but is safely unwrapped using the **?** operator.

Some additional features include:

- Closures unified with function pointers
- Tuples and multiple return values
- Generics
- Fast and concise iteration over a range or collection
- Structs that support methods, extensions, and protocols
- Functional programming patterns, e.g., map and filter
- Powerful error handling built-in
- Advanced control flow with do, guard, defer, and repeat keywords

## Try Swift out

Swift is available in Fedora 28 under then package name **swift-lang**. Once installed, run *swift* and the REPL console starts up.

$ swift Welcome to Swift version 4.2 (swift-4.2-RELEASE). Type :help for assistance. 1> let greeting="Hello world!" greeting: String = "Hello world!" 2> print(greeting) Hello world! 3> greeting = "Hello universe!" error: repl.swift:3:10: error: cannot assign to value: 'greeting' is a 'let' constant greeting = "Hello universe!" ~~~~~~~~ ^ 3>

Swift has a growing community, and in particular, a [work group](https://swift.org/server/) dedicated to making it an efficient and effective server-side programming language. Be sure to visit [its home page](http://swift.org) for more ways to get involved.

Photo by [Uillian Vargas](https://unsplash.com/photos/7oJpVR1inGk?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/search/photos/fast?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText).

## Lan

Swift is almost useless on linux-based operating system without a way to create iOS and macOS applications. 🙁

## Paul W. Frields

@Lan: Swift is used in scientific applications as well, independently of iOS and MacOS.

## Cris

What are the benefits of Swift over Julia? It was a rhetorical question. I understand that it’s good to have alternatives but I don’t see this expanding beyond the Apple ecosystem. Just another FireWire®

## Tpk

Swift is a first class language for Tensorflow for example

## Ray Scott

I don’t think Apple have ever had the intention of porting their frameworks to Linux. I believe Swift support on Linux is intended to be used for writing backend services, but even that’s not possible I imagine without Apple’s Foundation module.

## Link Dupont

The Swift binary distribution from swift.org and the source code distribution available on GitHub include an implementation of the Foundation module. From the README:

Fedora’s swift-lang package includes this module.

## Ray Scott

Thanks for informing me. I might actually give it a try! 🙂

## Robb

Do you know if SourceKittenDaemon is included, or might be in the future?

## Ron Olson

It isn’t included as it’s not officially part of Apple’s toolchain. I’d never heard of it until now; I’ll take a look to see how difficult it would be to package.

## Robb

Thanks! It’s the equivalent of Rust Racer – the editor plugin that really brings home the benefits of working with an inferencing, statically typed language.

## Ron Olson

The Linux version of Swift includes the Foundation framework, along with Dispatch (GCD on MacOS) and, specifically for Linux, Glibc.

## Ron Olson

My use of Swift on Linux has been to test out code, algorithms, etc.; I can log into a powerful 16-core Linux box and use multithreaded Swift code without dealing with my much older, and much slower, Mac.

## M Leslie Satenstein

As far as I know from what I read about recent C compilers, uninitialized pointers and arrays are Nulled. Numbers (int, a char, float, are set to zero at function prologue.

My gcc C compiler tells me about a variable’s first use before being set.

If not C, I would still use C. The human brain knows better how to manage memory allocations.

## Andi

So, Fedora opens up the possibility to use Swift in order to develop Apps on Fedora? Is it right? Normally, I have to do it with my iMac.

## Robb

Really happy to see support for Fedora!

IMO there’s one piece of the puzzle remaining, to develop Swift on Linux: autocomplete and other code intelligence support. And

thatwill only arrive if “SourceKittenDaemon” is ported to Linux:https://github.com/terhechte/SourceKittenDaemon/issues/74

Without this part of the picture, we can’t get a lot of the benefits from working with Swift: the smart development environment that helps out with documentation and more as we go.

So personally, I switched to Rust as my compiled, modern, friendly Linux development language. But I’d like to see Swift give it some competition.

## Robb

Really happy to see this support for Swift.

I gave Swift dev on Fedora a try, but the lack of an intelligent code plugin held me back:

https://github.com/terhechte/SourceKittenDaemon/issues/74

No, I don’t NEED autocompletion and in-place documentation to code, but it makes my life so much more pleasant. I gave Rust a try, and it’s pretty much fulfilling the Swift promise, on Linux. Rust’s “Racer” code intelligence app compiles fine.

I’d love to give Swift a real shot on Fedora, but without IDE/editor support, we don’t get the full benefits.

## Paul W. Frields

I believe one can get Swift plugins for VS Code, which is available on Fedora, if you want to use that.

## Robb

Thanks, yep – that’s the path I followed, which led me to the SourceKittenDaemon dependency. If I’m right, that’s the piece which actually does the heavy lifting for the Swift plugins in VSC, Emacs, etc.

## Ray

I tried that this afternoon, but the plugin complained about a missing SourceKit dependency. I think the VSCode plugins are only expected to work on macOS, and won’t work on Linux until the SourceKit related issues are resolved.

## ANDRE GOMPEL

For assertive programming, from C, to Erlang, Julia, Go, Rust, Swift (and more), so many “me too languages” who do almost the same thing as C (C99) !

For system low level, the differences are so minor, that rather than a yet another language (YAL), I would much prefer as “a pragma statement” at the beginning of the source file, a choice for “YAFC” (yet another flavor of C).

So in most case (I know it is not always easy) theses file could be linked together.

In most cases it is doable.

Noe that many years ago, DEC (Digital Equipment Corporation) almost achieved the same goal on VAX/VMS.

The main issues are :

* “multi-core” processing (Like in Erlang).

Memory management (Automatic garbage collection is rarely suitable for system low level, i.e self contained , without O/S resources).

Object Oriented (when available) name mangling.

In line assembly code (Often necessary for system low level).

I am not sure thought, that a language adequate for system low level, which include device drivers, scheduler, semaphores, access to memory, and I/O mapped, embedded system (without an OS)…) will be the same for “a great application level” programming language, which in most cases run on top of an O/S and all its resources.

Microsoft Visual Studio:

I know, many people love IDE’s (I still prefer the UNIX philosophy of separate solutions: compiler, linker, debugger, Makefiles or similar).

I see a danger for the Open Source, to leave the control wide open to a large corporation (Microsoft) for the much appreciated “Visual Studio”, for which there seem to be no great “pure open source” equivalent.

GTK+ and Qt provide decent GUI frameworks. (Not KDE, bloated, never finished). Wondering if it ever will be a great FOSS, IDE build with either one?

Please comment.

Andre Gompel

## Frederik

For C++, the combination of Gnome builder and glade works pretty well. You’re buying into the entire glib ecosystem which is a no-go for some — personally that was the case, but I’ve realize that you simply can’t get anything real done without buying into one ecosystem or another. I personally like how glib does things, more than I like how Qt does things (lot of legacy cruft that hasn’t been dumped). I use the C-API of Glib, not the C++ API, which loses a lot of values over the C API on it’s insistence on using classes.

Gnome builder lacks a few integrations out of the box. I’d love to see a glade plugin that will at least allow me to launch glade from the IDE; at the moment I have to open my UI files from somewhere outside of Gnome builder. The git plugin seems to be hidden somewhere on the internet, that I can’t find (please provide a link if you know where to find it).

Given it’s dependency on meson (which is awesome), I would love to see a better integration with the Gnome builder.

## Michael J. Ryan

FYI: Visual Studio Code is completely Open-Source with an MIT license [1]. Not to be confused with the Visual Studio IDE. It’s quickly become one of the best developer environments on the planet imho. I use it on Windows, Linux and Mac regularly, as I tend to prefer the same tools everywhere as much as possible.

[1] https://github.com/Microsoft/vscode

## Ron Olson

I can also confirm that VS Code has syntax highlighting for Swift under Linux; I’m using it right now. 🙂

## Elmmur

Actually, the VS Code application that Microsoft provides is closed source.

License, see 5. :

http://code.visualstudio.com/license

If you would like to use actually FOSS VS code, you have to build it yourself:

https://github.com/Microsoft/vscode/wiki/How-to-Contribute

Or use flatpak OSS version with MS marketplace integrated:

https://flathub.org/apps/details/com.visualstudio.code.oss

More details:

https://github.com/flathub/com.visualstudio.code.oss/issues/6#issuecomment-380152999

## Elmmur

Give KDevelop a chance.

GomeBuilder is deeply tied to gnome projects. They even pin gnome projects at the front page, which will be wholey dowloaded if you click on them. That actually holds me back from it. But yeah maybe that’s why it’s called Gnome Builder. Anyway, KDevelop looks more like a general purpouse IDE to me.

## Thomas An

Can we use the kind of libraries with swift in Fedora? For examples, GLib, Gtk, DBus and so on. If so, it would be nice 🙂

## Ron Olson

You can interact with native libraries/headers, etc. Take a look at this (now old) project I wrote to learn how to do this very thing: https://github.com/tachoknight/Crazy8sBot. You could just as well work with any other library via the ‘unsafe’ bindings.

## Van

We can do server side on linux with Vapor (https://github.com/vapor/vapor) or Kitura (https://github.com/IBM-Swift/Kitura), Perfect. Apple also developed SwiftNIO for supporting server side frameworks (https://github.com/apple/swift-nio)

## steve

I downloaded and tried it. sorry to be so selective but there is no gui? modern programming languages have good editors, gui and graphical design of the screens. this looks like it runs in vi and is terminal based only. useless in today’s world. Unless i am doing something wrong in which case please tell me what it is.

## Ron Olson

Turning it around, good editors know about languages; gcc does not come with its own editor, but most (all?) Linux-based editors know how to highlight C/C++ code (though sometimes there’s a disconnect between the editor highlighting and the language features

coughC++20 experimental features).Visual Studio Code provides syntax highlighting for Swift; there is no Linux-based XCode (yet!)

## Ron Olson

I mentioned this elsewhere, but in case you didn’t see it, you can use Visual Studio Code, Microsoft’s free editor, on Linux with Swift syntax highlighting. Because it has a built-in terminal, you can use the Swift REPL in the editor whilst writing Swift code; I do this all the time.

## Paul Dufresne

hum… tried:

import Glibc

at line 1 of swift, and it seems to generate a few errors.

## Ron Olson

This happens when the REPL can’t find its Linux headers; this isn’t unique to Fedora (I’ve seen it happen with the official Ubuntu versions as well) and the solution for me is to add:

alias swift=”swift -I /usr/lib/swift-lldb/swift/clang/include/”

in my shell configuration of choice (I use both bash and fish so in .bashrc or config.fish, respectively)

## Paul Dufresne

Works fine. Thanks!