将 Go 中的一些更有力的功能(如 channels、goroutines 和 defers)带到您的 iOS / Swift 项目中。
针对 Swift 2.0 构建 - 要支持 Swift 1.2,请使用 v0.1.4 或更早版本。
请注意,以下示例以及所有 examples
目录中的示例均来自 https://gobyexample.golang.ac.cn 和 Mark McGranaghan。
Go
package main
import "fmt"
func main() {
jobs := make(chan int, 5)
done := make(chan bool)
go func() {
for {
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()
for j := 1; j <= 3; j++ {
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("sent all jobs")
<-done
}
Swift
func main() {
var jobs = Chan<Int>(5)
var done = Chan<Bool>()
go {
for ;; {
var (j, more) = <?jobs
if more {
println("received job \(j!)")
} else {
println("received all jobs")
done <- true
return
}
}
}
for var j = 1; j <= 3; j++ {
jobs <- j
println("sent job \(j)")
}
close(jobs)
println("sent all jobs")
<-done
}
每个示例都有一个 .swift
和 .go
文件,其中包含相同的逻辑。
./run.sh examples/goroutines.swift
./run.sh examples/goroutines.go
将 GoSwift\go.swift
文件复制到您的项目。
手动安装时无需 import GoSwift
。
Josh Baker @tidwall
GoSwift 源代码在 MIT 许可证下。
examples
目录中的 Go 源代码版权属于 Mark McGranaghan,并按照 Creative Commons Attribution 3.0 Unported License 许可。
示例代码的 Swift 版本由 Josh Baker 提供