Swift:在 Win10 上编程入门

时间:2024-04-06 11:49:55

访问 https://swift.org/download/
找到 Windows 10:x86_64
下载 swift-5.10-RELEASE-windows10.exe  大约490MB
建议安装在 D:\Swift\ ,安装后大约占2.56GB

官网文档:https://www.swift.org/documentation/

中文教程:The swift programming language 中文版

运行  cmd

swiftc -v
Swift version 5.10 (swift-5.10-RELEASE)
Target: x86_64-unknown-windows-msvc

cd D:\Swift\

mkdir test ; cd  test

用 Notepad++ 编写  hello.swift  如下

let a = 2
let b = 3
print("a+b=", a+b)

SET SDKROOT=D:\Swift\Platforms\5.10.0\Windows.platform\Developer\SDKs\Windows.sdk

可以在环境变量中设置,编译执行  swiftc hello.swift -o hello.exe -sdk %SDKROOT%

运行  hello.exe

编写  fibonacci.swift  如下

import Foundation

var i:Int = 0
if CommandLine.arguments.count > 1 {
    let str = CommandLine.arguments[1]
    let number = NumberFormatter().number(from: str)
    i = number!.intValue
} else {
    print(" usage: fibonacci.exe n ")
    exit(0)
}
// 计算 斐波那契数列(Fibonacci sequence)
func fib(n: Int) -> Int {
    if n <= 0 {
        return n
    }   
    var last:Int = 0, next:Int = 1
    for _ in 1..<n {
        (last, next) = (next, next + last)
     }
    return next
}
// 调用示例
print("fib(\(i))=", fib(n:i))

编写 compile.bat  如下

@echo off
SET SDKROOT=D:\Swift\Platforms\5.10.0\Windows.platform\Developer\SDKs\Windows.sdk
swiftc %1.swift -o %1.exe -sdk %SDKROOT%

编译执行  compile.bat  fibonacci

运行 fibonacci.exe 30

fib(30)= 832040

推荐阅读:Swift 编程入门(非常详细)从零基础入门到精通