print("hello channel")
Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu
hello channel
let hoge = "hoge" dump(hoge)
Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu
- "hoge"
print("\n``"+"`\n\n@swiftbot#4647 \n``"+"`swift\nprint(\"hello\")\n
") ```Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu
@swiftbot#4647 print("hello")
```print("hoge\n``"+"`\n\n@swiftbot#4647 \n``"+"`swift\nprint(\"hello\")\n``"+"`")
Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu
hoge
@swiftbot#4647 print("hello")
```pre texts
@swiftbot
print("hello")
Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu
hello
print("hoge\n``"+"`\n\n<@4647> \n``"+"`swift\nprint(\"hello\")\n``"+"`")
Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu
hoge
@Unknown
print("hello")
```"+"
\n\n<@!swiftbot> \n`"+"
swift\nprint("hello")\n`"+"
")print("hoge\n``"+"`\n\n<@!swiftbot> \n``"+"`swift\nprint(\"hello\")\n``"+"`")
print("hoge\n``"+"`\n\n<@!swiftbot> \n``"+"`swift\nprint(\"hello\")\n``"+"`")
Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu
hoge
<@!swiftbot> print("hello")
```import Foundation
がなくても良いように見えるのが気になってたんですが、これは Fundation
が import
できることを示すためとかでしょうか?Foundation
の何かを使ってたらわかりやすいかもしれません。 round
とかの関数だと使いやすそうです。exec
へ渡している様に見えるのですが、大丈夫ですか? https://github.com/kishikawakatsumi/swift-playground/blob/master/sandbox.js#L56 (edited)Usage: @swiftbot [--version=SWIFT_VERSION] [--command={swift, swiftc}] [--options=SWIFTC_OPTIONS] ``` [Swift Code] ``` @swiftbot versions: show available Swift toolchain versions @swiftbot contribute: show repository URLs @swiftbot help: show help
Usage: @swiftbot [--version=SWIFT_VERSION] [--command={swift, swiftc}] [--options=SWIFTC_OPTIONS] ``` [Swift Code] ``` Examples: @swiftbot ``` print("Hello world!") ``` @swiftbot --version=4.0.3 ``` print("Hello world!") ``` @swiftbot --command=swiftc --options=-dump-parse ``` print("Hello world!") ``` Subcommands: @swiftbot versions: show available Swift toolchain versions @swiftbot contribute: show repository URLs @swiftbot help: show help
let 🐣 = "hiyoko" print("🐣 = \(🐣)")
Swift version 4.1 (swift-4.1-RELEASE)
🐣 = hiyoko
2018-04-04-a 2018-04-03-a 2018-04-02-a 2018-04-01-a 2018-03-31-a 4.1 4.0.3 3.1.1 3.0.2
--version=latest
と--version=stable
というのを使えるようにしました。latest
は最新のスナップショット、stable
は最新のリリースバージョンが動きます。 (edited)func fibonacci(number: Int) -> Int { if number <= 1 { return number } else { return fibonacci(number: number - 1) + fibonacci(number: number - 2) } } print(fibonacci(number: 10))
Swift version 4.2-dev (LLVM 0d52728a8a, Clang b9ad4239d1, Swift a1eb1fe24c)
55
import Foundation func exec(_ cmd: [String]) -> String { let process = Process() process.executableURL = URL(fileURLWithPath: cmd[0]) let pipe = Pipe() process.standardOutput = pipe process.arguments = Array(cmd[1...]) try! process.run() let handle = pipe.fileHandleForReading let data = handle.readDataToEndOfFile() let str = String(data: data, encoding: .utf8) ?? "<binary>" return str } print(exec(["/bin/ls", "-al"]))
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:5:5: error: value of type 'Process' has no member 'executableURL' process.executableURL = URL(fileURLWithPath: cmd[0]) ^~~~~~~ ~~~~~~~~~~~~~ /usercode/main.swift:10:10: error: value of type 'Process' has no member 'run' try! process.run() ^~~~~~~ ~~~
import Foundation func exec(_ cmd: [String]) -> String { let process = Process() process.launchPath = cmd[0] let pipe = Pipe() process.standardOutput = pipe process.arguments = Array(cmd[1...]) process.launch() let handle = pipe.fileHandleForReading let data = handle.readDataToEndOfFile() process.waitUntilExit() let str = String(data: data, encoding: .utf8) ?? "<binary>" return str } print(exec(["/bin/ls", "-al"]))
Swift version 4.1 (swift-4.1-RELEASE)
total 76 drwxr-xr-x 1 root root 4096 Apr 5 21:15 . drwxr-xr-x 1 root root 4096 Apr 5 21:15 .. -rwxr-xr-x 1 root root 0 Apr 5 21:15 .dockerenv drwxr-xr-x 1 root root 4096 Apr 1 12:25 bin drwxr-xr-x 2 root root 4096 Apr 12 2016 boot drwxr-xr-x 5 root root 340 Apr 5 21:15 dev drwxr-xr-x 1 root root 4096 Apr 5 21:15 etc drwxr-xr-x 2 root root 4096 Apr 12 2016 home drwxr-xr-x 1 root root 4096 Apr 1 12:26 lib drwxr-xr-x 2 root root 4096 Feb 28 19:14 lib64 drwxr-xr-x 2 root root 4096 Feb 28 19:13 media drwxr-xr-x 2 root root 4096 Feb 28 19:13 mnt drwxr-xr-x 2 root root 4096 Feb 28 19:13 opt dr-xr-xr-x 130 root root 0 Apr 5 21:15 proc drwx------ 2 root root 4096 Feb 28 19:14 root drwxr-xr-x 1 root root 4096 Feb 28 19:14 run drwxr-xr-x 1 root root 4096 Apr 1 12:25 sbin drwxr-xr-x 2 root root 4096 Feb 28 19:13 srv dr-xr-xr-x 13 root root 0 Apr 5 21:15 sys drwxrwxrwt 1 root root 4096 Apr 5 21:15 tmp drwxrwxrwx 2 1000 1000 4096 Apr 5 21:15 usercode drwxr-xr-x 1 root root 4096 Mar 29 21:57 usr drwxr-xr-x 1 root root 4096 Feb 28 19:14 var
import Foundation func exec(_ cmd: [String]) -> String { let process = Process() process.launchPath = cmd[0] let pipe = Pipe() process.standardOutput = pipe process.arguments = Array(cmd[1...]) process.launch() let handle = pipe.fileHandleForReading let data = handle.readDataToEndOfFile() process.waitUntilExit() let str = String(data: data, encoding: .utf8) ?? "<binary>" return str } print(exec(["/bin/cat", ".dockerenv"]))
Swift version 4.1 (swift-4.1-RELEASE)
import Foundation func exec(_ cmd: [String]) -> String { let process = Process() process.launchPath = cmd[0] let pipe = Pipe() process.standardOutput = pipe process.arguments = Array(cmd[1...]) process.launch() let handle = pipe.fileHandleForReading let data = handle.readDataToEndOfFile() process.waitUntilExit() let str = String(data: data, encoding: .utf8) ?? "<binary>" return str } print(exec(["/bin/ls", "-alR", "usercode"]))
Swift version 4.1 (swift-4.1-RELEASE)
usercode: total 20 drwxrwxrwx 2 1000 1000 4096 Apr 5 21:16 . drwxr-xr-x 1 root root 4096 Apr 5 21:16 .. -rw-r--r-- 1 root root 0 Apr 5 21:16 errors -rw-r--r-- 1 root root 0 Apr 5 21:16 log -rw-rw-r-- 1 1000 1000 483 Apr 5 21:16 main.swift -rwxrwxr-x 1 1000 1000 164 Apr 5 21:16 script.sh -rw-r--r-- 1 root root 71 Apr 5 21:16 version
import Foundation func exec(_ cmd: [String]) -> String { let process = Process() process.launchPath = cmd[0] let pipe = Pipe() process.standardOutput = pipe process.arguments = Array(cmd[1...]) process.launch() let handle = pipe.fileHandleForReading let data = handle.readDataToEndOfFile() process.waitUntilExit() let str = String(data: data, encoding: .utf8) ?? "<binary>" return str } print(exec(["/bin/cat", "usercode/script.sh"]))
Swift version 4.1 (swift-4.1-RELEASE)
#!/bin/bash swift --version > /usercode/version exec 1> "/usercode/log" exec 2> "/usercode/errors" $@ /usercode/main.swift mv /usercode/log /usercode/completed
import Foundation let semaphore = DispatchSemaphore(value: 0) let url = URL(string: "http://httpbin.org/get")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in defer{ semaphore.signal() } if let error = error { print(error) return } print(response!.url!) print(String(data: data!, encoding: .utf8)!) }; task.resume() semaphore.wait()
Swift version 4.1 (swift-4.1-RELEASE)
http://httpbin.org/get { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "deflate, gzip", "Accept-Language": "en", "Connection": "close", "Host": "httpbin.org", "User-Agent": "swift (unknown version) curl/7.47.0" }, "origin": "138.68.23.220", "url": "http://httpbin.org/get" }
print(“hello iPad”)
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:1:20: error: unicode curly quote found, replace with '"' print(“hello iPad”) /usercode/main.swift:1:7: error: unicode curly quote found, replace with '"' print(“hello iPad”)
print("hello from iPad")
Swift version 4.1 (swift-4.1-RELEASE)
hello from iPad
if true { print("hello") }
Swift version 4.1 (swift-4.1-RELEASE)
if true { print("hello") }
import Foundation let semaphore = DispatchSemaphore(value: 0) let url = URL(string: "http://httpbin.org/get")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in defer{ semaphore.signal() } if let error = error { print(error) return } print(response!.url!) print(String(data: data!, encoding: .utf8)!) }; task.resume() semaphore.wait()
Swift version 4.1 (swift-4.1-RELEASE)
URLError(_nsError: Could not resolve host: httpbin.org)
import SwiftyMath
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:1:8: error: no such module 'SwiftyMath' import SwiftyMath ^
import SwiftyMath typealias F5 = IntegerQuotientRing<_5> F5.printAddTable() F5.printMulTable()
Swift version 4.1 (swift-4.1-RELEASE)
+ | 0 1 2 3 4 -------------------------- 0 | 0 1 2 3 4 1 | 1 2 3 4 0 2 | 2 3 4 0 1 3 | 3 4 0 1 2 4 | 4 0 1 2 3 * | 0 1 2 3 4 -------------------------- 0 | 0 0 0 0 0 1 | 0 1 2 3 4 2 | 0 2 4 1 3 3 | 0 3 1 4 2 4 | 0 4 3 2 1
import SwiftyTopology
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:1:8: error: no such module 'SwiftyTopology' import SwiftyTopology ^
import SwiftyMath let a = 𝐐(4, 5) // 4/5 let b = 𝐐(3, 2) // 3/2 print(a + b) // 23/10
Swift version 4.1 (swift-4.1-RELEASE)
23/10
import SwiftyMath import SwiftyTopology let S = SimplicialComplex.sphere(dim:3) print(S.detailDescription)
Swift version 4.1 (swift-4.1-RELEASE)
S^3 { 0: v₁, v₂, v₃, v₄, v₀ 1: (v₁, v₂), (v₁, v₃), (v₂, v₃), (v₁, v₄), (v₂, v₄), (v₃, v₄), (v₀, v₂), (v₀, v₃), (v₀, v₄), (v₀, v₁) 2: (v₁, v₂, v₃), (v₁, v₂, v₄), (v₁, v₃, v₄), (v₂, v₃, v₄), (v₀, v₂, v₃), (v₀, v₂, v₄), (v₀, v₃, v₄), (v₀, v₁, v₃), (v₀, v₁, v₄), (v₀, v₁, v₂) 3: (v₁, v₂, v₃, v₄), (v₀, v₂, v₃, v₄), (v₀, v₁, v₃, v₄), (v₀, v₁, v₂, v₄), (v₀, v₁, v₂, v₃) }
import SwiftyMath import SwiftyTopology let S = SimplicialComplex.sphere(dim:3) let H = Homology(S, Int.self) print(H.detailDescription)
Swift version 4.1 (swift-4.1-RELEASE)
H(S^3; 𝐙) = { 0 : 𝐙, [v₄], 1 : 0, [], 2 : 0, [], 3 : 𝐙, [-1(v₀, v₁, v₃, v₄) + -1(v₁, v₂, v₃, v₄) + (v₀, v₁, v₂, v₄) + -1(v₀, v₁, v₂, v₃) + (v₀, v₂, v₃, v₄)] }
import SwiftyMath import SwiftyTopology let S = SimplicialComplex.sphere(dim:3) let H = Homology(S, Int.self) print(H.detailDescription)
Swift version 4.1 (swift-4.1-RELEASE)
H(S^3; 𝐙) = { 0 : 𝐙, [v₄], 1 : 0, [], 2 : 0, [], 3 : 𝐙, [-1(v₁, v₂, v₃, v₄) + -1(v₀, v₁, v₃, v₄) + (v₀, v₁, v₂, v₄) + (v₀, v₂, v₃, v₄) + -1(v₀, v₁, v₂, v₃)] }
'rand()' is unavailable in Swift: Use arc4random
ってでますね…(それで arc4random
にしたんでした) (edited)DESCRIPTION These functions use a cryptographic pseudo-random number generator to generate high quality random bytes very quickly.
drand48()
は使えた。これなら Ubuntu でもビルドできるんですかね?print(drand48())
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:1:7: error: use of unresolved identifier 'drand48' print(drand48()) ^~~~~~~
import Foundation print(drand48())
Swift version 4.1 (swift-4.1-RELEASE)
3.90798504668055e-14
import Glibc print(drand48())
Swift version 4.1 (swift-4.1-RELEASE)
3.90798504668055e-14
HISTORY The original version of this random number generator used the RC4 (also known as ARC4) algorithm. In OS X 10.12 it was replaced with the NIST-approved AES cipher, and it may be replaced again in the future as cryptographic techniques advance. A good mnemonic is ``A Replacement Call for Random''.
訳すと RC4(ARC4とも言う)アルゴリズムの実装だけど OS10.12で AESに変わったし、後にまた変わるから、 A Replacement Call For Random の略として覚えると良いよ (edited)import Foundation srand48(time(nil)) print(drand48())
Swift version 4.1 (swift-4.1-RELEASE)
0.918770220204355
import Foundation srand48(time(nil)) print(drand48())
Swift version 4.1 (swift-4.1-RELEASE)
0.272781763532297
private var randInit = false private func rand() -> Double { if !randInit { srand48(time(nil)) randInit = true } return drand48() }
extension Never: ExpressibleByNilLiteral { public init(nilLiteral: ()) { self = unsafeBitCast((), to: Never.self) } } let a: Never = nil print(a)
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:9:7: warning: will never be executed print(a) ^ /usercode/main.swift:7:16: note: a call to a never-returning function let a: Never = nil ^ /usercode/main.swift:2:12: warning: will never be executed public init(nilLiteral: ()) { ^ /usercode/main.swift:2:12: note: a call to a never-returning function public init(nilLiteral: ()) { ^ Segmentation fault (core dumped)
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT) * frame #0: 0x00007fffaba7aa9b libobjc.A.dylib`_objc_msgSend_uncached + 11 frame #1: 0x00007fff9865d231 Foundation`-[NSPlaceholderString initWithString:] + 107 frame #2: 0x00000001036ca007 PlaygroundLogger`function signature specialization <Arg[0] = Dead> of static PlaygroundLogger.LoggingPolicyStack.get() -> PlaygroundLogger.LoggingPolicyStack + 151 frame #3: 0x00000001036c3f22 PlaygroundLogger`function signature specialization <Arg[1] = Owned To Guaranteed and Exploded> of playground_log_hidden + 98 frame #4: 0x00000001036c365b PlaygroundLogger`playground_log_hidden + 27 frame #5: 0x00000001041db0a7 $__lldb_expr158`Never.init(nilLiteral=() @ scalar) at MyPlayground.playground:4
extension Never: ExpressibleByNilLiteral { public init(nilLiteral: ()) { self = unsafeBitCast((), to: Never.self) print("わいわい") } } let a: Never = nil print(a)
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:10:7: warning: will never be executed print(a) ^ /usercode/main.swift:8:16: note: a call to a never-returning function let a: Never = nil ^ /usercode/main.swift:2:12: warning: will never be executed public init(nilLiteral: ()) { ^ /usercode/main.swift:2:12: note: a call to a never-returning function public init(nilLiteral: ()) { ^ /usr/bin/swift[0x3f24d54] /usr/bin/swift[0x3f25096] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fa0085a4390] /usr/lib/swift/linux/libswiftCore.so(swift_conformsToProtocol+0x30)[0x7fa004780730] /usr/lib/swift/linux/libswiftCore.so(+0x39c05f)[0x7fa00477205f] /usr/lib/swift/linux/libswiftCore.so(+0x39b82d)[0x7fa00477182d] /usr/lib/swift/linux/libswiftCore.so(+0x2e518a)[0x7fa0046bb18a] Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret /usercode/main.swift -disable-objc-interop -I /usr/lib/swift/clang/include/ -I /vendor/SwiftyMath/.build/release/ -I /vendor/swift-package-libbsd/ -module-name main -ldSwiftyMath Segmentation fault (core dumped)
わいわい Playground execution failed: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT). The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation. * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT) * frame #0: 0x00007fffaba7c64e libobjc.A.dylib`_object_remove_assocations + 24 frame #1: 0x00007fffaba7c603 libobjc.A.dylib`objc_destructInstance + 105 frame #2: 0x000000011048e398 libswiftCore.dylib`swift_deallocClassInstance + 24 frame #3: 0x000000011048e2f0 libswiftCore.dylib`_swift_release_dealloc + 16 frame #4: 0x000000010e437012 PlaygroundLogger`function signature specialization <Arg[0] = Dead> of static PlaygroundLogger.LoggingPolicyStack.get() -> PlaygroundLogger.LoggingPolicyStack + 162 frame #5: 0x000000010e430f22 PlaygroundLogger`function signature specialization <Arg[1] = Owned To Guaranteed and Exploded> of playground_log_hidden + 98 frame #6: 0x000000010e43065b PlaygroundLogger`playground_log_hidden + 27 frame #7: 0x000000010e4680af $__lldb_expr160`Never.init(nilLiteral=() @ scalar) at MyPlayground.playground:4
var foo: Foo { return x }
と func foo() -> Foo { return x }
の扱いが、前者はフィールドとして定義されているのでunsafeBitCastしても同じものが呼ばれるが、後者は実質的には第一引数にselfを与えるstatic funcなのでunsafeBitCastで違うものが呼ばれる、とか。var foo: Foo { return x }
じゃなくて let foo: Foo = x
だった。struct Cat { let face: String = "😺" func bark() -> String { return "にゃーん" } } struct Dog { let face: String = "🐶" func bark() -> String { return "わんわん" } } let cat = unsafeBitCast(Dog(), to: Cat.self) print(cat.face) print(cat.bark())
Swift version 4.1 (swift-4.1-RELEASE)
🐶 にゃーん
struct Cat { let face: String = "😺" func bark() -> String { return "\(face): にゃーん" } } struct Dog { let face: String = "🐶" func bark() -> String { return "\(face): わんわん" } } let cat = unsafeBitCast(Dog(), to: Cat.self) print(cat.face) print(cat.bark())
Swift version 4.1 (swift-4.1-RELEASE)
🐶 🐶: にゃーん
struct Cat { let face: String = "😺" func bark() -> String { return "\(face): にゃーん" } } struct Dog { let face: String = "🐶" func bark() -> String { return "\(face): わんわん" } } let cat = unsafeBitCast(Dog(), to: Cat.self) print(cat.bark())
Swift version 4.1 (swift-4.1-RELEASE)
🐶: にゃーん
cat.
の型に関係なく固定でcat用のメソッドが呼ばれてますね (edited)struct One { let one = 1 } struct OneTwoThree { let one = 1 let two = 2 let three = 3 } print(MemoryLayout.size(ofValue: One())) print(MemoryLayout.size(ofValue: OneTwoThree()))
Swift version 4.1 (swift-4.1-RELEASE)
8 24
struct Cat { let age: Int = 3 init() { self.age = 5 } } print(Cat())
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:5:18: error: immutable value 'self.age' may only be initialized once self.age = 5 ^ /usercode/main.swift:2:9: note: initial value already provided in 'let' declaration let age: Int = 3 ^ /usercode/main.swift:2:5: note: change 'let' to 'var' to make it mutable let age: Int = 3 ^~~ var
docker-compose
使ってローカルのDockerで岸川さんのswift-playgroundを実行できる様になった。docker-compose.yml
version: '3' services: playground: build: . environment: HOST_PWD: ${PWD} ports: - "80:8080" volumes: - /var/run/docker.sock:/var/run/docker.sock - .:/playground command: ["sh", "-c", "npm install && npm start"]
Dockerfile
FROM docker:latest RUN apk --update add bash nodejs && rm -rf /var/cache/apk/* WORKDIR /playground
HOST_PWD
にホストのディレクトリを持たせ、それをsandboxに渡してます。run.sh
の起動は/playground/run.sh 30 -v /Users/norio/github/swift-playground/temp/6e4fd5db976425e7d17a:/usercode -v /playground/vendor:/vendor:ro norionomura/swiftlint:swift-4.1 sh /usercode/script.sh swift
な感じに。docker:dind
にすればホストのパスは要らないけど、docker:dind
だとホストの/var/lib/docker/volumes
にデータが溜まっていくらしく、それを避けたかった。HOST_PWD
の自動取得くらいにしかdocker-compose
を活かせてないですね。options
がexec
へ文字列結合されて渡されてるところが心配。options="; docker run -v /:/host_root ubuntu cat /host_root/etc/passwd;"
とかすると、そのまま実行されてしまわないかな?docker pull norionomura/swiftlint:swift-4.1 # 利用するswiftイメージをあらかじめpull git clone https://github.com/norio-nomura/swift-playground.git -b docker-compose cd swift-playground docker-compose up
してブラウザで http://localhost を開く。func hoge() -> Never { return unsafeBitCast((), to: Never.self) } let voidNever = unsafeBitCast((), to: Never.self) // ① guard 1 == 0 else { hoge() } print("hello")
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:11:7: warning: will never be executed print("hello") ^ /usercode/main.swift:7:7: note: condition always evaluates to false guard 1 == 0 else { ^ Fatal error: Can't unsafeBitCast between types of different sizes Current stack trace: 0 libswiftCore.so 0x00007fcacbd63750 _swift_stdlib_reportFatalError + 171 1 libswiftCore.so 0x00007fcacbad1ad6 <unavailable> + 1366742 2 libswiftCore.so 0x00007fcacbd0c383 <unavailable> + 3703683 3 libswiftCore.so 0x00007fcacbad1ad6 <unavailable> + 1366742 4 libswiftCore.so 0x00007fcacbc3dd80 <unavailable> + 2858368 5 libswiftCore.so 0x00007fcacbad16b0 _fatalErrorMessage(_:_:file:line:flags:) + 19 7 swift 0x0000000000fed1ce <unavailable> + 12505550 8 swift 0x0000000000ff1692 <unavailable> + 12523154 9 swift 0x00000000004d9076 <unavailable> + 888950 10 swift 0x00000000004c35d3 <unavailable> + 800211 11 swift 0x00000000004beecc <unavailable> + 782028 12 swift 0x00000000004778c4 <unavailable> + 489668 13 libc.so.6 0x00007fcace27c740 __libc_start_main + 240 14 swift 0x0000000000475179 <unavailable> + 479609 /usr/bin/swift[0x3f24d54] /usr/bin/swift[0x3f25096] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fcacfb52390] /usr/lib/swift/linux/libswiftCore.so(+0x2b9d80)[0x7fcacbc3dd80] /usr/lib/swift/linux/libswiftCore.so(_T0s18_fatalErrorMessages5NeverOs12StaticStringV_A2E4fileSu4lines6UInt32V5flagstF+0x13)[0x7fcacbad16c3] [0x7fcacff820ec] /usr/bin/swift[0xfed1ce] /usr/bin/swift[0xff1692] /usr/bin/swift[0x4d9076] /usr/bin/swift[0x4c35d3] /usr/bin/swift[0x4beecc] /usr/bin/swift[0x4778c4] ...
func hoge() -> Never { return unsafeBitCast((), to: Never.self) } let voidNever = unsafeBitCast((), to: Never.self) // ① //guard 1 == 0 else { // hoge() //} print("hello")
Swift version 4.1 (swift-4.1-RELEASE)
hello
func hoge() -> Never { return unsafeBitCast((), to: Never.self) } let voidNever = unsafeBitCast((), to: Never.self) // ① hoge() print("hello")
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:9:7: warning: will never be executed print("hello") ^ /usercode/main.swift:7:1: note: a call to a never-returning function hoge() ^ Fatal error: Can't unsafeBitCast between types of different sizes Current stack trace: 0 libswiftCore.so 0x00007fc5595c8750 _swift_stdlib_reportFatalError + 171 1 libswiftCore.so 0x00007fc559336ad6 <unavailable> + 1366742 2 libswiftCore.so 0x00007fc559571383 <unavailable> + 3703683 3 libswiftCore.so 0x00007fc559336ad6 <unavailable> + 1366742 4 libswiftCore.so 0x00007fc5594a2d80 <unavailable> + 2858368 5 libswiftCore.so 0x00007fc5593366b0 _fatalErrorMessage(_:_:file:line:flags:) + 19 7 swift 0x0000000000fed1ce <unavailable> + 12505550 8 swift 0x0000000000ff1692 <unavailable> + 12523154 9 swift 0x00000000004d9076 <unavailable> + 888950 10 swift 0x00000000004c35d3 <unavailable> + 800211 11 swift 0x00000000004beecc <unavailable> + 782028 12 swift 0x00000000004778c4 <unavailable> + 489668 13 libc.so.6 0x00007fc55bae1740 __libc_start_main + 240 14 swift 0x0000000000475179 <unavailable> + 479609 /usr/bin/swift[0x3f24d54] /usr/bin/swift[0x3f25096] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fc55d3b7390] /usr/lib/swift/linux/libswiftCore.so(+0x2b9d80)[0x7fc5594a2d80] /usr/lib/swift/linux/libswiftCore.so(_T0s18_fatalErrorMessages5NeverOs12StaticStringV_A2E4fileSu4lines6UInt32V5flagstF+0x13)[0x7fc5593366c3] [0x7fc55d7e708c] /usr/bin/swift[0xfed1ce] /usr/bin/swift[0xff1692] /usr/bin/swift[0x4d9076] /usr/bin/swift[0x4c35d3] /usr/bin/swift[0x4beecc] /usr/bin/swift[0x4778c4] ...
let voidNever = unsafeBitCast((), to: Never.self) // ① print("hello")
Swift version 4.1 (swift-4.1-RELEASE)
hello
func f() { let voidNever = unsafeBitCast((), to: Never.self) // ① print("hello") } f()
Swift version 4.1 (swift-4.1-RELEASE)
hello
/usercode/main.swift:2:5: warning: initialization of immutable value 'voidNever' was never used; consider replacing with assignment to '_' or removing it let voidNever = unsafeBitCast((), to: Never.self) // ①
Usage: @swiftbot [--version=SWIFT_VERSION] [--command={swift, swiftc}] [--options=SWIFTC_OPTIONS] ``` [Swift Code] ``` Examples: @swiftbot ``` print("Hello world!") ``` @swiftbot --version=4.0.3 ``` print("Hello world!") ``` @swiftbot --command=swiftc --options=-dump-parse ``` print("Hello world!") ``` Subcommands: @swiftbot versions: show available Swift toolchain versions @swiftbot contribute: show repository URLs @swiftbot help: show help
func hoge() -> Never { return unsafeBitCast((), to: Never.self) // 落ちるならこっちじゃないの } _ = unsafeBitCast((), to: Never.self) // ここで落ちる hoge()
Swift version 4.1 (swift-4.1-RELEASE)
Fatal error: Can't unsafeBitCast between types of different sizes Current stack trace: 0 libswiftCore.so 0x00007f380f961750 _swift_stdlib_reportFatalError + 171 1 libswiftCore.so 0x00007f380f6cfad6 <unavailable> + 1366742 2 libswiftCore.so 0x00007f380f90a383 <unavailable> + 3703683 3 libswiftCore.so 0x00007f380f6cfad6 <unavailable> + 1366742 4 libswiftCore.so 0x00007f380f83bd80 <unavailable> + 2858368 5 libswiftCore.so 0x00007f380f6cf6b0 _fatalErrorMessage(_:_:file:line:flags:) + 19 7 swift 0x0000000000fed1ce <unavailable> + 12505550 8 swift 0x0000000000ff1692 <unavailable> + 12523154 9 swift 0x00000000004d9076 <unavailable> + 888950 10 swift 0x00000000004c35d3 <unavailable> + 800211 11 swift 0x00000000004beecc <unavailable> + 782028 12 swift 0x00000000004778c4 <unavailable> + 489668 13 libc.so.6 0x00007f3811e7a740 __libc_start_main + 240 14 swift 0x0000000000475179 <unavailable> + 479609 /usr/bin/swift[0x3f24d54] /usr/bin/swift[0x3f25096] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f3813750390] /usr/lib/swift/linux/libswiftCore.so(+0x2b9d80)[0x7f380f83bd80] /usr/lib/swift/linux/libswiftCore.so(_T0s18_fatalErrorMessages5NeverOs12StaticStringV_A2E4fileSu4lines6UInt32V5flagstF+0x13)[0x7f380f6cf6c3] [0x7f3813b80080] /usr/bin/swift[0xfed1ce] /usr/bin/swift[0xff1692] /usr/bin/swift[0x4d9076] /usr/bin/swift[0x4c35d3] /usr/bin/swift[0x4beecc] /usr/bin/swift[0x4778c4] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f3811e7a830] /usr/bin/swift[0x475179] Stack dump: ...
let voidNever = unsafeBitCast((), to: Never.self) // ① print("hello")
(edited)Swift version 4.1 (swift-4.1-RELEASE)
<unknown>:0: error: option '-emit-silgen' is not supported by 'swift'; did you mean to use 'swiftc'?
func hoge() -> Never { print(3) return unsafeBitCast((), to: Never.self) // 落ちるならこっちじゃないの } print(1) _ = unsafeBitCast((), to: Never.self) // ここで落ちる print(2) hoge() print(4)
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:10:7: warning: will never be executed print(4) ^ /usercode/main.swift:9:1: note: a call to a never-returning function hoge() ^ Fatal error: Can't unsafeBitCast between types of different sizes Current stack trace: 0 libswiftCore.so 0x00007fecfce05750 _swift_stdlib_reportFatalError + 171 1 libswiftCore.so 0x00007fecfcb73ad6 <unavailable> + 1366742 2 libswiftCore.so 0x00007fecfcdae383 <unavailable> + 3703683 3 libswiftCore.so 0x00007fecfcb73ad6 <unavailable> + 1366742 4 libswiftCore.so 0x00007fecfccdfd80 <unavailable> + 2858368 5 libswiftCore.so 0x00007fecfcb736b0 _fatalErrorMessage(_:_:file:line:flags:) + 19 7 swift 0x0000000000fed1ce <unavailable> + 12505550 8 swift 0x0000000000ff1692 <unavailable> + 12523154 9 swift 0x00000000004d9076 <unavailable> + 888950 10 swift 0x00000000004c35d3 <unavailable> + 800211 11 swift 0x00000000004beecc <unavailable> + 782028 12 swift 0x00000000004778c4 <unavailable> + 489668 13 libc.so.6 0x00007fecff31e740 __libc_start_main + 240 14 swift 0x0000000000475179 <unavailable> + 479609 /usr/bin/swift[0x3f24d54] /usr/bin/swift[0x3f25096] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fed00bf4390] /usr/lib/swift/linux/libswiftCore.so(+0x2b9d80)[0x7fecfccdfd80] /usr/lib/swift/linux/libswiftCore.so(_T0s18_fatalErrorMessages5NeverOs12StaticStringV_A2E4fileSu4lines6UInt32V5flagstF+0x13)[0x7fecfcb736c3] [0x7fed010241ae] /usr/bin/swift[0xfed1ce] /usr/bin/swift[0xff1692] /usr/bin/swift[0x4d9076] /usr/bin/swift[0x4c35d3] /usr/bin/swift[0x4beecc] /usr/bin/swift[0x4778c4] ...
let voidNever = unsafeBitCast((), to: Never.self) // ① print("hello")
Swift version 4.1 (swift-4.1-RELEASE)
sil_stage raw import Builtin import Swift import SwiftShims // voidNever sil_global hidden [let] @_T04main9voidNevers0C0Ovp : $Never // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): alloc_global @_T04main9voidNevers0C0Ovp // id: %2 %3 = global_addr @_T04main9voidNevers0C0Ovp : $*Never // user: %10 %4 = tuple () // user: %6 %5 = alloc_stack $() // users: %11, %10, %6 store %4 to [trivial] %5 : $*() // id: %6 %7 = metatype $@thin Never.Type %8 = metatype $@thick Never.Type // user: %10 // function_ref unsafeBitCast<A, B>(_:to:) %9 = function_ref @_T0s13unsafeBitCastq_x_q_m2totr0_lF : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @thick τ_0_1.Type) -> @out τ_0_1 // user: %10 %10 = apply %9<(), Never>(%3, %5, %8) : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @thick τ_0_1.Type) -> @out τ_0_1 dealloc_stack %5 : $*() // id: %11 %12 = integer_literal $Builtin.Word, 1 // user: %14 // function_ref _allocateUninitializedArray<A>(_:) %13 = function_ref @_T0s27_allocateUninitializedArraySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %14 %14 = apply %13<Any>(%12) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // users: %20, %19, %15 %15 = begin_borrow %14 : $(Array<Any>, Builtin.RawPointer) // users: %19, %18, %16 %16 = tuple_extract %15 : $(Array<Any>, Builtin.RawPointer), 0 // user: %17 %17 = copy_value %16 : $Array<Any> // user: %35 %18 = tuple_extract %15 : $(Array<Any>, Builtin.RawPointer), 1 // user: %21 ...
func hoge() -> Never { return unsafeBitCast((), to: Never.self) } let voidNever = unsafeBitCast((), to: Never.self) // ① hoge() print("hello")
Swift version 4.1 (swift-4.1-RELEASE)
<unknown>:0: error: unknown argument: '--emit-silgen'
func hoge() -> Never { return unsafeBitCast((), to: Never.self) } let voidNever = unsafeBitCast((), to: Never.self) // ① hoge() print("hello")
Swift version 4.1 (swift-4.1-RELEASE)
sil_stage raw import Builtin import Swift import SwiftShims // voidNever sil_global hidden [let] @_T04main9voidNevers0C0Ovp : $Never // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): alloc_global @_T04main9voidNevers0C0Ovp // id: %2 %3 = global_addr @_T04main9voidNevers0C0Ovp : $*Never // user: %10 %4 = tuple () // user: %6 %5 = alloc_stack $() // users: %11, %10, %6 store %4 to [trivial] %5 : $*() // id: %6 %7 = metatype $@thin Never.Type %8 = metatype $@thick Never.Type // user: %10 // function_ref unsafeBitCast<A, B>(_:to:) %9 = function_ref @_T0s13unsafeBitCastq_x_q_m2totr0_lF : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @thick τ_0_1.Type) -> @out τ_0_1 // user: %10 %10 = apply %9<(), Never>(%3, %5, %8) : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0, @thick τ_0_1.Type) -> @out τ_0_1 dealloc_stack %5 : $*() // id: %11 // function_ref hoge() %12 = function_ref @_T04main4hoges5NeverOyF : $@convention(thin) () -> Never // user: %13 %13 = apply %12() : $@convention(thin) () -> Never %14 = integer_literal $Builtin.Word, 1 // user: %16 // function_ref _allocateUninitializedArray<A>(_:) %15 = function_ref @_T0s27_allocateUninitializedArraySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %16 %16 = apply %15<Any>(%14) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // users: %22, %21, %17 %17 = begin_borrow %16 : $(Array<Any>, Builtin.RawPointer) // users: %21, %20, %18 %18 = tuple_extract %17 : $(Array<Any>, Builtin.RawPointer), 0 // user: %19 ...
print(MemoryLayout<()>.size) print(MemoryLayout<Never>.size)
Swift version 4.1 (swift-4.1-RELEASE)
0 0
enum Fruit { case apple } print(MemoryLayout<Fruit>.size)
Swift version 4.1 (swift-4.1-RELEASE)
0
func a() { func b(_ a: Int) {} func b(_ a: String) {} }
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:3:8: error: definition conflicts with previous value func b(_ a: String) {} ^ /usercode/main.swift:2:8: note: previous definition of 'b' is here func b(_ a: Int) {} ^
print("a")
execFile
でshell
オプションを使わないならサニタイズ不要にも思えます。 https://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callbackprotocol Widget { func print() func clone() -> Self } extension Widget { func print() { Swift.print("a widget of type \(Self.self)") } func clone() -> Self { return self } } class Box<Element> : Widget { init(value: Element) { self.contents = value } let contents: Element // Default implementation of print() is OK! // You must define this, or conformance checking fails on Swift 4.0.x: // func clone() -> Self { return self } } class Crate<T> : Box<T> { override init(value: T) { super.init(value: value) } } let c = Crate<Int>(value: 3) c.print() // prints: a widget of type Crate<Int>
Swift version 4.0.3 (swift-4.0.3-RELEASE)
/usercode/main.swift:8:10: error: method 'clone()' in non-final class 'Box<Element>' must return `Self` to conform to protocol 'Widget' func clone() -> Self { return self } ^
protocol Widget { func print() func clone() -> Self } extension Widget { func print() { Swift.print("a widget of type \(Self.self)") } func clone() -> Self { return self } } class Box<Element> : Widget { init(value: Element) { self.contents = value } let contents: Element // Default implementation of print() is OK! // You must define this, or conformance checking fails on Swift 4.0.x: // func clone() -> Self { return self } } class Crate<T> : Box<T> { override init(value: T) { super.init(value: value) } } let c = Crate<Int>(value: 3) c.print() // prints: a widget of type Crate<Int>
Swift version 4.1 (swift-4.1-RELEASE)
a widget of type Crate<Int>
--version=stable...latest
や--version=3...4.1
のように書けたらいいのかな?...
だとその間のバージョンで対応してるもの全部って感じですか?カンマ区切りで明示的な配列指定を想像していましたけど--version="4.0.3, 4.1, latest"
こんな感じかな。 (edited)stable...latest
で上のように展開されるという思い込みと、カンマだとおそらくクオートで囲む必要がありそうで、それを避けたかった感じ。--version=4.0.3,4.1,latest
みたいにスペースなくしても "
っていりますっけ? (edited)--version=4.0.3,4.1
これがいけるとちょっと入力しやすくて嬉しいです[omochi@omochi-iMac-PC43 temp]$ cat a.bash for arg in "$@"; do echo "[$arg]" done [omochi@omochi-iMac-PC43 temp]$ ./a.bash --version=4.0.3,4.1 [--version=4.0.3,4.1]
--x
なのもこのライブラリのデフォルトによります。 https://github.com/kishikawakatsumi/swift-compiler-discord-bot/blob/master/app.js#L87execFile
を使っても、run.sh
の中でどう解釈されるか、によるかも。>サニタイズ要・不要docker run
コマンドの実行をオプションに渡す文字列で止めて、かつそのあとに任意の処理が実行できるんじゃないなということですよね。たぶんできたんじゃないかな。run.sh
とは別のプロセスが起動できそうだと思ったのです。>exec
使用 (edited)script.sh
を実行した上で別途test
ってファイルを作れます。 const exec = require('child_process').exec; const options = "& echo hello>test"; exec(['sh', 'script.sh', [options].join(' ')].join(' '));
join
でつなぐやり方はsandbox.js
で使われてるのと同じ。docker
に入れたnode
で実行しようと考えたきっかけです。execFile
を使えばサニタイズ無くても大丈夫かも? → しかしrun.sh
の中での扱いは大丈夫? といった流れ。 (edited)print("hello, discord!")
Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu hello, discord!
swift package generate-xcodeproj
すればXcodeでデバッグできるのがSwiftで書くメリットかな。protocol Widget { func print() func clone() -> Self } extension Widget { func print() { Swift.print("a widget of type \(Self.self)") } func clone() -> Self { return self } } class Box<Element> : Widget { init(value: Element) { self.contents = value } let contents: Element // Default implementation of print() is OK! // You must define this, or conformance checking fails on Swift 4.0.x: // func clone() -> Self { return self } } class Crate<T> : Box<T> { override init(value: T) { super.init(value: value) } } let c = Crate<Int>(value: 3) c.print() // prints: a widget of type Crate<Int>
main.swift:8:10: error: method 'clone()' in non-final class 'Box<Element>' must return `Self` to conform to protocol 'Widget' func clone() -> Self { return self } ^
a widget of type Crate<Int>
enum CustomString: ExpressibleByStringLiteral { typealias StringLiteralType = String init(stringLiteral value: StringLiteralType) { self = "hoge" } } let hoge: CustomString = "fuga" print(hoge)
Swift version 4.1 (swift-4.1-RELEASE)
/usercode/main.swift:8:26: warning: will never be executed let hoge: CustomString = "fuga" ^ /usercode/main.swift:8:26: note: a call to a never-returning function let hoge: CustomString = "fuga" ^ /usercode/main.swift:4:14: warning: will never be executed self = "hoge" ^ /usercode/main.swift:4:16: note: a call to a never-returning function self = "hoge" ^ /usercode/main.swift:3:5: warning: will never be executed init(stringLiteral value: StringLiteralType) { ^ /usercode/main.swift:3:5: note: a call to a never-returning function init(stringLiteral value: StringLiteralType) { ^ /usr/bin/swift[0x3f24d54] /usr/bin/swift[0x3f25096] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f8003430390] /usr/lib/swift/linux/libswiftCore.so(_T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC+0x4)[0x7f7fff39e424] [0x7f800385f0e4] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] [0x7f800385f0fa] ...
self = "hoge"
がinit(stringLiteral:)
を再起呼び出ししてますね。contents
の最大サイズか。enum CustomString: ExpressibleByStringLiteral { typealias StringLiteralType = String init(stringLiteral value: StringLiteralType) { self = "hoge" } } let hoge: CustomString = "fuga" print(hoge)
main.swift:8:26: warning: will never be executed let hoge: CustomString = "fuga" ^ main.swift:8:26: note: a call to a never-returning function let hoge: CustomString = "fuga" ^ main.swift:4:14: warning: will never be executed self = "hoge" ^ main.swift:4:16: note: a call to a never-returning function self = "hoge" ^ main.swift:3:5: warning: will never be executed init(stringLiteral value: StringLiteralType) { ^ main.swift:3:5: note: a call to a never-returning function init(stringLiteral value: StringLiteralType) { ^ 0 swift 0x0000000003ae91b8 1 swift 0x0000000003ae98f6 2 libpthread.so.0 0x00007f6a35029390 3 libpthread.so.0 0x00007f6a35458058 4 libpthread.so.0 0x00007f6a3545809a 5 libpthread.so.0 0x00007f6a3545809a 6 libpthread.so.0 0x00007f6a3545809a 7 libpthread.so.0 0x00007f6a3545809a 8 libpthread.so.0 0x00007f6a3545809a 9 libpthread.so.0 0x00007f6a3545809a 10 libpthread.so.0 0x00007f6a3545809a 11 libpthread.so.0 0x00007f6a3545809a 12 libpthread.so.0 0x00007f6a3545809a 13 libpthread.so.0 0x00007f6a3545809a 14 libpthread.so.0 0x00007f6a3545809a 15 libpthread.so.0 0x00007f6a3545809a 16 libpthread.so.0 0x00007f6a3545809a 17 libpthread.so.0 0x00007f6a3545809a 18 libpthread.so.0 0x00007f6a3545809a 19 libpthread.so.0 0x00007f6a3545809a 20 libpthread.so.0 0x00007f6a3545809a 21 libpthread.so.0 0x00007f6a3545809a 22 libpthread.so.0 0x00007f6a3545809a 23 libpthread.so.0 0x00007f6a3545809a 24 libpthread.so.0 0x00007f6a3545809a 25 libpthread.so.0 0x00007f6a3545809a 26 libpthread.so.0 0x00007f6a3545809a 27 libpthread.so.0 0x00007f6a3545809a 28 libpthread.so.0 0x00007f6a3545809a 29 libpthread.so.0 0x00007f6a3545809a 30 libpthread.so.0 0x00007f6a3545809a 31 libpthread.so.0 0x00007f6a3545809a 32 libpthread.so.0 0x00007f6a3545809a 33 libpthread.so.0 0x00007f6a3545809a 34 libpthread.so.0 0x0000
main.swift:8:26: warning: will never be executed let hoge: CustomString = "fuga" ^ main.swift:8:26: note: a call to a never-returning function let hoge: CustomString = "fuga" ^ main.swift:4:14: warning: will never be executed self = "hoge" ^ main.swift:4:16: note: a call to a never-returning function self = "hoge" ^ main.swift:3:5: warning: will never be executed init(stringLiteral value: StringLiteralType) { ^ main.swift:3:5: note: a call to a never-returning function init(stringLiteral value: StringLiteralType) { ^ /usr/bin/swift[0x3f24d54] /usr/bin/swift[0x3f25096] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f46186b8390] [0x7f4618ae70e2] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae70fa] [0x7f4618ae
import Foundation func execute(_ args: [String], in directory: URL? = nil) -> (stdout: String, stderr: String) { let process = Process() process.launchPath = "/usr/bin/env" process.arguments = args if let directory = directory { process.currentDirectoryPath = directory.path } let stdoutPipe = Pipe(), stderrPipe = Pipe() process.standardOutput = stdoutPipe process.standardError = stderrPipe process.launch() process.waitUntilExit() let stdout = String(data: stdoutPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" let stderr = String(data: stderrPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" return (stdout, stderr) } execute(["df", "-m"])
main.swift:19:1: warning: result of call to 'execute(_:in:)' is unused execute(["df", "-m"]) ^ ~~~~~~~~~~~~~~
main.swift:19:1: warning: result of call to 'execute(_:in:)' is unused execute(["df", "-m"]) ^ ~~~~~~~~~~~~~~
import Foundation func execute(_ args: [String], in directory: URL? = nil) -> (stdout: String, stderr: String) { let process = Process() process.launchPath = "/usr/bin/env" process.arguments = args if let directory = directory { process.currentDirectoryPath = directory.path } let stdoutPipe = Pipe(), stderrPipe = Pipe() process.standardOutput = stdoutPipe process.standardError = stderrPipe process.launch() process.waitUntilExit() let stdout = String(data: stdoutPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" let stderr = String(data: stderrPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" return (stdout, stderr) } print(execute(["df", "-m"]).stdout)
Filesystem 1M-blocks Used Available Use% Mounted on none 384019 79671 284825 22% / /dev/mapper/evg0-evol0 384019 79671 284825 22% /tmp udev 30709 1 30709 1% /dev/herokudev none 64 0 64 0% /dev/shm tmpfs 6145 1 6144 1% /etc/resolv.conf
Filesystem 1M-blocks Used Available Use% Mounted on none 384019 80516 283980 23% / /dev/mapper/evg0-evol0 384019 80516 283980 23% /tmp udev 30709 1 30709 1% /dev/herokudev none 64 0 64 0% /dev/shm tmpfs 6145 1 6144 1% /etc/resolv.conf
Usage: @swift403 [SWIFT_OPTIONS] ``` [Swift Code] ```
Usage: @swift41 [SWIFT_OPTIONS] ``` [Swift Code] ```
Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.0.3 (swift-4.0.3-RELEASE) Target: x86_64-unknown-linux-gnu
func f(){}
sil_stage canonical import Builtin import Swift import SwiftShims func f() // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int32, 0 // user: %3 %3 = struct $Int32 (%2 : $Builtin.Int32) // user: %4 return %3 : $Int32 // id: %4 } // end sil function 'main' // f() sil hidden @_T04main1fyyF : $@convention(thin) () -> () { bb0: %0 = tuple () // user: %1 return %0 : $() // id: %1 } // end sil function '_T04main1fyyF'
sil_stage canonical import Builtin import Swift import SwiftShims func f() // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int32, 0 // user: %3 %3 = struct $Int32 (%2 : $Builtin.Int32) // user: %4 return %3 : $Int32 // id: %4 } // end sil function 'main' // f() sil hidden @_T04main1fyyF : $@convention(thin) () -> () { bb0: %0 = tuple () // user: %1 return %0 : $() // id: %1 } // end sil function '_T04main1fyyF'
Usage: @swiftbot [--version=SWIFT_VERSION] [--command={swift, swiftc}] [--options=SWIFTC_OPTIONS] ``` [Swift Code] ``` Examples: @swiftbot ``` print("Hello world!") ``` @swiftbot --version=4.0.3 ``` print("Hello world!") ``` @swiftbot --command=swiftc --options=-dump-parse ``` print("Hello world!") ``` Subcommands: @swiftbot versions: show available Swift toolchain versions @swiftbot contribute: show repository URLs @swiftbot help: show help
2018-04-13-a 4.1 4.0.3 3.1.1 3.0.2
func f() {}
sil_stage canonical import Builtin import Swift import SwiftShims func f() // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int32, 0 // user: %3 %3 = struct $Int32 (%2 : $Builtin.Int32) // user: %4 return %3 : $Int32 // id: %4 } // end sil function 'main' // f() sil hidden @_T04main1fyyF : $@convention(thin) () -> () { bb0: %0 = tuple () // user: %1 return %0 : $() // id: %1 } // end sil function '_T04main1fyyF'
sil_stage canonical import Builtin import Swift import SwiftShims func f() // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int32, 0 // user: %3 %3 = struct $Int32 (%2 : $Builtin.Int32) // user: %4 return %3 : $Int32 // id: %4 } // end sil function 'main' // f() sil hidden @_T04main1fyyF : $@convention(thin) () -> () { bb0: %0 = tuple () // user: %1 return %0 : $() // id: %1 } // end sil function '_T04main1fyyF'
struct S: Hashable { var int: Int }
main.swift:1:8: error: type 'S' does not conform to protocol 'Hashable' struct S: Hashable { ^ main.swift:1:8: error: type 'S' does not conform to protocol 'Equatable' struct S: Hashable { ^ Swift.==:2:13: note: candidate has non-matching type '<Element where Element : Equatable> (ContiguousArray<Element>, ContiguousArray<Element>) -> Bool' public func ==<Element>(lhs: ContiguousArray<Element>, rhs: ContiguousArray<Element>) -> Bool where Element : Equatable ^ Swift.==:2:13: note: candidate has non-matching type '<Element where Element : Equatable> (ArraySlice<Element>, ArraySlice<Element>) -> Bool' public func ==<Element>(lhs: ArraySlice<Element>, rhs: ArraySlice<Element>) -> Bool where Element : Equatable ^ Swift.==:2:13: note: candidate has non-matching type '<Element where Element : Equatable> (Array<Element>, Array<Element>) -> Bool' public func ==<Element>(lhs: [Element], rhs: [Element]) -> Bool where Element : Equatable ^ Swift.==:3:13: note: candidate has non-matching type '(Any.Type?, Any.Type?) -> Bool' public func ==(t0: Any.Type?, t1: Any.Type?) -> Bool ^ Swift.==:6:13: note: candidate has non-matching type '<T where T : RawRepresentable, T.RawValue : Equatable> (T, T) -> Bool' public func ==<T>(lhs: T, rhs: T) -> Bool where T : RawRepresentable, T.RawValue : Equatable ^ Swift.==:45:13: note: candidate has non-matching type '<T where T : Equatable> (T?, T?) -> Bool' public func ==<T>(lhs: T?, rhs: T?) -> Bool where T : Equatable ^ Swift.==:22:13: note: candidate has non-matching type '<T> (T?, _OptionalNilComparisonType) -> Bool' public func ==<T>(lhs: T?, rhs: _OptionalNilComparisonType) -> Bool ^ Swift.==:22:13: note: candidate has non-matching type '<T> (_OptionalNilComparisonType, T?) -> Bool' public func ==<T>(lhs: _OptionalNilComparisonType, rhs: T?) -> Bool ^ Swift.==:9:13: note: candidate
func fibonacci(number: Int) -> Int { if number <= 1 { return number } else { return fibonacci(number: number - 1) + fibonacci(number: number - 2) } } print(fibonacci(number: 10))
Swift version 4.2-dev (LLVM 8a97de0e52, Clang 3c973cd6c1, Swift e0c091a012)
55
Swift version 4.1 (swift-4.1-RELEASE)
55
Swift version 4.0.3 (swift-4.0.3-RELEASE)
55
func fibonacci(number: Int) -> Int { if number <= 1 { return number } else { return fibonacci(number: number - 1) + fibonacci(number: number - 2) } } print(fibonacci(number: 10))
Swift version 4.2-dev (LLVM 8a97de0e52, Clang 3c973cd6c1, Swift e0c091a012)
55
Swift version 4.1 (swift-4.1-RELEASE)
55
Swift version 4.0.3 (swift-4.0.3-RELEASE)
55
GUILD_TEXT
の場合(通常のチャンネル)だけ受け付ける様にしました。 https://discordapp.com/developers/docs/resources/channel#channel-object-channel-typesprint("hello")
lldb swift -c core -o bt -b
でバックトレースを作れる。symbolicate-linux-fatal
の方は実際に成功していないけど、 symbolicate-linux-fatal app crash.log
的な使い方をするぽい。lldb
の実行に依存してる。lldb
を使えなかった。print("hello")
/usr/bin/swift[0x3f24d54] /usr/bin/swift[0x3f25096] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f2d23306390] /usr/bin/swift[0x4c55c0] /usr/bin/swift[0x4c3a83] /usr/bin/swift[0x4beecc] /usr/bin/swift[0x4778c4] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f2d21a30830] /usr/bin/swift[0x475179] Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret main.swift -disable-objc-interop -debug-crash-after-parse -module-name main
llvm-symbolizer
が PATH に入っているともっとマシなトレースが出るはずです。#0 0x0000000003e318c4 PrintStackTraceSignalHandler(void*) (/home/rintaro/Documents/swift-oss/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swift+0x3e318c4) #1 0x0000000003e31c06 SignalHandler(int) (/home/rintaro/Documents/swift-oss/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swift+0x3e31c06) #2 0x00007fa3d67ae390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00000000004c1710 debugFailWithCrash() (/home/rintaro/Documents/swift-oss/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swift+0x4c1710) #4 0x00000000004bfbd3 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) (/home/rintaro/Documents/swift-oss/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swift+0x4bfbd3) #5 0x00000000004bb013 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) (/home/rintaro/Documents/swift-oss/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swift+0x4bb013) #6 0x0000000000473a44 main (/home/rintaro/Documents/swift-oss/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swift+0x473a44) #7 0x00007fa3d4ed8830 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20830) #8 0x0000000000471319 _start (/home/rintaro/Documents/swift-oss/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swift+0x471319) Stack dump: 0. Program arguments: /home/rintaro/Documents/swift-oss/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swift -frontend -interpret test.swift -disable-objc-interop -debug-crash-after-parse -color-diagnostics -module-name test Illegal instruction (core dumped)
llvm-symbolizer
は普通にapt-get
で入れるやつで構わないのですか?/usr/bin/llvm-symbolizer-3.8
として既に入ってた。apt-get install llvm
として明示的にインストールすれば、バージョンサフィックス無しのシンボリックリンクが作られるみたいですね。apt-get install llvm
として明示的にインストールすれば (edited)update-alternatives(8)
を使った。 https://gist.github.com/norio-nomura/505e5a5dce1502c774db51c9e3663700llvm-symbolizer
を使う様になりました。 @swift403 @swift-4.1.3 -Xfrontend -debug-crash-after-parse print("hello")
#0 0x0000000003ae91b8 llvm::sys::PrintStackTrace(llvm::raw_ostream&) (/usr/bin/swift+0x3ae91b8) #1 0x0000000003ae98f6 SignalHandler(int) (/usr/bin/swift+0x3ae98f6) #2 0x00007f1fcf2b6390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00000000004b0540 debugFailWithCrash() (/usr/bin/swift+0x4b0540) #4 0x00000000004aea28 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) (/usr/bin/swift+0x4aea28) #5 0x00000000004aa52b swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) (/usr/bin/swift+0x4aa52b) #6 0x0000000000465564 main (/usr/bin/swift+0x465564) #7 0x00007f1fcd9e0830 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20830) #8 0x0000000000462e29 _start (/usr/bin/swift+0x462e29) Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret main.swift -disable-objc-interop -debug-crash-after-parse -module-name main
#0 0x0000000003f24d54 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x3f24d54) #1 0x0000000003f25096 SignalHandler(int) (/usr/bin/swift+0x3f25096) #2 0x00007fcd052c1390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00000000004c55c0 debugFailWithCrash() (/usr/bin/swift+0x4c55c0) #4 0x00000000004c3a83 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) (/usr/bin/swift+0x4c3a83) #5 0x00000000004beecc swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) (/usr/bin/swift+0x4beecc) #6 0x00000000004778c4 main (/usr/bin/swift+0x4778c4) #7 0x00007fcd039eb830 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20830) #8 0x0000000000475179 _start (/usr/bin/swift+0x475179) Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret main.swift -disable-objc-interop -debug-crash-after-parse -module-name main
enum CustomString: ExpressibleByStringLiteral { typealias StringLiteralType = String init(stringLiteral value: StringLiteralType) { self = "hoge" } } let hoge: CustomString = "fuga" print(hoge)
main.swift:8:26: warning: will never be executed let hoge: CustomString = "fuga" ^ main.swift:8:26: note: a call to a never-returning function let hoge: CustomString = "fuga" ^ main.swift:4:14: warning: will never be executed self = "hoge" ^ main.swift:4:16: note: a call to a never-returning function self = "hoge" ^ main.swift:3:5: warning: will never be executed init(stringLiteral value: StringLiteralType) { ^ main.swift:3:5: note: a call to a never-returning function init(stringLiteral value: StringLiteralType) { ^ #0 0x0000000003f24d54 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x3f24d54) #1 0x0000000003f25096 SignalHandler(int) (/usr/bin/swift+0x3f25096) #2 0x00007f2fb4579390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00007f2fafce7424 _T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC (/usr/lib/swift/linux/libswiftCore.so+0x13c424) #4 0x00007f2fb49a80e4 #5 0x00007f2fb49a80fa #6 0x00007f2fb49a80fa #7 0x00007f2fb49a80fa #8 0x00007f2fb49a80fa #9 0x00007f2fb49a80fa #10 0x00007f2fb49a80fa #11 0x00007f2fb49a80fa #12 0x00007f2fb49a80fa #13 0x00007f2fb49a80fa #14 0x00007f2fb49a80fa #15 0x00007f2fb49a80fa #16 0x00007f2fb49a80fa #17 0x00007f2fb49a80fa #18 0x00007f2fb49a80fa #19 0x00007f2fb49a80fa #20 0x00007f2fb49a80fa #21 0x00007f2fb49a80fa #22 0x00007f2fb49a80fa #23 0x00007f2fb49a80fa #24 0x00007f2fb49a80fa #25 0x00007f2fb49a80fa #26 0x00007f2fb49a80fa #27 0x00007f2fb49a80fa #28 0x00007f2fb49a80fa #29 0x00007f2fb49a80fa #30 0x00007f2fb49a80fa #31 0x00007f2fb49a80fa #32 0x00007f2fb49a80fa #33 0x00007f2fb49a80fa #34 0x00007f2fb49a80fa #35 0x00007f2fb49a80fa #36 0x00007f2fb49a80fa #37 0x00007f2fb49a80fa #38 0x00007f2fb49a80fa #39 0x00007f2fb49a80fa #40 0x00007f2fb49a80fa #41 0x00007f2fb49a80fa #42 0x00007f2fb49a80fa #43 0x00007f2fb49a80fa #44 0x00007f2fb49a80fa #45
print("Hello SwiftBot")
Swift version 4.1 (swift-4.1-RELEASE)
Hello SwiftBot
swift-DEVELOPMENT-SNAPSHOT-2018-04-16-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang c38020c511, Swift da10607e45)
Hello SwiftBot
Swift version 4.1 (swift-4.1-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.2-dev (LLVM d14a2b25f2, Clang c38020c511, Swift da10607e45) Target: x86_64-unknown-linux-gnu
Swift version 4.0.3 (swift-4.0.3-RELEASE) Target: x86_64-unknown-linux-gnu
protocol DictionaryType { associatedtype Key associatedtype Value } protocol A: DictionaryType where Key == Value { static func foo() } extension A { static func foo() { print(type(of: self)) } } extension Dictionary: DictionaryType {} extension Dictionary: A where Key == Value { } extension Array where Element: A { static func foo() { Element.foo() } } [String: String].foo() // Dictionary<String, String> [[String: String]].foo() // Crash
Dictionary<String, String>.Type .Type
master
はこんな感じですよ。 $ ../build/Ninja-ReleaseAssert/swift-macosx-x86_64/bin/swift test.swift Dictionary<String, String>.Type Dictionary<String, String>.Type
import Foundation print(PorcessInfo.processInfo.enrionment["SWIFT_VERSION"])
main.swift:2:7: error: use of unresolved identifier 'PorcessInfo'; did you mean 'ProcessInfo'? print(PorcessInfo.processInfo.enrionment["SWIFT_VERSION"]) ^~~~~~~~~~~ ProcessInfo Foundation.ProcessInfo:1:12: note: 'ProcessInfo' declared here open class ProcessInfo : Foundation.NSObject { ^
import Foundation print(ProcessInfo.processInfo.enrionment["SWIFT_VERSION"])
main.swift:2:19: error: value of type 'ProcessInfo' has no member 'enrionment'; did you mean 'environment'? print(ProcessInfo.processInfo.enrionment["SWIFT_VERSION"]) ~~~~~~~~~~~~^~~~~~~~~~~ ~~~~~~~~~~ environment Foundation.ProcessInfo:3:14: note: 'environment' declared here open var environment: [String : String] { get } ^
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"])
Optional("DEVELOPMENT-SNAPSHOT-2018-04-17-a")
main.swift:2:7: warning: expression implicitly coerced from 'String?' to 'Any' print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ main.swift:2:42: note: provide a default value to avoid this warning print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~ ?? <#default value#> main.swift:2:42: note: force-unwrap the value to avoid this warning print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~ ! main.swift:2:42: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~ as Any
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"] ?? "")
DEVELOPMENT-SNAPSHOT-2018-04-17-a
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"] ?? "")
Swift Versionを返すのはこれでいいのか!swift-DEVELOPMENT-SNAPSHOT-2018-04-16-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang c38020c511, Swift da10607e45)
swift-DEVELOPMENT-SNAPSHOT-2018-04-16-a
SWIFT_VERSION
を設定してますね。swift-
プリフィックスが無いです。swiftenv
の流儀かな?Usage: @swift41 [SWIFT_OPTIONS] ``` [Swift Code] ```
(edited)print("hello")
(edited)hello
(edited)print("あと、コマンド実行中に入力中インジケータを出す様にしました。")
あと、コマンド実行中に入力中インジケータを出す様にしました。
4.1
4.2
4.0.3
の絵文字を登録するとかEXPOSE
していません。 (edited)EXPOSE
サポートしてなかった。 https://devcenter.heroku.com/articles/container-registry-and-runtime#unsupported-dockerfile-commandsSwift version 4.1 (swift-4.1-RELEASE)
(edited)Hello world!!
(edited)swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
Hello world!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
Hello world!!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
Hello world!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
Hello world!!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
Hello world!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
Hello world!!
Swift version 4.1 (swift-4.1-RELEASE)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
Int?.none!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
a!
enum Hoge: CaseIterable { case hoge, fuga, piyo } Hoge.allCases.map { print($0) }
(edited)enum Hoge: CaseIterable { case hoge, fuga, piyo } Hoge.allCases.forEach { print($0) }
(edited)hoge fuga piyo
(edited)import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"] ?? "")
(edited)DEVELOPMENT-SNAPSHOT-2018-04-19-a
(edited)DEVELOPMENT-SNAPSHOT-2018-04-20-a
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"] ?? "")
(edited)DEVELOPMENT-SNAPSHOT-2018-04-22-a
import Foundation let versionOfRxSwift = ProcessInfo.processInfo.environment["RXSWIFT_VERSION"] ?? "" print("RxSwift version: \(versionOfRxSwift)") import RxSwift _ = Observable<String>.create { observerOfString in print("Observable created") observerOfString.on(.next("😉")) observerOfString.on(.completed) return Disposables.create() } .subscribe { event in print(event) }
RxSwift version: 4.1.2 Observable created next(😉) completed
RxSwift version: 4.1.2 Observable created next(😉) completed
RxSwift version: 4.1.2 Observable created next(😉) completed
libRxSwift.so
を作るのにPackage.swift
内でlibrary typeをdynamicにしなくても、 swift build --target RxSwift -Xswiftc -emit-library -Xswiftc -o -Xswiftc `swift build --show-bin-path`/libRxSwift.so
とすれば作れることを知りました。let a: UInt32 = 0x80_00_00_00 let b: UInt32 = 0x80_00_00_00 let c = a.addingReportingOverflow(b) dump(c)
(edited)Swift version 4.1 (swift-4.1-RELEASE)
(edited)▿ (2 elements) - partialValue: 0 - overflow: true
let a: UInt32 = 0x80_00_00_00 let b: UInt32 = 0x7F_FF_FF_FF let c = a.addingReportingOverflow(b) dump(c)
Swift version 4.1 (swift-4.1-RELEASE)
▿ (2 elements) - partialValue: 4294967295 - overflow: false
import TensorFlow
import Python
は通るけど、動かない? @swift-tensorflow
import TensorFlow import Python // NumPy example: let np = Python.import("numpy") // import numpy as np let a = np.arange(15).reshape(3, 5) // a = np.arange(15).reshape(3, 5) let b = np.array([6, 7, 8]) // b = np.array([6, 7, 8])
main.swift:5:18: error: cannot call value of non-function type 'PyValue' let a = np.arange(15).reshape(3, 5) // a = np.arange(15).reshape(3, 5) ~~~~~~~~~^ main.swift:6:17: error: cannot call value of non-function type 'PyValue' let b = np.array([6, 7, 8]) // b = np.array([6, 7, 8]) ~~~~~~~~^
np.arange.call(with: 15)
じゃないと動かないみたいですねimport Foundation @objc protocol Hoge { func foobarbaz() } var x: AnyObject = "hoge" as NSString x.foobarbaz()
(edited)Swift version 4.1 (swift-4.1-RELEASE)
(edited)<unknown>:0: error: fatal error encountered during compilation; please file a bug report with your project and the crash log <unknown>:0: note: Program used external function 'sel_registerName' which could not be resolved! /usr/bin/swift[0x3f24d54] /usr/bin/swift[0x3f25096] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f12ac409390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7f12aab48428] /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7f12aab4a02a] /usr/bin/swift[0x4c3f75] /usr/bin/swift[0x3eb851f] /usr/bin/swift[0xffeddb] /usr/bin/swift[0xffd626] /usr/bin/swift[0xfead79] /usr/bin/swift[0x4d8e48] /usr/bin/swift[0x4c35d3] /usr/bin/swift[0x4beecc] /usr/bin/swift[0x4778c4] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f12aab33830] /usr/bin/swift[0x475179] Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret /usercode/main.swift -disable-objc-interop -I /usr/lib/swift/clang/include/ -I /vendor/SwiftyMath/.build/release/ -I /vendor/swift-package-libbsd/ -module-name main -ldSwiftyMath Aborted (core dumped)
(edited)swift-DEVELOPMENT-SNAPSHOT-2018-04-18-a Swift version 4.2-dev (LLVM d14a2b25f2, Clang da1edea3f7, Swift ac061632b2)
/usercode/main.swift:7:22: error: 'Int' is not convertible to 'AnyObject'; did you mean to use 'as!' to force downcast? var x: AnyObject = 1 as AnyObject ~~^~~~~~~~~~~~ as!
AnyObject
の何でもメソッド呼べちゃう性を Linux で試して見たかっただけなのですが、どこで落ちているのか分からないですねwimport Foundation @objc protocol Hoge { func foobarbaz() } var x: AnyObject = "hoge" as NSString x.foobarbaz()
(edited)<unknown>:0: error: fatal error encountered during compilation; please file a bug report with your project and the crash log <unknown>:0: note: Program used external function 'sel_registerName' which could not be resolved! #0 0x0000000003f24d54 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x3f24d54) #1 0x0000000003f25096 SignalHandler(int) (/usr/bin/swift+0x3f25096) #2 0x00007f3b0201f390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00007f3b0075e428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #4 0x00007f3b0076002a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #5 0x00000000004c3f75 (/usr/bin/swift+0x4c3f75) #6 0x0000000003eb851f llvm::report_fatal_error(llvm::Twine const&, bool) (/usr/bin/swift+0x3eb851f) #7 0x0000000000ffeddb llvm::RuntimeDyldImpl::resolveExternalSymbols() (/usr/bin/swift+0xffeddb) #8 0x0000000000ffd626 llvm::RuntimeDyldImpl::resolveRelocations() (/usr/bin/swift+0xffd626) #9 0x0000000000fead79 llvm::MCJIT::finalizeObject() (/usr/bin/swift+0xfead79) #10 0x00000000004d8e48 swift::RunImmediately(swift::CompilerInstance&, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, swift::IRGenOptions&, swift::SILOptions const&) (/usr/bin/swift+0x4d8e48) #11 0x00000000004c35d3 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) (/usr/bin/swift+0x4c35d3) #12 0x00000000004beecc swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) (/usr/bin/swift+0x4beecc) #13 0x00000000004778c4 main (/usr/bin/swift+0x4778c4) #14 0x00007f3b00749830 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20830) #15 0x0000000000475179 _start (/usr/bin/swift+0x475179) Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret main.sw
(edited)_T0s19preconditionFailures5NeverOSSyXK_s12StaticStringV4fileSu4linetFfA_ ---> default argument 0 of Swift.preconditionFailure(@autoclosure () -> Swift.String, file: Swift.StaticString, line: Swift.UInt) -> Swift.Never
_T0s19preconditionFailures5NeverOSSyXK_s12StaticStringV4fileSu4linetFfA_ ---> default argument 0 of preconditionFailure(_:file:line:)
(edited)[@swift41 [SWIFT_OPTIONS]] ``` [Swift Code] ```
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"] ?? "")
(edited)4.2-DEVELOPMENT-SNAPSHOT-2018-04-23-a
swift
に main.swift
としてコードを渡して実行させる方式だと、シグナルハンドラを設定しても呼ばれないな。4.2-DEVELOPMENT-SNAPSHOT-2018-05-02-a
import Foundation func decimalNumberWithDouble(double: Double) -> NSDecimalNumber { let number = double as NSNumber return NSDecimalNumber(string: number.stringValue) } var i = decimalNumberWithDouble(double: 0.0) let limit = decimalNumberWithDouble(double: 1.1) let target = decimalNumberWithDouble(double: 1.0) while i.compare(limit) == ComparisonResult.orderedAscending { let add = decimalNumberWithDouble(double: 0.01) i = i.adding(add) print(i, i == target) if i == target { print("####called this line####") } } print("fin")
main.swift:5:18: error: cannot convert value of type 'Double' to type 'NSNumber' in coercion let number = double as NSNumber ^~~~~~
import Foundation protocol P { func hoge() } class Q {} extension Q: P { @objc func hoge() { print("q: hoge") } } class R: Q { override func hoge() { super.hoge() print("r: hoge") } } let q = Q() let r = R() q.hoge() r.hoge()
swift: /home/buildnode/jenkins/workspace/oss-swift-4.1-package-linux-ubuntu-16_04/swift/lib/IRGen/GenClass.cpp:2211: llvm::Constant *swift::irgen::emitCategoryData(swift::irgen::IRGenModule &, swift::ExtensionDecl *): Assertion `IGM.ObjCInterop && "emitting RO-data outside of interop mode"' failed. #0 0x0000000003f24d54 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x3f24d54) #1 0x0000000003f25096 SignalHandler(int) (/usr/bin/swift+0x3f25096) #2 0x00007f19216ff390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00007f191fe3e428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #4 0x00007f191fe4002a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #5 0x00007f191fe36bd7 (/lib/x86_64-linux-gnu/libc.so.6+0x2dbd7) #6 0x00007f191fe36c82 (/lib/x86_64-linux-gnu/libc.so.6+0x2dc82) #7 0x000000000066766e swift::irgen::emitCategoryData(swift::irgen::IRGenModule&, swift::ExtensionDecl*) (/usr/bin/swift+0x66766e) #8 0x00000000004e8dc1 swift::irgen::IRGenModule::emitExtension(swift::ExtensionDecl*) (/usr/bin/swift+0x4e8dc1) #9 0x00000000004e0555 swift::irgen::IRGenModule::emitSourceFile(swift::SourceFile&, unsigned int) (/usr/bin/swift+0x4e0555) #10 0x00000000005ad7d6 performIRGeneration(swift::IRGenOptions&, swift::ModuleDecl*, std::unique_ptr<swift::SILModule, std::default_delete<swift::SILModule> >, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, llvm::GlobalVariable**, unsigned int) (/usr/bin/swift+0x5ad7d6) #11 0x00000000005abf9d swift::performIRGeneration(swift::IRGenOptions&, swift::ModuleDecl*, std::unique_ptr<swift::SILModule, std::default_delete<swift::SILModule> >, llvm::StringRef, llvm::LLVMContext&, llvm::GlobalVariable**) (/usr/bin/swift+0x5abf9d) #12 0x00000000004d878b swift::RunImmediately(swift::CompilerInstance&, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>
2018-04-25-a 2018-05-02-a 3.0.1 3.0.2 3.1 3.1.1 4.0 4.0.2 4.0.3 4.1
4.1.1-RELEASE
send(contents, options)
みたいなAPIになっていて、options
に{split: true}
で自動的に分割してくれます。4.0.2 4.1.1 2018-04-25-a 2018-05-02-a 4.1 4.0.3 4.0 3.1.1 3.1 3.0.2 3.0.1
2018-05-02-a
が出てこないのなんでかな。 curl https://api.github.com/repos/apple/swift/tags
{ "data": { "repository": { "refs": { "pageInfo": { "endCursor": "MTAw", "hasNextPage": true, "startCursor": "MQ==" }, "tags": [ { "name": "swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-02-a" }, { "name": "swift-4.1.1-RELEASE" }, { "name": "swift-DEVELOPMENT-SNAPSHOT-2018-04-25-a" }, …
query ($owner: String!, $name: String!, $cursor: String = "") { repository(owner: $owner, name: $name) { refs(refPrefix: "refs/tags/", first: 100, after: $cursor, orderBy: {field: TAG_COMMIT_DATE, direction: DESC}) { pageInfo { endCursor hasNextPage startCursor } tags: nodes { name } } } }
Query Variables: { "owner": "apple", "name": "swift", "cursor": "" }
(edited)cursor
に前のendCursor
を渡す。curl https://api.github.com/repos/apple/swift/tags
でタグ一覧を取得する方法は、そもそもAPIドキュメントに載ってないので、非公式な動作なのかも? https://developer.github.com/v3/git/tags/swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-02-a swift-4.1.1-RELEASE swift-DEVELOPMENT-SNAPSHOT-2018-04-25-a swift-DEVELOPMENT-SNAPSHOT-2018-04-24-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-04-23-a swift-DEVELOPMENT-SNAPSHOT-2018-04-23-a swift-DEVELOPMENT-SNAPSHOT-2018-04-22-a swift-DEVELOPMENT-SNAPSHOT-2018-04-21-a swift-DEVELOPMENT-SNAPSHOT-2018-04-20-a swift-DEVELOPMENT-SNAPSHOT-2018-04-19-a ...
2018-05-02-a 2018-04-25-a 4.1.1 4.1 4.0.3 4.0.2 4.0 3.1.1 3.1 3.0.2 3.0.1
install: missing destination file operand after 'swift-4.2-DEVELOPMENT-SNAPSHOT-2018-04-23-a' Try 'install --help' for more information.
install: missing destination file operand after 'swift-4.2-DEVELOPMENT-SNAPSHOT-2018-04-23-a' Try 'install --help' for more information.
Sending build context to Docker daemon 89.73MB Step 1/10 : FROM ubuntu:16.04 ---> f975c5035748 Step 2/10 : LABEL maintainer="Katsumi Kishikawa <kishikawakatsumi@mac.com>" ---> Running in 3cad3c7b2297 Removing intermediate container 3cad3c7b2297 ---> 14b761354421 Step 3/10 : LABEL Description="Docker Container for the Apple's Swift programming language" ---> Running in 1ac6435d7538 Removing intermediate container 1ac6435d7538 ---> e199f6c5ff72 Step 4/10 : RUN apt-get -q update && apt-get -q install -y make libc6-dev clang-3.8 curl libedit-dev libpython2.7 libicu-dev libssl-dev libxml2 tzdata git libcurl4-openssl-dev pkg-config && update-alternatives --quiet --install /usr/bin/clang clang /usr/bin/clang-3.8 100 && update-alternatives --quiet --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.8 100 && rm -r /var/lib/apt/lists/* ---> Running in 0fb9c293500c Get:1 http://security.ubuntu.com/ubuntu xenial-security InRelease [107 kB] Get:2 http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB] Get:3 http://security.ubuntu.com/ubuntu xenial-security/universe Sources [80.4 kB] Get:4 http://security.ubuntu.com/ubuntu xenial-security/main amd64 Packages [612 kB] Get:5 http://security.ubuntu.com/ubuntu xenial-security/restricted amd64 Packages [12.7 kB] Get:6 http://security.ubuntu.com/ubuntu xenial-security/universe amd64 Packages [436 kB] Get:7 http://security.ubuntu.com/ubuntu xenial-security/multiverse amd64 Packages [3755 B] Get:8 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB] Get:9 http://archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB] Get:10 http://archive.ubuntu.com/ubuntu xenial/universe Sources [9802 kB] Get:11 http://archive.ubuntu.com/ubuntu xenial/main amd64 Packages [1558 kB] Get:12 http://archive.ubuntu.com/ubuntu xenial/restricted amd64 Packages [14.1 kB] ...
2018-05-02-a 2018-04-25-a 2018-04-23-a 4.1.1 4.1 4.0.3 4.0.2 4.0 3.1.1 3.1 3.0.2 3.0.1
import SwiftyMath import SwiftyTopology let S = SimplicialComplex.sphere(dim:3) let H = Homology(S, Int.self) print(H.detailDescription) import Foundation import RxSwift _ = Observable<String>.create { observerOfString in print("Observable created") observerOfString.on(.next("😉")) observerOfString.on(.completed) return Disposables.create() } .subscribe { event in print(event) } import CryptoSwift let data = Data(bytes: [0x01, 0x02, 0x03]) let bytes = data.bytes print(bytes) print(Array<UInt8>(hex: "0x010203")) print(bytes.toHexString()) print("123".md5())
import SwiftyMath import SwiftyTopology let S = SimplicialComplex.sphere(dim:3) let H = Homology(S, Int.self) print(H.detailDescription) import Foundation import RxSwift _ = Observable<String>.create { observerOfString in print("Observable created") observerOfString.on(.next("😉")) observerOfString.on(.completed) return Disposables.create() } .subscribe { event in print(event) } import CryptoSwift let data = Data(bytes: [0x01, 0x02, 0x03]) let bytes = data.bytes print(bytes) print(Array<UInt8>(hex: "0x010203")) print(bytes.toHexString()) print("123".md5())
swift-4.1-RELEASE
H(S^3; 𝐙) = { 0 : 𝐙, [v₀], 1 : 0, [], 2 : 0, [], 3 : 𝐙, [(v₀, v₁, v₂, v₃) + -(v₀, v₁, v₂, v₄) + (v₀, v₁, v₃, v₄) + -(v₀, v₂, v₃, v₄) + (v₁, v₂, v₃, v₄)] } Observable created next(😉) completed [1, 2, 3] [1, 2, 3] 010203 202cb962ac59075b964b07152d234b70
4.1.1-RELEASE
DEVELOPMENT-2018-05-03-a
swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-02-a swift-4.1.1-RELEASE swift-DEVELOPMENT-SNAPSHOT-2018-04-25-a swift-DEVELOPMENT-SNAPSHOT-2018-04-24-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-04-23-a swift-DEVELOPMENT-SNAPSHOT-2018-04-23-a swift-DEVELOPMENT-SNAPSHOT-2018-04-22-a swift-DEVELOPMENT-SNAPSHOT-2018-04-21-a swift-DEVELOPMENT-SNAPSHOT-2018-04-20-a swift-DEVELOPMENT-SNAPSHOT-2018-04-19-a ...
Usage: @swiftbot [--version=SWIFT_VERSION] [--command={swift, swiftc}] [--options=SWIFTC_OPTIONS] ``` [Swift Code] ``` Examples: @swiftbot ``` print("Hello world!") ``` @swiftbot --version=4.0.3 ``` print("Hello world!") ``` @swiftbot --command=swiftc --options=-dump-parse ``` print("Hello world!") ``` Subcommands: @swiftbot versions: show available Swift toolchain versions @swiftbot contribute: show repository URLs @swiftbot help: show help
print(pow(2,5))
swift-4.1.1-RELEASE
/usercode/main.swift:1:7: error: use of unresolved identifier 'pow' print(pow(2,5)) ^~~
import SwiftGlibc print(pow(2,5))
swift-4.1.1-RELEASE
32.0
print("hello")
swift-4.0.3-RELEASE
hello
import Foundation var hint = addrinfo(), addrinfo0: UnsafeMutablePointer<addrinfo>? = nil #if _runtime(_ObjC) hint.ai_socktype = SOCK_STREAM #else hint.ai_socktype = Int32(SOCK_STREAM.rawValue) #endif let error = getaddrinfo("whois.nic.google", "nicname", &hint, &addrinfo0) guard error == 0 else { print(String.init(cString: gai_strerror(error))) exit(error) } defer { freeaddrinfo(addrinfo0) } var addrinfoNext = addrinfo0?.pointee while let addrinfo = addrinfoNext { defer { addrinfoNext = addrinfo.ai_next?.pointee } let sock = socket(addrinfo.ai_family, addrinfo.ai_socktype, addrinfo.ai_protocol) guard sock != -1, connect(sock, addrinfo.ai_addr, addrinfo.ai_addrlen) == 0 else { print(String(cString: strerror(errno))) continue } let handle = FileHandle(fileDescriptor: sock, closeOnDealloc: true) handle.write("xcode.app\r\n".data(using: .utf8)!) FileHandle.standardOutput.write(handle.readDataToEndOfFile()) }
(edited)import Foundation var hint = addrinfo(), addrinfo0: UnsafeMutablePointer<addrinfo>? = nil #if _runtime(_ObjC) hint.ai_socktype = SOCK_STREAM #else hint.ai_socktype = Int32(SOCK_STREAM.rawValue) #endif let error = getaddrinfo("whois.iana.org", "nicname", &hint, &addrinfo0) guard error == 0 else { print(String.init(cString: gai_strerror(error))) exit(error) } defer { freeaddrinfo(addrinfo0) } var addrinfoNext = addrinfo0?.pointee while let addrinfo = addrinfoNext { defer { addrinfoNext = addrinfo.ai_next?.pointee } let sock = socket(addrinfo.ai_family, addrinfo.ai_socktype, addrinfo.ai_protocol) guard sock != -1, connect(sock, addrinfo.ai_addr, addrinfo.ai_addrlen) == 0 else { print(String(cString: strerror(errno))) continue } let handle = FileHandle(fileDescriptor: sock, closeOnDealloc: true) handle.write("xcode.app\r\n".data(using: .utf8)!) FileHandle.standardOutput.write(handle.readDataToEndOfFile()) }
swift-4.1.1-RELEASE
Temporary failure in name resolution
% IANA WHOIS server % for more information on IANA, visit http://www.iana.org % This query returned 1 object refer: whois.nic.google domain: APP organisation: Charleston Road Registry Inc. address: 1600 Amphitheatre Parkway Mountain View, CA 94043 address: United States contact: administrative name: Domains Policy and Compliance organisation: Google Inc. address: 601 N. 34th Street address: Seattle, WA 98103 address: United States phone: 1 202 642 2325 fax-no: 1 650 492 5631 e-mail: iana-contact@google.com contact: technical name: Richard Roberto organisation: Google Inc address: 76 9th Avenue, 4th Floor address: New York, NY 10011 address: United States phone: 1 212 565 2633 fax-no: 1 650 492 5631 e-mail: crr-tech@google.com nserver: NS-TLD1.CHARLESTONROADREGISTRY.COM 2001:4860:4802:32:0:0:0:69 216.239.32.105 nserver: NS-TLD2.CHARLESTONROADREGISTRY.COM 2001:4860:4802:34:0:0:0:69 216.239.34.105 nserver: NS-TLD3.CHARLESTONROADREGISTRY.COM 2001:4860:4802:36:0:0:0:69 216.239.36.105 nserver: NS-TLD4.CHARLESTONROADREGISTRY.COM 2001:4860:4802:38:0:0:0:69 216.239.38.105 nserver: NS-TLD5.CHARLESTONROADREGISTRY.COM 2001:4860:4805:0:0:0:0:69 216.239.60.105 ds-rdata: 41971 8 2 858FEEE8930855598DB109C9705955EDF494FA641ED1CDD07A95C13357E9FD19 ds-rdata: 23684 8 2 3a5cc8a31e02c94aba6461912fabb7e9f5e34957bb6114a55a864d96aec31836 whois: whois.nic.google status: ACTIVE remarks: Registration information: http://www.registry.google created: 2015-06-25 changed: 2018-03-20 source: IANA Network is unreachable
whois.iana.org
への問い合わせは動くけど、whois.nic.google
への問い合わせは動かないな。print(3)
whois.nic.google
print(3)
Domain Name: xcode.app Registry Domain ID: 2C5582619-APP Registrar WHOIS Server: whois.nic.google Registrar URL: http://www.ascio.com Updated Date: 2018-04-05T15:45:23Z Creation Date: 2018-03-30T11:42:39Z Registry Expiry Date: 2019-03-30T11:42:39Z Registrar: Ascio Technologies, Inc. Registrar IANA ID: 106 Registrar Abuse Contact Email: abuse@ascio.com Registrar Abuse Contact Phone: +44.2070159370 Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited Registrant Organization: Apple Inc. Registrant State/Province: CA Registrant Country: US Name Server: a.ns.apple.com Name Server: b.ns.apple.com Name Server: c.ns.apple.com Name Server: d.ns.apple.com DNSSEC: unsigned
4.2-DEVELOPMENT-SNAPSHOT-2018-05-08-a
Sending build context to Docker daemon 89.89MB Step 1/10 : FROM ubuntu:16.04 ---> f975c5035748 Step 2/10 : LABEL maintainer="Katsumi Kishikawa <kishikawakatsumi@mac.com>" ---> Running in 74672f4fa8d7 Removing intermediate container 74672f4fa8d7 ---> 59ef556a8cc5 Step 3/10 : LABEL Description="Docker Container for the Apple's Swift programming language" ---> Running in 5be2396d3584 Removing intermediate container 5be2396d3584 ---> cb7e4d4d82b3 Step 4/10 : RUN apt-get -q update && apt-get -q install -y make libc6-dev clang-3.8 curl libedit-dev libpython2.7 libicu-dev libssl-dev libxml2 tzdata git libcurl4-openssl-dev pkg-config && update-alternatives --quiet --install /usr/bin/clang clang /usr/bin/clang-3.8 100 && update-alternatives --quiet --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.8 100 && rm -r /var/lib/apt/lists/* ---> Running in a914c461bbe6 Get:1 http://security.ubuntu.com/ubuntu xenial-security InRelease [107 kB] Get:2 http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB] Get:3 http://security.ubuntu.com/ubuntu xenial-security/universe Sources [80.4 kB] Get:4 http://security.ubuntu.com/ubuntu xenial-security/main amd64 Packages [625 kB] Get:5 http://security.ubuntu.com/ubuntu xenial-security/restricted amd64 Packages [12.7 kB] Get:6 http://security.ubuntu.com/ubuntu xenial-security/universe amd64 Packages [438 kB] Get:7 http://security.ubuntu.com/ubuntu xenial-security/multiverse amd64 Packages [3759 B] Get:8 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB] Get:9 http://archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB] Get:10 http://archive.ubuntu.com/ubuntu xenial/universe Sources [9802 kB] Get:11 http://archive.ubuntu.com/ubuntu xenial/main amd64 Packages [1558 kB] Get:12 http://archive.ubuntu.com/ubuntu xenial/restricted amd64 Packages [14.1 kB] ...
swift-4.2-branch
とmaster
でそれぞれスナップショットが出てますよ。 (edited)swift-DEVELOPMENT-SNAPSHOT-2018-05-08-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-08-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-02-a swift-4.1.1-RELEASE swift-DEVELOPMENT-SNAPSHOT-2018-04-25-a swift-DEVELOPMENT-SNAPSHOT-2018-04-24-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-04-23-a swift-DEVELOPMENT-SNAPSHOT-2018-04-23-a swift-DEVELOPMENT-SNAPSHOT-2018-04-22-a swift-DEVELOPMENT-SNAPSHOT-2018-04-21-a ...
Sending build context to Docker daemon 89.89MB Step 1/10 : FROM ubuntu:16.04 ---> f975c5035748 Step 2/10 : LABEL maintainer="Katsumi Kishikawa <kishikawakatsumi@mac.com>" ---> Running in 6131c07eaec0 Removing intermediate container 6131c07eaec0 ---> 3be293815ff5 Step 3/10 : LABEL Description="Docker Container for the Apple's Swift programming language" ---> Running in f6ad39fa35f5 Removing intermediate container f6ad39fa35f5 ---> cfb1b891f8e9 Step 4/10 : RUN apt-get -q update && apt-get -q install -y make libc6-dev clang-3.8 curl libedit-dev libpython2.7 libicu-dev libssl-dev libxml2 tzdata git libcurl4-openssl-dev pkg-config && update-alternatives --quiet --install /usr/bin/clang clang /usr/bin/clang-3.8 100 && update-alternatives --quiet --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.8 100 && rm -r /var/lib/apt/lists/* ---> Running in d1d8b173ba38 Get:1 http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB] Get:2 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB] Get:3 http://archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB] Get:4 http://archive.ubuntu.com/ubuntu xenial/universe Sources [9802 kB] Get:5 http://security.ubuntu.com/ubuntu xenial-security InRelease [107 kB] Get:6 http://archive.ubuntu.com/ubuntu xenial/main amd64 Packages [1558 kB] Get:7 http://archive.ubuntu.com/ubuntu xenial/restricted amd64 Packages [14.1 kB] Get:8 http://archive.ubuntu.com/ubuntu xenial/universe amd64 Packages [9827 kB] Get:9 http://archive.ubuntu.com/ubuntu xenial/multiverse amd64 Packages [176 kB] Get:10 http://archive.ubuntu.com/ubuntu xenial-updates/universe Sources [255 kB] Get:11 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 Packages [1002 kB] Get:12 http://archive.ubuntu.com/ubuntu xenial-updates/restricted amd64 Packages [13.1 kB] ...
-
以降のオプションをCommandLine.arguments
で取れる様になりました。 @swift-4.1.3 -Onone - -arg1 value1 print(CommandLine.arguments)
["-", "-arg1", "value1"]
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"] ?? "")
(edited)4.2-DEVELOPMENT-SNAPSHOT-2018-05-10-a
DEVELOPMENT-2018-05-10-a
swift-4.1-DEVELOPMENT-SNAPSHOT-2018-05-11-a swift-DEVELOPMENT-SNAPSHOT-2018-05-11-a swift-DEVELOPMENT-SNAPSHOT-2018-05-10-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-10-a swift-DEVELOPMENT-SNAPSHOT-2018-05-08-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-08-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-02-a swift-4.1.1-RELEASE swift-DEVELOPMENT-SNAPSHOT-2018-04-25-a swift-DEVELOPMENT-SNAPSHOT-2018-04-24-a ...
import Foundation protocol Operand: Numeric {} typealias Operator<Value: Operand> = (Value, Value) -> Value indirect enum Node<Value: Operand> { case v(Value) case op(Node<Value>, Operator<Value>, Node<Value>) func evaluate() -> Value { switch self { case .v(let value): return value case .op(let operand1, let `operator`, let operand2): return `operator`(operand1.evaluate(), operand2.evaluate()) } } } extension Int: Operand {} extension Node: ExpressibleByIntegerLiteral where Value == Int { typealias IntegerLiteralType = Int init(integerLiteral value: Value) { self = .v(value) } } let root: Node<Int> = .op(1, +, .op(2, *, 3)) print(root.evaluate())
(edited)import Foundation print(TimeZone(abbreviation: "JST"))
swift-4.1.1-RELEASE
Optional(Asia/Tokyo (fixed))
/usercode/main.swift:2:7: warning: expression implicitly coerced from 'TimeZone?' to Any print(TimeZone(abbreviation: "JST")) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /usercode/main.swift:2:7: note: provide a default value to avoid this warning print(TimeZone(abbreviation: "JST")) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ?? <#default value#> /usercode/main.swift:2:7: note: force-unwrap the value to avoid this warning print(TimeZone(abbreviation: "JST")) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! /usercode/main.swift:2:7: note: explicitly cast to Any with 'as Any' to silence this warning print(TimeZone(abbreviation: "JST")) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ as Any
import Foundation import CoreFoundation print(CFTimeZoneCopyAbbreviationDictionary())
import Foundation import CoreFoundation print(CFTimeZoneCopyAbbreviationDictionary())
swift-4.1.1-RELEASE
Fatal error: customMirror is not yet implemented: file Foundation/NSDictionary.swift, line 691 /usr/bin/swift[0x3f24d64] /usr/bin/swift[0x3f250a6] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fa9e279b390] /usr/lib/swift/linux/libswiftCore.so(+0x2baf79)[0x7fa9dd9d9f79] /usr/lib/swift/linux/libswiftCore.so(_T0s17_assertionFailures5NeverOs12StaticStringV_SSAE4fileSu4lines6UInt32V5flagstF+0x2c)[0x7fa9dd86c46c] /usr/lib/swift/linux/libFoundation.so(+0x50438f)[0x7fa9dc5b238f] /usr/lib/swift/linux/libFoundation.so(+0x50425a)[0x7fa9dc5b225a] /usr/lib/swift/linux/libFoundation.so(+0x41451b)[0x7fa9dc4c251b] /usr/lib/swift/linux/libswiftCore.so(+0x2f3af8)[0x7fa9dda12af8] /usr/lib/swift/linux/libswiftCore.so(+0x2f5221)[0x7fa9dda14221] /usr/lib/swift/linux/libswiftCore.so(+0x34d751)[0x7fa9dda6c751] /usr/lib/swift/linux/libswiftCore.so(+0x34e72e)[0x7fa9dda6d72e] /usr/lib/swift/linux/libswiftCore.so(+0x21ee99)[0x7fa9dd93de99] ...
import Foundation let date = Date() let timeZone = TimeZone(secondsFromGMT: 0)! let cal = Calendar(identifier: .gregorian) let comp = cal.dateComponents(in: timeZone, from: date) print(comp.second) print(comp.nanosecond)
import Foundation let date = Date() let timeZone = TimeZone(secondsFromGMT: 0)! let cal = Calendar(identifier: .gregorian) let comp = cal.dateComponents(in: timeZone, from: date) print(comp.second) print(comp.nanosecond)
swift-4.1.1-RELEASE
Optional(14) nil
/usercode/main.swift:7:7: warning: expression implicitly coerced from 'Int?' to Any print(comp.second) ^~~~~~~~~~~ /usercode/main.swift:7:12: note: provide a default value to avoid this warning print(comp.second) ~~~~~^~~~~~ ?? <#default value#> /usercode/main.swift:7:12: note: force-unwrap the value to avoid this warning print(comp.second) ~~~~~^~~~~~ ! /usercode/main.swift:7:12: note: explicitly cast to Any with 'as Any' to silence this warning print(comp.second) ~~~~~^~~~~~ as Any /usercode/main.swift:8:7: warning: expression implicitly coerced from 'Int?' to Any print(comp.nanosecond) ^~~~~~~~~~~~~~~ /usercode/main.swift:8:12: note: provide a default value to avoid this warning print(comp.nanosecond) ~~~~~^~~~~~~~~~ ?? <#default value#> /usercode/main.swift:8:12: note: force-unwrap the value to avoid this warning print(comp.nanosecond) ~~~~~^~~~~~~~~~ ...
import Foundation import RxSwift class Hoge: NSObject {} extension Reactive where Base == Hoge { class Piyo {} var hoge: Observable<Int> { return Observable.create { observer in var piyo = Piyo() observer.onNext(42) return Disposables.create {} } } } let hoge = Hoge() hoge.rx.hoge.subscribe(onNext: { res in print(res) })
(edited)import Foundation import RxSwift class Hoge: NSObject {} extension Reactive where Base == Hoge { class Piyo {} var hoge: Observable<Int> { return Observable.create { observer in var piyo = Piyo() observer.onNext(42) return Disposables.create {} } } } let hoge = Hoge() hoge.rx.hoge.subscribe(onNext: { res in print(res) })
swift-4.1.1-RELEASE
42
/usercode/main.swift:10:17: warning: initialization of variable 'piyo' was never used; consider replacing with assignment to '_' or removing it var piyo = Piyo() ~~~~^~~~ _ /usercode/main.swift:19:14: warning: result of call to 'subscribe(onNext:onError:onCompleted:onDisposed:)' is unused hoge.rx.hoge.subscribe(onNext: { res in ^ ~~~~~~~~~~~~~~~~~
Usage: @swiftbot [--version=SWIFT_VERSION] [--command={swift, swiftc}] [--options=SWIFTC_OPTIONS] ``` [Swift Code] ``` Examples: @swiftbot ``` print("Hello world!") ``` @swiftbot --version=4.0.3 ``` print("Hello world!") ``` @swiftbot --command=swiftc --options=-dump-parse ``` print("Hello world!") ``` Subcommands: @swiftbot versions: show available Swift toolchain versions @swiftbot contribute: show repository URLs @swiftbot help: show help
import RxSwift
swift-4.1.1-RELEASE
2018-05-08-a 2018-05-02-a 2018-04-25-a 2018-04-23-a 4.1.1 4.1 4.0.3 4.0.2 4.0 3.1.1 3.1 3.0.2 3.0.1
import RxSwift
swift-4.1-RELEASE
/usercode/main.swift:1:8: error: no such module 'RxSwift' import RxSwift ^
swift-4.0.3-RELEASE
/usercode/main.swift:1:8: error: no such module 'RxSwift' import RxSwift ^
swift-3.1.1-RELEASE
/usercode/main.swift:1:8: error: no such module 'RxSwift' import RxSwift ^
swift-3.0.2-RELEASE
/usercode/main.swift:1:8: error: no such module 'RxSwift' import RxSwift ^
4.1.1/Libraries/*
、 3.0.2/Libraries/*
... のようにディレクトリでバージョニングして、それぞれのPackage.swiftでそのバージョンで使うライブラリを指定するって感じに改修ですね。 そうすると使う方(Botのプログラム)で -L ${SWIFT_VERSION}/Libraries/All
のように切り替えられるのでうまくいくと思うんでなんだったらPRしてくれると です (edited)4.2-DEVELOPMENT-SNAPSHOT-2018-05-14-a
import Foundation protocol EnumCollection: Hashable { static var all: [Self] { get } } extension EnumCollection { static func cases() -> AnySequence<Self> { typealias SelfType = Self return AnySequence { () -> AnyIterator<SelfType> in var raw = 0 return AnyIterator { let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: SelfType.self, capacity: 1) { $0.pointee } } guard current.hashValue == raw else { return nil } raw += 1 return current } } } static var all: [Self] { return Array(self.cases()) } } enum SampleEnum: String, EnumCollection { case hoge = "hoge" case foo case bar = "BAR" } print(SampleEnum.all)
(edited)import Foundation protocol EnumCollection: Hashable { static var all: [Self] { get } } extension EnumCollection { static func cases() -> AnySequence<Self> { typealias SelfType = Self return AnySequence { () -> AnyIterator<SelfType> in var raw = 0 return AnyIterator { let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: SelfType.self, capacity: 1) { $0.pointee } } guard current.hashValue == raw else { return nil } raw += 1 return current } } } static var all: [Self] { return Array(self.cases()) } } enum SampleEnum: String, EnumCollection { case hoge = "hoge" case foo case bar = "BAR" } print(SampleEnum.all)
swift-4.1-RELEASE
[main.SampleEnum.hoge, main.SampleEnum.foo, main.SampleEnum.bar]
swift-4.0-RELEASE
[main.SampleEnum.hoge, main.SampleEnum.foo, main.SampleEnum.bar]
swift-3.1.1-RELEASE
[main.SampleEnum.hoge, main.SampleEnum.foo, main.SampleEnum.bar]
DEVELOPMENT-SNAPSHOT-2018-05-17-a
4.1-DEVELOPMENT-SNAPSHOT-2018-05-17-a
4.2-DEVELOPMENT-SNAPSHOT-2018-05-14-a
Swift version 4.2-dev (LLVM c30b3a99bf, Clang 1bc45fa980, Swift e96fcee6cd) Target: x86_64-unknown-linux-gnu /usr/bin/lldb --repl=-disable-objc-interop error: failed to launch REPL process: process launch failed: 'A' packet returned an error: 8
(edited)Swift version 4.2-dev (LLVM c30b3a99bf, Clang 1bc45fa980, Swift e96fcee6cd) Target: x86_64-unknown-linux-gnu
(edited)Swift version 4.2-dev (LLVM ae60dc0632, Clang 91ee593a0d, Swift f58f5286fd) Target: x86_64-unknown-linux-gnu
master
ブランチから来てます。Swift version 4.1.2-dev (LLVM 1a7347a5f0, Clang cd84be6c42, Swift 0b46ecacfe) Target: x86_64-unknown-linux-gnu
OVERVIEW: Swift Format Tool USAGE: swift [options] <inputs> DEBUG/DEVELOPMENT OPTIONS: -driver-always-rebuild-dependents Always rebuild dependents of files that have been modified -driver-batch-seed <value> Use the given seed value to randomize batch-mode partitions -driver-print-actions Dump list of actions to perform -driver-print-bindings Dump list of job inputs and outputs -driver-print-derived-output-file-map Dump the contents of the derived output file map -driver-print-jobs Dump list of jobs to execute -driver-print-output-file-map Dump the contents of the output file map -driver-show-incremental With -v, dump information about why files are being rebuilt -driver-show-job-lifecycle Show every step in the lifecycle of driver jobs -driver-skip-execution Skip execution of subtasks when performing compilation -driver-use-filelists Pass input files as filelists whenever possible -driver-use-frontend-path <value> Use the given executable to perform compilations MODES: -dump-ast Parse and type-check input file(s) and dump AST(s) -dump-interface-hash Parse input file(s) and dump interface token hash(es) -dump-parse Parse input file(s) and dump AST(s) -dump-scope-maps <expanded-or-list-of-line:column> Parse and type-check input file(s) and dump the scope map(s) -dump-type-refinement-contexts Type-check input file(s) and dump type refinement contexts(s) -emit-assembly Emit assembly file(s) (-S) -emit-bc Emit LLVM BC file(s) -emit-executable Emit a linked executable -emit-imported-modules Emit a list of the imported modules -emit-ir Emit LLVM IR file(s) -emit-library Emit a linked libra
swift-format
が入ってるぽい? (edited)OVERVIEW: Swift Format Tool USAGE: swift [options] <inputs> OPTIONS: -help Display available options -in-place Overwrite input file with formatted file. -indent-switch-case Indent cases in switch statements. -indent-width <n> Number of characters to indent. -line-range <n:n> <start line>:<end line>. Formats a range of lines (1-based). Can only be used with one input file. -o <file> Write output to <file> -tab-width <n> Width of tab character. -use-tabs Use tabs for indentation.
for _ in 0..<10 { print(Int.random(in: 0..<10)) }
6 9 3 1 5 3 2 9 4 5
import Vapor let app = try Application() let client = try app.make(Client.self) let response = try client.get("http://www.apple.com/").wait() print(response.http.status)
import NIO struct E: Error {} let eventLoop = EmbeddedEventLoop() let promises: [EventLoopPromise<Void>] = (0..<100).map { (_: Int) in eventLoop.newPromise() } let futures = promises.map { $0.futureResult } let fN: EventLoopFuture<Void> = EventLoopFuture<Void>.andAll(futures, eventLoop: eventLoop) _ = promises.map { $0.fail(error: E()) } do { () = try fN.wait() print("should've thrown an error") } catch _ as E { print("good") } catch let e { print("error of wrong type \(e)") }
swiftc
へ渡すオプションを.build/debug.yaml
から取り出して、それを渡すと良い。 https://github.com/norio-nomura/SwiftCompilerDiscordappBot/blob/8962b0dec3723876b2ac8a105653fce8567025eb/Sources/SwiftCompilerDiscordappBot/App.swift#L201-L207 (edited)class A { init(a: A) { } } class B: A { init() { super.init(a: self) } }
class A { init(a: A) { } } class B: A { init() { super.init(a: self) } }
<stdin>:8:23: error: 'self' used before super.init call super.init(a: self) ^
<stdin>:8:15: error: 'self' used before 'super.init' call super.init(a: self) ^
class A { init(a: B) {} } class B: A { var s: String init() { self.s = "aaa" super.init(a: self) } }
0. Program arguments: /usr/bin/swift -frontend -interpret /usercode/main.swift -disable-objc-interop -module-name main 1. While running pass #34 SILFunctionTransform "Definite Initialization" on SILFunction "@_TFC4main1BcfT_S0_". Aborted (core dumped)
class A { let hoge: C init(a: B) { a.foo() self.hoge = .init() } } class C {} class B: A { init() { super.init(a: self) } func foo() { print(self.hoge) } } B.init().foo()
壊した!Usage: @swiftbot [--version=SWIFT_VERSION] [--command={swift, swiftc}] [--options=SWIFTC_OPTIONS] ``` [Swift Code] ``` Examples: @swiftbot ``` print("Hello world!") ``` @swiftbot --version=4.0.3 ``` print("Hello world!") ``` @swiftbot --command=swiftc --options=-dump-parse ``` print("Hello world!") ``` Subcommands: @swiftbot versions: show available Swift toolchain versions @swiftbot contribute: show repository URLs @swiftbot help: show help
var a = Random.default var b = a print(a.next()) print(b.next())
struct LinearCongruentialGenerator : RandomNumberGenerator { private var seed: UInt64 init(seed: UInt64 = 0) { self.seed = seed } mutating func next() -> UInt64 { seed = 6364136223846793005 &* seed &+ 1442695040888963407 return seed } } var a = LinearCongruentialGenerator() var b = a print(a.next()) print(b.next())
1442695040888963407 1442695040888963407
struct A<T1, T2> {} typealias B<T> = A<Int, T> typealias D = A<Int, Int> protocol C {} extension B: C {}
struct A<T1, T2> {} typealias B<T> = A<Int, T> typealias D = A<Int, Int> protocol C {} extension B: C {}
swift-4.0.3-RELEASE
struct A<T1, T2> {} typealias B<T> = A<Int, T> typealias D = A<Int, Int> protocol C {} extension A: C where T1 == Int {}
struct A<T1, T2> {} typealias B<T> = A<Int, T> typealias D = A<Int, Int> protocol C {} extension A: C where T1 == Int {}
swift-4.0.3-RELEASE
/usercode/main.swift:7:1: error: extension of type 'A' with constraints cannot have an inheritance clause extension A: C where T1 == Int {} ^ ~
import Vapor let app = try Application() let client = try app.make(Client.self) let response = try client.get("http://www.apple.com/").wait() print(response.http.status)
Usage: @swiftbot [--version=SWIFT_VERSION] [--command={swift, swiftc}] [--options=SWIFTC_OPTIONS] ``` [Swift Code] ``` Examples: @swiftbot ``` print("Hello world!") ``` @swiftbot --version=4.0.3 ``` print("Hello world!") ``` @swiftbot --command=swiftc --options=-dump-parse ``` print("Hello world!") ``` Subcommands: @swiftbot versions: show available Swift toolchain versions @swiftbot contribute: show repository URLs @swiftbot help: show help
swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-29-a swift-4.1-DEVELOPMENT-SNAPSHOT-2018-05-29-a swift-DEVELOPMENT-SNAPSHOT-2018-05-29-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-28-a swift-4.1-DEVELOPMENT-SNAPSHOT-2018-05-28-a swift-DEVELOPMENT-SNAPSHOT-2018-05-28-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-27-a swift-4.1-DEVELOPMENT-SNAPSHOT-2018-05-27-a swift-DEVELOPMENT-SNAPSHOT-2018-05-27-a swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-26-a ...
swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-29-a
でいいんですかね?DEVELOPMENT-SNAPSHOT-2018-05-29-a
しか見てないので、同じ日付のうち、どれか1つしか入りません。2018-05-08-a 2018-05-02-a 2018-04-25-a 2018-04-23-a 4.1.1 4.1 4.0.3 4.0.2 4.0 3.1.1 3.1 3.0.2 3.0.1
install: missing destination file operand after 'swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-29-a' Try 'install --help' for more information.
Sending build context to Docker daemon 89.91MB Step 1/10 : FROM ubuntu:16.04 ---> f975c5035748 Step 2/10 : LABEL maintainer="Katsumi Kishikawa <kishikawakatsumi@mac.com>" ---> Running in a69bfb9db1ab Removing intermediate container a69bfb9db1ab ---> 5ccd5d03a5fe Step 3/10 : LABEL Description="Docker Container for the Apple's Swift programming language" ---> Running in 21f3976de53e Removing intermediate container 21f3976de53e ---> 91e0694f254e Step 4/10 : RUN apt-get -q update && apt-get -q install -y make libc6-dev clang-3.8 curl libedit-dev libpython2.7 libicu-dev libssl-dev libxml2 tzdata git libcurl4-openssl-dev pkg-config && update-alternatives --quiet --install /usr/bin/clang clang /usr/bin/clang-3.8 100 && update-alternatives --quiet --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.8 100 && rm -r /var/lib/apt/lists/* ---> Running in 0599cc52794a Get:1 http://security.ubuntu.com/ubuntu xenial-security InRelease [107 kB] Get:2 http://archive.ubuntu.com/ubuntu xenial InRelease [247 kB] Get:3 http://security.ubuntu.com/ubuntu xenial-security/universe Sources [80.9 kB] Get:4 http://security.ubuntu.com/ubuntu xenial-security/main amd64 Packages [637 kB] Get:5 http://security.ubuntu.com/ubuntu xenial-security/restricted amd64 Packages [12.7 kB] Get:6 http://security.ubuntu.com/ubuntu xenial-security/universe amd64 Packages [444 kB] Get:7 http://security.ubuntu.com/ubuntu xenial-security/multiverse amd64 Packages [3743 B] Get:8 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB] Get:9 http://archive.ubuntu.com/ubuntu xenial-backports InRelease [107 kB] Get:10 http://archive.ubuntu.com/ubuntu xenial/universe Sources [9802 kB] Get:11 http://archive.ubuntu.com/ubuntu xenial/main amd64 Packages [1558 kB] Get:12 http://archive.ubuntu.com/ubuntu xenial/restricted amd64 Packages [14.1 kB] ...
2018-05-29-a 2018-05-08-a 2018-05-02-a 2018-04-25-a 2018-04-23-a 4.1.1 4.1 4.0.3 4.0.2 4.0 3.1.1 3.1 3.0.2 3.0.1
protocol P0 { init(string: String) } class Animal { init() {} convenience init(string: String) { self.init() } var str1: String = "" } final class Cat : Animal, P0 { var str2: String = "" } func createP0<X: P0>() -> X { return X.init(string: "apple") } let cat: Cat = createP0() print(cat)
protocol P0 { init(string: String) } class Animal { init() {} convenience init(string: String) { self.init() } var str1: String = "" } final class Cat : Animal, P0 { var str2: String = "" } func createP0<X: P0>() -> X { return X.init(string: "apple") } let cat: Cat = createP0() print(cat)
swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-29-a
swift: /home/buildnode/jenkins/workspace/oss-swift-4.2-package-linux-ubuntu-16_04/swift/lib/IRGen/MetadataLayout.h:208: const swift::irgen::ClassMetadataLayout::StoredMethodInfo &swift::irgen::ClassMetadataLayout::getStoredMethodInfo(swift::SILDeclRef) const: Assertion `it != MethodInfos.end()' failed. /usr/bin/swift[0x40fb264] /usr/bin/swift[0x40f90f2] /usr/bin/swift[0x40fb412] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f549b0bc390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7f54997fb428] /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7f54997fd02a] /lib/x86_64-linux-gnu/libc.so.6(+0x2dbd7)[0x7f54997f3bd7] /lib/x86_64-linux-gnu/libc.so.6(+0x2dc82)[0x7f54997f3c82] /usr/bin/swift[0x625c26] /usr/bin/swift[0x685385] /usr/bin/swift[0x68579b] /usr/bin/swift[0x5f20f5] /usr/bin/swift[0x5e41c8] /usr/bin/swift[0x5e216e] /usr/bin/swift[0x505bcb] /usr/bin/swift[0x5bc277] /usr/bin/swift[0x5baa10] /usr/bin/swift[0x4f6c37] /usr/bin/swift[0x4ddb8b] /usr/bin/swift[0x4d8eb1] ...
swift-4.1.1-RELEASE
main.Cat
Swift version 4.2-dev (LLVM 6a6f279fed, Clang 8c9b467e0e, Swift 1a317f4712) Target: x86_64-unknown-linux-gnu
(edited)Swift version 4.1.2 (swift-4.1.2-RELEASE) Target: x86_64-unknown-linux-gnu
SwiftBacktrace
をインポートできる様にしました。 @swift-4.1.3
import Foundation import SwiftBacktrace handle(signal: SIGABRT) { signo in fputs(backtrace().joined(separator: "\n") + "\nsignal: \(signo)", stderr) fflush(stderr) } abort()
/Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(callStackSymbols<A>(_:transform:)+0x87) [0x00007f899fa2d567] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(backtrace(_:formatter:)+0xd8) [0x00007f899fa2ce98] -(+0x0) [0x00007f89a790d175] -(+0x0) [0x00007f89a790d410] /lib/x86_64-linux-gnu/libpthread.so.0(__restore_rt+0x0) [0x00007f89a74dd390] -(+0x0) [0x00007ffdd962fcb0] signal: 6
do { class A { let title: String init(title: String) { self.title = title } } let a1 = A(title: "Hello") print(a1.title) }
do { class A { let title: String init(title: String) { self.title = title } } let a1 = A(title: "Hello") print(a1.title) }
do { class A { let title: String init(title: String) { self.title = title } } let a1 = A(title: "Hello") print(a1.title) }
swift-4.1.1-RELEASE
Hello
do { class A { let title: String init(title: String) { self.title = title } } let a1 = A(title: "Hello") print(a1.title) }
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT).
になります )Welcome to Apple Swift version 4.2 (swiftlang-1000.0.16.4 clang-1000.0.25.3).
(edited)protocol A { associatedtype C = B } struct B {} struct D<T>: A {} extension D where T: A { typealias C = T.C }
protocol A { associatedtype C = B } struct B {} struct D<T>: A {} extension D where T: A { typealias C = T.C }
⚠️ 2018-06-18-a
Swift '2018-06-18-a' toolchain is not supported.
swift-4.1.1-RELEASE
Can't demangle: _T0Xe1C4main1APqaMa /usr/bin/swift[0x3f24d64] /usr/bin/swift[0x3f250a6] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f80fc8ab390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7f80fafea428] /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7f80fafec02a] /usr/bin/swift[0x1752665] /usr/bin/swift[0x17522cf] /usr/bin/swift[0x5f6e5f] /usr/bin/swift[0x5f6527] /usr/bin/swift[0x5f5a18] /usr/bin/swift[0x4e7e2c] /usr/bin/swift[0x4ec855] /usr/bin/swift[0x55017e] /usr/bin/swift[0x53dc74] /usr/bin/swift[0x5783d4] /usr/bin/swift[0x577cbd] /usr/bin/swift[0x56e18d] /usr/bin/swift[0x4e5c60] /usr/bin/swift[0x5ad73f] /usr/bin/swift[0x5abf9d] /usr/bin/swift[0x4d878b] /usr/bin/swift[0x4c35d3] /usr/bin/swift[0x4beecc] /usr/bin/swift[0x4778c4] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f80fafd5830] /usr/bin/swift[0x475179] Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret /usercode/main.swift -disable-objc-interop -module-name main ...
struct Path<T1, T2> {} protocol PathConstructorType { associatedtype T1 associatedtype T2 associatedtype PathType = Path<T1, T2> } struct PathConstructor<T1, T2>: PathConstructorType { func create(path: [String]) -> PathType { fatalError() } } extension PathConstructor where T2: PathConstructorType { typealias PathType = Path<T1, T2.PathType> }
実際のコードはこんな感じで、PathConstructor<T1, PathConstructor<T2, T3>>
を Path<T1, Path<T2, T3>>
に変換するために再帰させたいなーとassociatedtype
を上書きですかー。 (edited)struct A { } struct B { } protocol P { associatedtype Assoc = A } struct S<T>: P { } extension S where T == Int { typealias Assoc = B } print(S<String>.Assoc())
(edited)struct A { } struct B { } protocol P { associatedtype Assoc = A } struct S<T>: P { } extension S where T == Int { typealias Assoc = B } print(S<String>.Assoc())
swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-29-a
B()
swift-4.1.1-RELEASE
B()
protocol P { typealias Assoc = A } struct A {} struct B: P { typealias Assoc = Int } struct S<T>: P {} extension S where T: P { typealias Assoc = T.Assoc } print(type(of: S<B>.Assoc.self))
(edited)protocol P { typealias Assoc = A } struct A {} struct B: P { typealias Assoc = Int } struct S<T>: P {} extension S where T: P { typealias Assoc = T.Assoc } print(type(of: S<B>.Assoc.self))
swift-4.2-DEVELOPMENT-SNAPSHOT-2018-05-29-a
A.Type
swift-4.1.1-RELEASE
A.Type
protocol P { typealias Assoc = A } struct A {} struct B: P { typealias Assoc = Int } struct S<T>: P {} extension S where T: P { typealias Assoc = T.Assoc } print(type(of: S<B>.Assoc.self))
PathConstructor<T1, PathConstructor<T2, T3>>
を Path<T1, Path<T2, T3>>
に変換するために再帰させたいなーと struct Path<T1, T2> {} struct PathConstructor<T1, T2> { func create(path: [String]) -> Path<T1, T2> { fatalError() } } extension<T3, T4> PathConstructor where T2 == PathConstructor<T3, T4> { func create(path: [String]) -> Path<T1, Path<T3, T4>> { fatalError() } }
struct Path<T1, T2> {} struct PathConstructor<T1, T2> { typealias PathType = Path<T1, T2> } extension<T3, T4> PathConstructor where T2 == PathConstructor<T3, T4> { typealias PathType = Path<T1, T2.PathType> } extension PathConstructor { func create(path: [String]) -> PathType { fatalError() } }
(edited)extension Optional { func flatten<T>() -> T? where Wrapped == T? { return flatMap { $0 } } } let a: Int?? = .some(.some(42)) let b: Int? = a.flatten() print(String(describing: b))
(edited)extension Optional { func flatten<T>() -> T? where Wrapped == T? { return flatMap { $0 } } } let a: Int?? = .some(.some(42)) let b: Int? = a.flatten() print(String(describing: b))
swift-4.1.1-RELEASE
Optional(42)
struct A<T> { } extension A where T == Bool { typealias B = String } extension A { typealias B = Int }
struct A<T> { } extension A where T == Bool { typealias B = String } extension A { typealias B = Int }
swift-4.1.1-RELEASE
/usercode/main.swift:7:13: error: invalid redeclaration of 'B' typealias B = Int ^ /usercode/main.swift:4:13: note: 'B' previously declared here typealias B = String ^
protocol P { associatedtype T1 associatedtype T2 } extension P where T1 == Int { typealias T2 = String } struct A<T>: P { typealias T1 = T } print(A<String>.T2.self)
protocol P { associatedtype T1 associatedtype T2 } extension P where T1 == Int { typealias T2 = String } struct A<T>: P { typealias T1 = T } print(A<String>.T2.self)
swift-4.1.1-RELEASE
String
protocol P { associatedtype T1 } protocol HasT2 { associatedtype T2 } struct A<T>: P { typealias T1 = T } extension A: HasT2 where T == Int { typealias T2 = String } print(A<String>.T2.self)
protocol P { associatedtype T1 } protocol HasT2 { associatedtype T2 } struct A<T>: P { typealias T1 = T } extension A: HasT2 where T == Int { typealias T2 = String } print(A<String>.T2.self)
swift-4.1.1-RELEASE
String
protocol P { associatedtype T1 } protocol HasT2 { associatedtype T2 } struct A<T>: P { typealias T1 = T } extension A: HasT2 where T == Int { typealias T2 = String } func f<A: HasT2>(_ a: A.Type) {} f(A<String>.self)
protocol P { associatedtype T1 } protocol HasT2 { associatedtype T2 } struct A<T>: P { typealias T1 = T } extension A: HasT2 where T == Int { typealias T2 = String } func f<A: HasT2>(_ a: A.Type) {} f(A<String>.self)
swift-4.1.1-RELEASE
/usercode/main.swift:15:1: error: 'String' is not convertible to 'Int' f(A<String>.self) ^
protocol A { associatedtype X } protocol B { associatedtype Y } protocol C { associatedtype Y } struct M<T>: A { typealias X = T } extension M: B where X == Int { typealias Y = Int } extension M: C where X == String { typealias Y = String }
<stdin>:21:15: error: invalid redeclaration of 'Y' typealias Y = String ^ <stdin>:17:15: note: 'Y' previously declared here typealias Y = Int ^ <stdin>:16:1: error: type 'M<T>' does not conform to protocol 'B' extension M: B where X == Int { ^ <stdin>:5:20: note: multiple matching types named 'Y' associatedtype Y ^ <stdin>:17:15: note: possibly intended match typealias Y = Int ^ <stdin>:21:15: note: possibly intended match typealias Y = String ^ <stdin>:20:1: error: type 'M<T>' does not conform to protocol 'C' extension M: C where X == String { ^ <stdin>:9:20: note: multiple matching types named 'Y' associatedtype Y ^ <stdin>:17:15: note: possibly intended match typealias Y = Int ^ <stdin>:21:15: note: possibly intended match typealias Y = String ^
let a: Float80 = 0
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
DEVELOPMENT-SNAPSHOT-2018-06-26-a
Usage: @swift41 [SWIFT_OPTIONS] ``` [Swift Code] ```
import Foundation var formatter = ISO8601DateFormatter() formatter.formatOptions = .withFullDate let date = formatter.date(from: "2018-06-30") print(date)
Optional(2018-06-30 00:00:00 +0000)
stderr:<stdin>:5:7: warning: expression implicitly coerced from 'Date?' to Any print(date) ^~~~ <stdin>:5:7: note: provide a default value to avoid this warning print(date) ^~~~ ?? <#default value#> <stdin>:5:7: note: force-unwrap the value to avoid this warning print(date) ^~~~ ! <stdin>:5:7: note: explicitly cast to Any with 'as Any' to silence this warning print(date) ^~~~ as Any
class A { init() {} convenience init(s: String) { print(self.init()) } }
(edited)swift: /home/buildnode/jenkins/workspace/oss-swift-4.1-package-linux-ubuntu-16_04/swift/lib/Sema/CSApply.cpp:5684: swift::Expr *(anonymous namespace)::ExprRewriter::coerceCallArguments(swift::Expr *, swift::AnyFunctionType *, swift::ApplyExpr *, ArrayRef<swift::Identifier>, bool, swift::constraints::ConstraintLocatorBuilder): Assertion `fromTupleExpr.size() == 1 && fromTupleExpr[0]' failed. #0 0x0000000003f25074 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x3f25074) #1 0x0000000003f253b6 SignalHandler(int) (/usr/bin/swift+0x3f253b6) #2 0x00007f4f34d07390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00007f4f33446428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #4 0x00007f4f3344802a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #5 0x00007f4f3343ebd7 (/lib/x86_64-linux-gnu/libc.so.6+0x2dbd7) #6 0x00007f4f3343ec82 (/lib/x86_64-linux-gnu/libc.so.6+0x2dc82) #7 0x0000000001399d4e (anonymous namespace)::ExprRewriter::coerceCallArguments(swift::Expr*, swift::AnyFunctionType*, swift::ApplyExpr*, llvm::ArrayRef<swift::Identifier>, bool, swift::constraints::ConstraintLocatorBuilder) (/usr/bin/swift+0x1399d4e) #8 0x0000000001383604 (anonymous namespace)::ExprRewriter::finishApply(swift::ApplyExpr*, swift::Type, swift::constraints::ConstraintLocatorBuilder) (/usr/bin/swift+0x1383604) #9 0x000000000139b0e3 (anonymous namespace)::ExprRewriter::visitApplyExpr(swift::ApplyExpr*) (/usr/bin/swift+0x139b0e3) #10 0x000000000137fbd4 (anonymous namespace)::ExprRewriter::walkToExprPost(swift::Expr*) (/usr/bin/swift+0x137fbd4) #11 0x0000000001385621 (anonymous namespace)::ExprWalker::walkToExprPost(swift::Expr*) (/usr/bin/swift+0x1385621) #12 0x000000000167719c swift::Expr::walk(swift::ASTWalker&) (/usr/bin/swift+0x167719c) #13 0x000000000137c7ef swift::constraints::ConstraintSystem::applySolution(swift::constraints::Solution&, swift::Expr*, swift::Type, bool, bool, bool) (/usr/bin/swift+0x137c7ef) #14 0x00000000012c64b6
(edited)The command '/bin/sh -c SWIFT_URL=https://swift.org/builds/$SWIFT_BRANCH/$(echo "$SWIFT_PLATFORM" | tr -d .)/$SWIFT_VERSION/$SWIFT_VERSION-$SWIFT_PLATFORM.tar.gz && curl -fSsL $SWIFT_URL -o swift.tar.gz && curl -fSsL $SWIFT_URL.sig -o swift.tar.gz.sig && export GNUPGHOME="$(mktemp -d)" && tar -xzf swift.tar.gz --directory / --strip-components=1 && rm -r "$GNUPGHOME" swift.tar.gz.sig swift.tar.gz && chmod -R o+r /usr/lib/swift' returned a non-zero code: 22
2018-05-29-a 2018-05-08-a 2018-05-02-a 2018-04-25-a 2018-04-23-a 4.1.1 4.1 4.0.3 4.0.2 4.0 3.1.1 3.1 3.0.2 3.0.1
public func p(_ items: Any...) {} class A { init() {} convenience init(s: String) { p(self.init()) } }
public func p(_ items: Any...) {} class A { init() {} convenience init(s: String) { p(self.init()) } }
swift-4.1.1-RELEASE
swift: /home/buildnode/jenkins/workspace/oss-swift-4.1-package-linux-ubuntu-16_04/swift/lib/Sema/CSApply.cpp:5684: swift::Expr *(anonymous namespace)::ExprRewriter::coerceCallArguments(swift::Expr *, swift::AnyFunctionType *, swift::ApplyExpr *, ArrayRef<swift::Identifier>, bool, swift::constraints::ConstraintLocatorBuilder): Assertion `fromTupleExpr.size() == 1 && fromTupleExpr[0]' failed. /usr/bin/swift[0x3f24d64] /usr/bin/swift[0x3f250a6] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f167dc3e390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7f167c37d428] /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7f167c37f02a] /lib/x86_64-linux-gnu/libc.so.6(+0x2dbd7)[0x7f167c375bd7] /lib/x86_64-linux-gnu/libc.so.6(+0x2dc82)[0x7f167c375c82] /usr/bin/swift[0x1399b2e] /usr/bin/swift[0x13833e4] /usr/bin/swift[0x139aec3] /usr/bin/swift[0x137f9b4] /usr/bin/swift[0x1385401] /usr/bin/swift[0x1676f7c] /usr/bin/swift[0x137c5cf] /usr/bin/swift[0x12c6296] /usr/bin/swift[0x1355fd6] ...
self.init()
の戻り値を変数に受けられないっていうの初めて知ったんですよね。Void
として扱われていますね。import Foundation print("Good night") sleep(1) print("Morning")
import Foundation print("Good night") sleep(1) print("Morning")
swift-4.1.1-RELEASE
Good night Morning
import Foundation //import PlaygroundSupport //PlaygroundPage.current.needsIndefiniteExecution = true let group1 = DispatchGroup() func a(_ name: String) { group1.enter() print("Good night, \(name)..") sleep(2) print("Morning, \(name)!") group1.leave() } DispatchQueue.global().async { a("Anna") } DispatchQueue.global().async { a("Bob") } DispatchQueue.global().async { a("Cony") } group1.notify(queue: .main) { print("*** Good morning, all! ***") //PlaygroundPage.current.finishExecution() } // Xcode 9.4.1 と 10.0 beta2 どちらも同じ結果でした /* Playground Settings - Platform: macOS Good night, Cony.. Good night, Anna.. Good night, Bob.. Morning, Cony! Morning, Bob! Morning, Anna! *** Good morning, all! *** */ /* Playground Settings - Platform: iOS Good night, Anna.. Good night, Cony.. Good night, Bob.. *** Good morning, all! *** */
import Foundation //import PlaygroundSupport //PlaygroundPage.current.needsIndefiniteExecution = true let group1 = DispatchGroup() func a(_ name: String) { group1.enter() print("Good night, \(name)..") sleep(2) print("Morning, \(name)!") group1.leave() } DispatchQueue.global().async { a("Anna") } DispatchQueue.global().async { a("Bob") } DispatchQueue.global().async { a("Cony") } group1.notify(queue: .main) { print("*** Good morning, all! ***") //PlaygroundPage.current.finishExecution() } // Xcode 9.4.1 と 10.0 beta2 どちらも同じ結果でした /* Playground Settings - Platform: macOS Good night, Cony.. Good night, Anna.. Good night, Bob.. Morning, Cony! Morning, Bob! Morning, Anna! *** Good morning, all! *** */ /* Playground Settings - Platform: iOS Good night, Anna.. Good night, Cony.. Good night, Bob.. *** Good morning, all! *** */
swift-4.1.1-RELEASE
Good night, Anna.. Good night, Bob..
import Foundation import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true let group1 = DispatchGroup() func a(_ name: String) { group1.enter() print("Good night, \(name)..") sleep(2) print("Morning, \(name)!") group1.leave() } DispatchQueue.global().async { a("Anna") } DispatchQueue.global().async { a("Bob") } DispatchQueue.global().async { a("Cony") } group1.notify(queue: .main) { print("*** Good morning, all! ***") PlaygroundPage.current.finishExecution() } // Xcode 9.4.1 と 10.0 beta2 どちらも同じ結果でした /* Playground Settings - Platform: macOS Good night, Cony.. Good night, Anna.. Good night, Bob.. Morning, Cony! Morning, Bob! Morning, Anna! *** Good morning, all! *** */ /* Playground Settings - Platform: iOS Good night, Anna.. Good night, Cony.. Good night, Bob.. *** Good morning, all! *** */
上記のコードを Playgroundで実行すると、Platformによって実行結果が変わってしまいます。macOSにすると望む結果になるんですけど、iOSだと待ち合わせしてくれないのです。 (edited)import Foundation let group1 = DispatchGroup() group1.notify(queue: .main) { print("*** Good morning, all! ***") } sleep(1)
(edited)import Foundation let group1 = DispatchGroup() group1.notify(queue: .main) { print("*** Good morning, all! ***") } sleep(1)
swift-4.1.1-RELEASE
import Foundation let task = DispatchQueue(label: "task") let group1 = DispatchGroup() group1.notify(queue: task) { print("*** Good morning, all! ***") } sleep(1)
import Foundation let task = DispatchQueue(label: "task") let group1 = DispatchGroup() group1.notify(queue: task) { print("*** Good morning, all! ***") } sleep(1)
swift-4.1.1-RELEASE
*** Good morning, all! ***
import Foundation let group1 = DispatchGroup() func a(_ name: String) { print("Good night, \(name)..") sleep(2) print("Morning, \(name)!") group1.leave() } group1.enter() DispatchQueue.global().async { a("Anna") } group1.enter() DispatchQueue.global().async { a("Bob") } group1.enter() DispatchQueue.global().async { a("Cony") } group1.notify(queue: .main) { print("*** Good morning, all! ***") }
import Foundation let group1 = DispatchGroup() func a(_ name: String) { print("Good night, \(name)..") sleep(2) print("Morning, \(name)!") } DispatchQueue.global().async(group: group1) { a("Anna") } DispatchQueue.global().async(group: group1) { a("Bob") } DispatchQueue.global().async(group: group1) { a("Cony") } group1.notify(queue: .main) { print("*** Good morning, all! ***") exit(0) } dispatchMain()
Good night, Anna.. Good night, Bob.. Good night, Cony.. Morning, Anna! Morning, Bob! Morning, Cony! *** Good morning, all! ***
SLACK_BOT_TOKEN
とか簡単に取得できそうだけど大丈夫なのかな… (edited)let wat: Int? = nil if let _: Int? = wat { print("1") } if let _: Any? = wat { print("2") }
1
stderr:<stdin>:2:4: warning: explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed if let _: Int? = wat { print("1") } ^ ~~~~ ~~~ Int
enum Result<Value, Error> { case success(Value) case failure(Error) } extension Result: Equatable where Value: Equatable, Error: Equatable { static func == (lhs: Result, rhs: Result) -> Bool { switch (lhs, rhs) { case let (.success(lhs), .success(rhs)): return lhs == rhs case let (.failure(lhs), .failure(rhs)): return lhs == rhs case (.success, .failure), (.failure, .success): return false } } } print(Result<String, Never>.success("a") == Result<String, Never>.success("b"))
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"] ?? "")
DEVELOPMENT-SNAPSHOT-2018-07-20-a
DEVELOPMENT-2018-07-19-a
struct ConditionalCast<T> { static func cast(value: Any?) -> T? { return value as? T } } print(ConditionalCast<Int?>.cast(value: nil))
4.1.3-RELEASE
class Object { func foo() -> String { return "from Object" } } class Child: Object { override func foo() -> String { return "from Child" } } let child = unsafeBitCast(Object(), to: Child.self) print(child.foo())
from Child
stderr:<stdin>:12:13: warning: 'unsafeBitCast' from 'Object' to 'Child' can be replaced with 'unsafeDowncast' let child = unsafeBitCast(Object(), to: Child.self) ^~~~~~~~~~~~~ unsafeDowncast
func f(a: Int = 1){}
internal func f(a: Int = default)
internal func f(a: Int = 1)
rintaro昨日 午後4時15分 https://github.com/apple/swift/pull/18579 これは嬉しい!インターフェイスでデフォルト値が default じゃなくてきちんと表示されるようになります。
-print-ast
が対応してるんですねclass Super<T> {} class Sub: Super<Sub> {} print(Sub())
(edited)protocol Animal {} extension Animal { init(_animal: Self) { self = _animal } } class AnimalBase: Animal { convenience init(with animal: AnimalBase) { self.init(_animal: animal) } } class Cat: AnimalBase { let _name = "Tama" var name: String { return _name } func bark() { print("cat \(self.name)") } } class Dog: AnimalBase {} let animal = Cat(with: Dog()) animal.bark()
(edited)#0 0x0000000003ae91b8 llvm::sys::PrintStackTrace(llvm::raw_ostream&) (/usr/bin/swift+0x3ae91b8) #1 0x0000000003ae98f6 SignalHandler(int) (/usr/bin/swift+0x3ae98f6) #2 0x00007fa453580390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00007fa44ed5824f _swift_retain_ (/usr/lib/swift/linux/libswiftCore.so+0x41324f) #4 0x00007fa4539af2f9 #5 0x00007fa4539af405 #6 0x00007fa4539af06b #7 0x0000000000f348bf llvm::MCJIT::runFunction(llvm::Function*, llvm::ArrayRef<llvm::GenericValue>) (/usr/bin/swift+0xf348bf) #8 0x0000000000f38a62 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, char const* const*) (/usr/bin/swift+0xf38a62) #9 0x00000000004bf776 swift::RunImmediately(swift::CompilerInstance&, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, swift::IRGenOptions&, swift::SILOptions const&) (/usr/bin/swift+0x4bf776) #10 0x00000000004ae580 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) (/usr/bin/swift+0x4ae580) #11 0x00000000004aa52b swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) (/usr/bin/swift+0x4aa52b) #12 0x0000000000465564 main (/usr/bin/swift+0x465564) #13 0x00007fa451caa830 __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x20830) #14 0x0000000000462e29 _start (/usr/bin/swift+0x462e29) Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/engine.git--3106915580378752918/Sources/CHTTP/inc
(edited)self.init(_animal: animal)
が通るのヤバですねfatalError()
swift-4.1.1-RELEASE
Fatal error: file /usercode/main.swift, line 1 Current stack trace: 0 libswiftCore.so 0x00007f64e85c55c0 _swift_stdlib_reportFatalErrorInFile + 221 1 libswiftCore.so 0x00007f64e83343dc <unavailable> + 1369052 2 libswiftCore.so 0x00007f64e856e222 <unavailable> + 3703330 3 libswiftCore.so 0x00007f64e856f689 <unavailable> + 3708553 4 libswiftCore.so 0x00007f64e8333ad6 <unavailable> + 1366742 5 libswiftCore.so 0x00007f64e856dfeb <unavailable> + 3702763 6 libswiftCore.so 0x00007f64e8333ad6 <unavailable> + 1366742 7 libswiftCore.so 0x00007f64e84a0f79 <unavailable> + 2862969 8 libswiftCore.so 0x00007f64e8333440 _assertionFailure(_:_:file:line:flags:) + 44 10 swift 0x0000000000fed1ce <unavailable> + 12505550 ...
import Foundation "".enumerateLines { (a, b) in }
swift-4.1.1-RELEASE
Fatal error: enumerateSubstrings(in:options:using:) is not yet implemented: file Foundation/NSString.swift, line 791 /usr/bin/swift[0x3f24d64] /usr/bin/swift[0x3f250a6] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f1619b01390] /usr/lib/swift/linux/libswiftCore.so(+0x2baf79)[0x7f1614d3ff79] /usr/lib/swift/linux/libswiftCore.so(_T0s17_assertionFailures5NeverOs12StaticStringV_SSAE4fileSu4lines6UInt32V5flagstF+0x2c)[0x7f1614bd246c] /usr/lib/swift/linux/libFoundation.so(+0x50438f)[0x7f160ddd538f] /usr/lib/swift/linux/libFoundation.so(+0x50425a)[0x7f160ddd525a] /usr/lib/swift/linux/libFoundation.so(_T010Foundation8NSStringC14enumerateLinesyySS_SpyAA8ObjCBoolVGtcF+0x77)[0x7f160de63117] /usr/lib/swift/linux/libFoundation.so(_T0s14StringProtocolP10FoundationSS5IndexVADRtzrlE14enumerateLinesyySS_Sbztc8invoking_tF+0xa0)[0x7f160de79620] [0x7f1619f310c3] /usr/bin/swift[0xfed1ce] /usr/bin/swift[0xff1692] /usr/bin/swift[0x4d9076] /usr/bin/swift[0x4c35d3] /usr/bin/swift[0x4beecc] ...
class Person { var name: String var friends: [Person] = [] var bestFriend: Person? = nil init(name: String) { self.name = name } } _ = \Person.bestFriend?.name
class Person { var name: String var friends: [Person] = [] var bestFriend: Person? = nil init(name: String) { self.name = name } } _ = \Person.bestFriend?.name
class Person { var name: String var friends: [Person] = [] var bestFriend: Person? = nil init(name: String) { self.name = name } } _ = \Person.bestFriend?.name
swift-4.0-RELEASE
-Xfrontend
ではなく-frontend
が使える様になりました。 @swift-4.2.4 -frontend -print-ast func f(n: Int = 1) {}
internal func f(n: Int = default)
-frontend -repl
も使える様になりました。 @swift-4.2.4 -frontend -repl import RxSwift :print_decl Observable
class Observable<Element> : ObservableType { typealias E = Element init() func subscribe<O>(_ observer: O) -> Disposable where Element == O.E, O : ObserverType func asObservable() -> Observable<Observable<Element>.E> @objc deinit func composeMap<R>(_ transform: @escaping (Element) throws -> R) -> Observable<R> } extension Observable { @available(*, deprecated, renamed: "from(optional:)", message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.") static func from(_ optional: Observable<Element>.E?) -> Observable<Observable<Element>.E> @available(*, deprecated, renamed: "from(optional:scheduler:)", message: "Implicit conversions from any type to optional type are allowed and that is causing issues with `from` operator overloading.") static func from(_ optional: Observable<Element>.E?, scheduler: ImmediateSchedulerType) -> Observable<Observable<Element>.E> }
:print_decl Hashable
(edited)protocol Hashable : Equatable { var hashValue: Int { get } func hash(into hasher: inout Hasher) }
(edited)protocol Hashable : Equatable { var hashValue: Int { get } }
Usage: @swiftbot [--version=SWIFT_VERSION] [--command={swift, swiftc}] [--options=SWIFTC_OPTIONS] ``` [Swift Code] ``` Examples: @swiftbot ``` print("Hello world!") ``` @swiftbot --version=4.0.3 ``` print("Hello world!") ``` @swiftbot --command=swiftc --options=-dump-parse ``` print("Hello world!") ``` Subcommands: @swiftbot versions: show available Swift toolchain versions @swiftbot contribute: show repository URLs @swiftbot help: show help
print("hello")
⚠️ 4.2
Swift '4.2' toolchain is not supported.
print("hello")
struct Stone { var x: Int { get { return 1 } _modify { var x: Int = 3 yield &x y = x } } var y: Int = 0 } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) print(a.y) } main()
<stdin>:7:9: error: expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition _modify { ^ <stdin>:23:9: error: cannot pass immutable value as inout argument: 'x' is a get-only property mod(&a.x) ^~~~
error: unable to invoke subcommand: /usr/bin/swift-←これで (No such file or directory)
struct Stone { var x: Int { get { return 1 } _modify { var x: Int = 3 yield &x y = x } } var y: Int = 0 } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) print(a.y) } main()
struct Stone { var x: Int { get { return 1 } _modify { var x: Int = 3 yield &x y = x } } var y: Int = 0 } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) print(a.y) } main()
struct Stone { var x: Int { get { return 1 } _modify { var x: Int = 3 yield &x y = x } } var y: Int = 0 } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) print(a.x) print(a.y) } main()
struct Stone { var x: Int { _modify { var x: Int = 3 yield &x y = x } } var y: Int = 0 } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) print(a.x) print(a.y) } main()
(edited)<stdin>:3:9: error: variable with a 'modify' accessor must also have a getter, addressor, or 'read' accessor _modify { ^
struct Stone { var x: Int { get { return 1 } _modify { var xx: Int = 3 yield &xx y = xx } } var y: Int = 0 } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) print(a.x) print(a.y) } main()
struct Stone { var x: Int { get { return 1 } _modify { var xx: Int = 3 print("before yield \(xx)") yield &xx print("after yield \(xx)") y = xx } } var y: Int = 0 } func mod(_ x: inout Int) { print("before modify") x = 8 print("after modify") } func main() { var a = Stone() mod(&a.x) print(a.y) } main()
before yield 3 before modify after modify after yield 8 8
struct Stone { var x: Int { get { return 1 } _modify { var xx: Int = 3 print("before yield \(xx)") yield &xx print("after yield \(xx)") y = xx } } var y: Int = 0 } func mod(_ x: inout Int) { print("before modify") x = 8 print("after modify") } func main() { var a = Stone() print("before coroutine") mod(&a.x) print("after coroutine") print(a.y) } main()
before coroutine before yield 3 before modify after modify after yield 8 after coroutine 8
class Hoge { func hoge() { let foo = { [weak self] in print(self) guard let self = self else { return } print(self) } foo() } } Hoge().hoge()
(edited)Optional(main.Hoge) main.Hoge
stderr:<stdin>:4:19: warning: expression implicitly coerced from 'Hoge?' to 'Any' print(self) ^~~~ <stdin>:4:19: note: provide a default value to avoid this warning print(self) ^~~~ ?? <#default value#> <stdin>:4:19: note: force-unwrap the value to avoid this warning print(self) ^~~~ ! <stdin>:4:19: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(self) ^~~~ as Any
(edited)let s = #"a\b\c"# print(s)
<stdin>:1:13: error: invalid escape sequence in literal let s = #"a\b\c"# ^ <stdin>:1:15: error: invalid escape sequence in literal let s = #"a\b\c"# ^ <stdin>:1:9: error: expected initial value after '=' let s = #"a\b\c"# ^ <stdin>:1:8: error: consecutive statements on a line must be separated by ';' let s = #"a\b\c"# ^ ; <stdin>:1:9: error: expected expression let s = #"a\b\c"# ^
Swift version 4.2-dev (LLVM 6d629af647, Clang 257fa19143, Swift 7ad7e1d968) Target: x86_64-unknown-linux-gnu
let s = #"a\b\c"# print(s)
protocol P {} extension P { init(_with instance: Self) { self = instance } } class Animal : P { init() {} convenience init(with instance: Animal) { self.init(_with: instance) } } class Cat : Animal { override init() {} } class Dog : Animal { override init() {} } let cat: Cat = Cat(with: Dog()) // Dog with Cat type??? print(type(of: cat))
(edited)<stdin>:10:22: error: cannot convert value of type 'Animal' to expected argument type 'Self' self.init(_with: instance) ^~~~~~~~ as! Self
(edited)-swift-version 5
でいかがでしょ?self
差し替えのも封じられたかな?最後の付け足しか Q&A かだったのでスライド↓中にコードが見当たらない・・・。 https://speakerdeck.com/kateinoigakukun/konpairakaraniu-jie-kuswift-method-dispatch-1protocol Animal {} extension Animal { init(_animal: Self) { self = _animal } } class AnimalBase: Animal { convenience init(with animal: AnimalBase) { self.init(_animal: animal) } } class Cat: AnimalBase { let _name = "Tama" var name: String { return _name } func bark() { print(name) } } class Dog: AnimalBase {} let animal = Cat(with: Dog()) animal.bark()
<stdin>:11:28: error: cannot convert value of type 'AnimalBase' to expected argument type 'Self' self.init(_animal: animal) ^~~~~~ as! Self
struct A { var b: Int = 1 @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 2 } }
struct A { var b: Int = 1 @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 2 } }
struct A { var b: Int = 1 @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 2 } }
struct A { var b: Int { return 11111 } @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 22222 } } print(A().b) print(A().itazura())
struct A { var b: Int { return 11111 } @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 22222 } } print(A().b) print(A().itazura())
~/D/swift-asobu $ swift --version Apple Swift version 4.1.2 (swiftlang-902.0.54 clang-902.0.39.2) Target: x86_64-apple-darwin17.7.0 ~/D/swift-asobu $ swift hoge.swift 11111 11111
struct A { var b: Int { return 11111 } }
<unknown>:0: error: option '-emit-sil' is not supported by 'swift'; did you mean to use 'swiftc'?
struct A { var b: Int { return 11111 } }
sil_stage canonical import Builtin import Swift import SwiftShims struct A { var b: Int { get } init() } // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int32, 0 // user: %3 %3 = struct $Int32 (%2 : $Builtin.Int32) // user: %4 return %3 : $Int32 // id: %4 } // end sil function 'main' // A.b.getter sil hidden @_T04main1AV1bSivg : $@convention(method) (A) -> Int { // %0 // user: %1 bb0(%0 : $A): debug_value %0 : $A, let, name "self", argno 1 // id: %1 %2 = integer_literal $Builtin.Int64, 11111 // user: %3 %3 = struct $Int (%2 : $Builtin.Int64) // user: %4 return %3 : $Int // id: %4 } // end sil function '_T04main1AV1bSivg' // Int.init(_builtinIntegerLiteral:) sil public_external [transparent] [serialized] @_T0S2iBi2048_22_builtinIntegerLiteral_tcfC : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int { // %0 // user: %2 bb0(%0 : $Builtin.Int2048, %1 : $@thin Int.Type): %2 = builtin "s_to_s_checked_trunc_Int2048_Int64"(%0 : $Builtin.Int2048) : $(Builtin.Int64, Builtin.Int1) // user: %3 %3 = tuple_extract %2 : $(Builtin.Int64, Builtin.Int1), 0 // user: %4 %4 = struct $Int (%3 : $Builtin.Int64) // user: %5 return %4 : $Int // id: %5 } // end sil function '_T0S2iBi2048_22_builtinIntegerLiteral_tcfC'
struct A { var b: Int { return 11111 } }
struct A { var b: Int { return 11111 } }
sil_stage canonical import Builtin import Swift import SwiftShims struct A { var b: Int { get } init() } // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int32, 0 // user: %3 %3 = struct $Int32 (%2 : $Builtin.Int32) // user: %4 return %3 : $Int32 // id: %4 } // end sil function 'main' // A.b.getter sil hidden @_T04hoge1AV1bSivg : $@convention(method) (A) -> Int { // %0 // user: %1 bb0(%0 : $A): debug_value %0 : $A, let, name "self", argno 1 // id: %1 %2 = integer_literal $Builtin.Int64, 11111 // user: %3 %3 = struct $Int (%2 : $Builtin.Int64) // user: %4 return %3 : $Int // id: %4 } // end sil function '_T04hoge1AV1bSivg' // Int.init(_builtinIntegerLiteral:) sil public_external [transparent] [serialized] @_T0S2iBi2048_22_builtinIntegerLiteral_tcfC : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int { // %0 // user: %2 bb0(%0 : $Builtin.Int2048, %1 : $@thin Int.Type): %2 = builtin "s_to_s_checked_trunc_Int2048_Int64"(%0 : $Builtin.Int2048) : $(Builtin.Int64, Builtin.Int1) // user: %3 %3 = tuple_extract %2 : $(Builtin.Int64, Builtin.Int1), 0 // user: %4 %4 = struct $Int (%3 : $Builtin.Int64) // user: %5 return %4 : $Int // id: %5 } // end sil function '_T0S2iBi2048_22_builtinIntegerLiteral_tcfC'
struct A { var b: Int { return 11111 } func itazura() -> Int { return 22222 } }
sil_stage canonical import Builtin import Swift import SwiftShims struct A { var b: Int { get } func itazura() -> Int init() } // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int32, 0 // user: %3 %3 = struct $Int32 (%2 : $Builtin.Int32) // user: %4 return %3 : $Int32 // id: %4 } // end sil function 'main' // A.b.getter sil hidden @_T04hoge1AV1bSivg : $@convention(method) (A) -> Int { // %0 // user: %1 bb0(%0 : $A): debug_value %0 : $A, let, name "self", argno 1 // id: %1 %2 = integer_literal $Builtin.Int64, 11111 // user: %3 %3 = struct $Int (%2 : $Builtin.Int64) // user: %4 return %3 : $Int // id: %4 } // end sil function '_T04hoge1AV1bSivg' // Int.init(_builtinIntegerLiteral:) sil public_external [transparent] [serialized] @_T0S2iBi2048_22_builtinIntegerLiteral_tcfC : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int { // %0 // user: %2 bb0(%0 : $Builtin.Int2048, %1 : $@thin Int.Type): %2 = builtin "s_to_s_checked_trunc_Int2048_Int64"(%0 : $Builtin.Int2048) : $(Builtin.Int64, Builtin.Int1) // user: %3 %3 = tuple_extract %2 : $(Builtin.Int64, Builtin.Int1), 0 // user: %4 %4 = struct $Int (%3 : $Builtin.Int64) // user: %5 return %4 : $Int // id: %5 } // end sil function '_T0S2iBi2048_22_builtinIntegerLiteral_tcfC' // A.itazura() sil hidden @_T04hoge1AV7itazuraSiyF : $@convention(method) (A) -> Int { // %0 // user: %1 bb0(%0 : $A): debug_value %0 : $A, let, name "self", argno 1 // id: %1 %2 = integer_literal $Builtin.Int64, 22222 // user: %3 %3 = struct $Int (%2 : $Bu
struct A { var b: Int { return 11111 } @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 22222 } }
swift: /home/buildnode/jenkins/workspace/oss-swift-4.1-package-linux-ubuntu-16_04/swift/lib/SILGen/SILGen.cpp:638: void swift::Lowering::SILGenModule::preEmitFunction(swift::SILDeclRef, llvm::PointerUnion<ValueDecl *, Expr *>, swift::SILFunction *, swift::SILLocation): Assertion `F->empty() && "already emitted function?!"' failed. #0 0x0000000003f25074 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x3f25074) #1 0x0000000003f253b6 SignalHandler(int) (/usr/bin/swift+0x3f253b6) #2 0x00007f19f566b390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00007f19f3daa428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #4 0x00007f19f3dac02a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #5 0x00007f19f3da2bd7 (/lib/x86_64-linux-gnu/libc.so.6+0x2dbd7) #6 0x00007f19f3da2c82 (/lib/x86_64-linux-gnu/libc.so.6+0x2dc82) #7 0x0000000000c2be2f swift::Lowering::SILGenModule::preEmitFunction(swift::SILDeclRef, llvm::PointerUnion<swift::ValueDecl*, swift::Expr*>, swift::SILFunction*, swift::SILLocation) (/usr/bin/swift+0xc2be2f) #8 0x0000000000c3336f swift::Lowering::SILGenModule::emitFunction(swift::FuncDecl*)::$_1::operator()(swift::SILFunction*) const (/usr/bin/swift+0xc3336f) #9 0x0000000000c2b975 swift::Lowering::SILGenModule::emitFunction(swift::FuncDecl*) (/usr/bin/swift+0xc2b975) #10 0x0000000000ccae75 (anonymous namespace)::SILGenType::emitType() (/usr/bin/swift+0xccae75) #11 0x0000000000ccab98 swift::Lowering::SILGenModule::visitNominalTypeDecl(swift::NominalTypeDecl*) (/usr/bin/swift+0xccab98) #12 0x0000000000c30e6b swift::Lowering::SILGenModule::emitSourceFile(swift::SourceFile*, unsigned int) (/usr/bin/swift+0xc30e6b) #13 0x0000000000c31b36 swift::SILModule::constructSIL(swift::ModuleDecl*, swift::SILOptions&, swift::FileUnit*, llvm::Optional<unsigned int>, bool) (/usr/bin/swift+0xc31b36) #14 0x0000000000c3210d swift::performSILGeneration(swift::ModuleDecl*, swift::SILOptions&, bool) (/usr/bin/swift+0xc3210d) #15 0x
struct A { var b: Int { return 11111 } @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> String { return "Hello" } } print(A().itazura())
4.1.2
と 4.1.3
のタグでチェックアウトしたり、その辺の git blame を見たりする@_silgen_name()
入れると何故か動かないですね。swift-4.2-DEVELOPMENT-SNAPSHOT-2018-09-07-a
以降、動かなくなってる> @swift-4.2.4import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
4.2-DEVELOPMENT-SNAPSHOT-2018-08-25-a
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
DEVELOPMENT-SNAPSHOT-2018-09-08-a
import Foundation struct Empty: Codable { } struct Foo: Codable { var empty: Empty } struct Bar: Codable { var empty: [Empty] } struct Piyo<E: Codable>: Codable { var empty: E } let encoder = JSONEncoder() let decoder = JSONDecoder() do { print(try decoder.decode(Bar.self, from: encoder.encode(Foo.init(empty: .init())))) } catch { print(error) } do { print(try decoder.decode(Foo.self, from: encoder.encode(Bar.init(empty: .init())))) } catch { print(error) } do { print(try decoder.decode(Piyo<Empty>.self, from: encoder.encode(Piyo<[Empty]>(empty: .init())))) } catch { print(error) } do { print(try decoder.decode(Piyo<[Empty]>.self, from: encoder.encode(Piyo<Empty>(empty: .init())))) } catch { print(error) }
⚠️ [DecodingError.typeMismatch: Value of type 'Array<Any>' required for key 'empty'.] Foo(empty: main.Empty()) Piyo<Empty>(empty: main.Empty()) ⚠️ [DecodingError.typeMismatch: Value of type 'Array<Any>' required for key 'empty'.]
import Foundation let d1 = Date() let d2 = Date() + 12345 let diff = Calendar.current.dateComponents([.hour, .minute, .second, .nanosecond], from: d1, to: d2) print(String(format: "%02d:%02d:%02d", diff.hour!, diff.minute!, diff.second!) )
(edited)import Foundation let d1 = Date() let d2 = Date() + 12345 let diff = Calendar.current.dateComponents([.hour, .minute, .second, .nanosecond], from: d1, to: d2) print(String(format: "%02d:%02d:%02d.%d", diff.hour!, diff.minute!, diff.second!, diff.nanosecond!) )
import Foundation let d1 = Date() let d2 = Date() + 12345 let diff = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second, .nanosecond], from: d1, to: d2) print(String(format: "%02d:%02d:%02d.%d", diff.hour!, diff.minute!, diff.second!, diff.nanosecond!) )
Fatal error: file Foundation/NSCalendar.swift, line 617 #0 0x0000000003f25074 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x3f25074) #1 0x0000000003f253b6 SignalHandler(int) (/usr/bin/swift+0x3f253b6) #2 0x00007fe2f1ecd390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00007fe2ecd880b9 _T0s17_assertionFailures5NeverOs12StaticStringV_SSAE4fileSu4lines6UInt32V5flagstFTf4nxnnn_n (/usr/lib/swift/linux/libswiftCore.so+0x2bb0b9) #4 0x00007fe2ecc1a41c _T0s17_assertionFailures5NeverOs12StaticStringV_SSAE4fileSu4lines6UInt32V5flagstF (/usr/lib/swift/linux/libswiftCore.so+0x14d41c) #5 0x00007fe2e9417056 _T010Foundation10NSCalendarC10componentsAA14DateComponentsVAC4UnitV_AA0D0V4fromAJ2toAC7OptionsV7optionstF (/usr/lib/swift/linux/libFoundation.so+0x3b0056) #6 0x00007fe2e97bac21 _T010Foundation8CalendarV14dateComponentsAA04DateD0Vs3SetVyAC9ComponentOG_AA0E0V4fromAM2totFAfA10NSCalendarCcfU_TA (/usr/lib/swift/linux/libFoundation.so+0x753c21) #7 0x00007fe2e97baa64 _T010Foundation10NSCalendarCAA14DateComponentsVs5Error_pIgxozo_AcEsAF_pIgxrzo_TRTA (/usr/lib/swift/linux/libFoundation.so+0x753a64) #8 0x00007fe2e97c0889 _T010Foundation10NSCalendarCAA14DateComponentsVs5Error_pIgxozo_AcEsAF_pIgxrzo_TRTA.124 (/usr/lib/swift/linux/libFoundation.so+0x759889) #9 0x00007fe2e96f7e29 _T010Foundation14_MutableHandleC3mapqd__qd__xKcKlF (/usr/lib/swift/linux/libFoundation.so+0x690e29) #10 0x00007fe2e97b3e7a _T010Foundation8CalendarV14dateComponentsAA04DateD0Vs3SetVyAC9ComponentOG_AA0E0V4fromAM2totF (/usr/lib/swift/linux/libFoundation.so+0x74ce7a) #11 0x00007fe2f22fd16c #12 0x0000000000fed3be llvm::MCJIT::runFunction(llvm::Function*, llvm::ArrayRef<llvm::GenericValue>) (/usr/bin/swift+0xfed3be) #13 0x0000000000ff1882 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, st
_T010Foundation10NSCalendarC10componentsAA14DateComponentsVAC4UnitV_AA0D0V4fromAJ2toAC7OptionsV7optionstF ---> Foundation.NSCalendar.components(Foundation.NSCalendar.Unit, from: Foundation.Date, to: Foundation.Date, options: Foundation.NSCalendar.Options) -> Foundation.DateComponents
Date
関連のnanosecond
周りはバグだらけ。enum Result<Value, Error: Swift.Error> { case success(Value) case failure(Error) func get() throws -> Value { switch self { case .success(let value): return value case .failure(let error): throw error } } } extension Result where Error == Never { func get() -> Value { switch self { case .success(let value): return value } } } let a: Result<Int, Never> = .success(42) print(a.get())
swift-4.2-DEVELOPMENT-SNAPSHOT-2018-09-07-a
以降でボットが動かない症状、URLSession.dataTask(with:)
へ渡したURLRequest
のhttpBody
がURLSessionDataTask
内部で失われているらしいところまでは把握したのだけれど、最低限の再現条件がわからなくてbugs.swift.orgへ登録できない…protocol P1 { associatedtype A1 associatedtype A2 } protocol P2: P1 where A2 == A3 { typealias A3 = A1 } class S: P2 { typealias A1 = Int typealias A2 = A3 }
(edited)protocol P1 { associatedtype A1 associatedtype A2 } protocol P2: P1 where A2 == A3 { typealias A3 = A1 } class S: P2 { typealias A1 = Int typealias A2 = A3 }
<stdin>:10:7: error: type 'S' does not conform to protocol 'P1' class S: P2 { ^ <stdin>:3:20: note: protocol requires nested type 'A2'; do you want to add it? associatedtype A2 ^ <stdin>:10:7: error: type 'S' does not conform to protocol 'P2' class S: P2 { ^
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
4.2-DEVELOPMENT-SNAPSHOT-2018-08-25-a
swift-4.2-DEVELOPMENT-SNAPSHOT-2018-09-07-a以降でボットが動かない症状、URLSession.dataTask(with:)へ渡したURLRequestのhttpBodyがURLSessionDataTask内部で失われているらしいところまでは把握したのだけれど、最低限の再現条件がわからなくてbugs.swift.orgへ登録できない…
再現できた。 https://bugs.swift.org/browse/SR-8759URLRequest
のhttpBody
が送られなくなるらしい。import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
4.2-DEVELOPMENT-SNAPSHOT-2018-09-14-a
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
protocol P {} protocol Foo {} extension Int: P {} extension Array: Foo where Element: P {} let a = [1,2,3] print(a is Foo)
(edited)true
stderr:<stdin>:8:9: warning: 'is' test is always true print(a is Foo) ^
(edited)<stdin>:8:9: warning: 'is' test is always true print(a is Foo) ^ warning: Swift runtime does not yet support dynamically querying conditional conformance ('Swift.Array<Swift.Int>': 'main.Foo') Could not cast value of type 'Swift.Array<Swift.Int>' (0x7f1e0cfb7240) to 'main.Foo' (0x7f1e0cfb7280). #0 0x0000000003f25074 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x3f25074) #1 0x0000000003f253b6 SignalHandler(int) (/usr/bin/swift+0x3f253b6) #2 0x00007f1e11cc7390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #3 0x00007f1e10406428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #4 0x00007f1e1040802a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #5 0x00007f1e0ce92fd3 (/usr/lib/swift/linux/libswiftCore.so+0x39dfd3) #6 0x00007f1e0ce8f599 (/usr/lib/swift/linux/libswiftCore.so+0x39a599) #7 0x00007f1e0ce8f5eb (/usr/lib/swift/linux/libswiftCore.so+0x39a5eb) #8 0x00007f1e0ce90b38 _dynamicCastToExistential(swift::OpaqueValue*, swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*, swift::TargetExistentialTypeMetadata<swift::InProcess> const*, swift::DynamicCastFlags) (/usr/lib/swift/linux/libswiftCore.so+0x39bb38) #9 0x00007f1e120f624d #10 0x00007f1e120f610e #11 0x0000000000fed3be llvm::MCJIT::runFunction(llvm::Function*, llvm::ArrayRef<llvm::GenericValue>) (/usr/bin/swift+0xfed3be) #12 0x0000000000ff1882 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, char const* const*) (/usr/bin/swift+0xff1882) #13 0x00000000004d9076 swift::RunImmediately(swift::CompilerInstance&, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, swift::IRGenOptions&, swift:
import SwiftyMath let a = 𝐐(4, 5) // 4/5 let b = 𝐐(3, 2) // 3/2 print(a + b) // 23/10
Int(Double(Int.max))
<stdin>:1:1: warning: result of 'Int' initializer is unused Int(Double(Int.max)) ^ ~~~~~~~~~~~~~~~~~ Fatal error: Double value cannot be converted to Int because the result would be greater than Int.max Current stack trace: 0 libswiftCore.so 0x00007f5ca0e9ff30 _swift_stdlib_reportFatalError + 168 1 libswiftCore.so 0x00007f5ca0bf7c6a <unavailable> + 1502314 2 libswiftCore.so 0x00007f5ca0e3515e <unavailable> + 3850590 3 libswiftCore.so 0x00007f5ca0bf7c6a <unavailable> + 1502314 4 libswiftCore.so 0x00007f5ca0d90059 <unavailable> + 3174489 5 libswiftCore.so 0x00007f5ca0bf7730 _fatalErrorMessage(_:_:file:line:flags:) + 19 7 swift 0x0000000001042d2e <unavailable> + 12856622 8 swift 0x0000000001046e52 <unavailable> + 12873298 9 swift 0x00000000004f8b52 <unavailable> + 1018706 10 swift 0x00000000004df0cb <unavailable> + 913611 11 swift 0x00000000004da400 <unavailable> + 893952 12 swift 0x000000000048a348 <unavailable> + 566088 13 libc.so.6 0x00007f5ca3833740 __libc_start_main + 240 14 swift 0x0000000000488009 <unavailable> + 557065 #0 0x0000000004108b64 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x4108b64) #1 0x00000000041069f2 llvm::sys::RunSignalHandlers() (/usr/bin/swift+0x41069f2) #2 0x0000000004108d12 SignalHandler(int) (/usr/bin/swift+0x4108d12) #3 0x00007f5ca5109390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x00007f5ca0d90061 $Ss18_fatalErrorMessage__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtFTf4nnddn_n (/usr/lib/swift/linux/libswiftCore.so+0x307061) #5 0x00007f5ca0bf7743 $Ss18_fatalErrorMessage__4file4line5flagss5Ne
Int(Float(Int.max) * 2)
<stdin>:1:1: warning: result of 'Int' initializer is unused Int(Float(Int.max) * 2) ^ ~~~~~~~~~~~~~~~~~~~~ Fatal error: Float value cannot be converted to Int because the result would be greater than Int.max Current stack trace: 0 libswiftCore.so 0x00007fe934031f30 _swift_stdlib_reportFatalError + 168 1 libswiftCore.so 0x00007fe933d89c6a <unavailable> + 1502314 2 libswiftCore.so 0x00007fe933fc715e <unavailable> + 3850590 3 libswiftCore.so 0x00007fe933d89c6a <unavailable> + 1502314 4 libswiftCore.so 0x00007fe933f22059 <unavailable> + 3174489 5 libswiftCore.so 0x00007fe933d89730 _fatalErrorMessage(_:_:file:line:flags:) + 19 7 swift 0x0000000001042d2e <unavailable> + 12856622 8 swift 0x0000000001046e52 <unavailable> + 12873298 9 swift 0x00000000004f8b52 <unavailable> + 1018706 10 swift 0x00000000004df0cb <unavailable> + 913611 11 swift 0x00000000004da400 <unavailable> + 893952 12 swift 0x000000000048a348 <unavailable> + 566088 13 libc.so.6 0x00007fe9369c5740 __libc_start_main + 240 14 swift 0x0000000000488009 <unavailable> + 557065 #0 0x0000000004108b64 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x4108b64) #1 0x00000000041069f2 llvm::sys::RunSignalHandlers() (/usr/bin/swift+0x41069f2) #2 0x0000000004108d12 SignalHandler(int) (/usr/bin/swift+0x4108d12) #3 0x00007fe93829b390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x00007fe933f22061 $Ss18_fatalErrorMessage__4file4line5flagss5NeverOs12StaticStringV_A2HSus6UInt32VtFTf4nnddn_n (/usr/lib/swift/linux/libswiftCore.so+0x307061) #5 0x00007fe933d89743 $Ss18_fatalErrorMessage__4file4line5flag
print(Int(Float80(Int.max)))
(edited)print(Int(Double(Int.min)))
(edited)print(Int.min) print(Int(Double(Int.min)))
-9223372036854775808 -9223372036854775808
import Foundation print(String(format: "%x", Int.min))
(edited)// Kotlin fun main(args: Array<String>) { println(Long.MAX_VALUE) println(Long.MAX_VALUE.toDouble().toLong()) }
9223372036854775807 9223372036854775807
(edited)import Foundation print(String(format: "%lx", Int.min))
8000000000000000
0b10000....
ってパターンだから、import Foundation let x: Int128 = abs(Int128(Int.min)) print(String(format: "%llx", x))
<stdin>:2:8: error: use of undeclared type 'Int128' let x: Int128 = abs(Int128(Int.min)) ^~~~~~
Long
→ Int
とかと同じで上位ビット切り捨てかと思ってた。 (edited)Double のビット数考えればしょうがないか。
変換できないのが?クラッシュするのが?Int.min
だとクラッシュしないのが微妙ですね。丸め方向の偶然に挙動が委ねられてる感が。Int(exactly: Double(Int.max))
(edited)protocol P { func foo() -> Int } struct S: P { @_implements(P, foo()) func bar() -> Int { return 1 } }
struct X {} protocol P1 { associatedtype U } protocol P2: P1 {} extension P2 { @_implements(P1, U) typealias _Default_U = X } struct S<A>: P2 {} extension S where A: P1 { typealias U = A.U }
(edited)error type should not appear in IRGen UNREACHABLE executed at /home/buildnode/jenkins/workspace/oss-swift-4.2-package-linux-ubuntu-16_04/swift/lib/IRGen/MetadataRequest.cpp:1258! #0 0x000000000410afb4 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x410afb4) #1 0x0000000004108e42 llvm::sys::RunSignalHandlers() (/usr/bin/swift+0x4108e42) #2 0x000000000410b162 SignalHandler(int) (/usr/bin/swift+0x410b162) #3 0x00007f943313c390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x00007f943187b428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #5 0x00007f943187d02a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #6 0x00000000040a3f4d llvm::llvm_unreachable_internal(char const*, char const*, unsigned int) (/usr/bin/swift+0x40a3f4d) #7 0x0000000000631e17 swift::CanTypeVisitor<(anonymous namespace)::EmitTypeMetadataRef, swift::irgen::MetadataResponse, swift::irgen::DynamicMetadataRequest>::visit(swift::CanType, swift::irgen::DynamicMetadataRequest) (/usr/bin/swift+0x631e17) #8 0x0000000000634708 swift::irgen::MetadataResponse llvm::function_ref<swift::irgen::MetadataResponse (swift::irgen::IRGenFunction&, swift::irgen::DynamicMetadataRequest, llvm::Constant*)>::callback_fn<swift::irgen::getTypeMetadataAccessFunction(swift::irgen::IRGenModule&, swift::CanType, swift::ForDefinition_t)::$_2>(long, swift::irgen::IRGenFunction&, swift::irgen::DynamicMetadataRequest, llvm::Constant*) (/usr/bin/swift+0x634708) #9 0x0000000000634566 swift::irgen::MetadataResponse llvm::function_ref<swift::irgen::MetadataResponse (swift::irgen::IRGenFunction&, swift::irgen::Explosion&)>::callback_fn<swift::irgen::getTypeMetadataAccessFunction(swift::irgen::IRGenModule&, swift::CanType, swift::ForDefinition_t, llvm::function_ref<swift::irgen::MetadataResponse (swift::irgen::IRGenFunction&, swift::irgen::DynamicMetadataRequest, llvm::Constant*)>)::$_1>(long, swift::irgen::IRGenFunction&, swift::irgen::Explosion&) (/usr/bin/swift+0x634566) #10 0
(edited)error type should not appear in IRGen UNREACHABLE executed at /home/buildnode/jenkins/workspace/oss-swift-package-linux-ubuntu-16_04/swift/lib/IRGen/MetadataRequest.cpp:1230! Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOZlib/include -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio-ssl-93eb7dfa/Sources/CNIOOpenSSL/include -I /Libraries/.build/checkouts/crypto-36ec1aea/Sources/libbcrypt/include -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOLinux/include -I /Libraries/.build/checkouts/SwiftBacktrace-fcbf89ea/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace-fcbf89ea/Sources/Clibunwind/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOZlib.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOOpenSSL.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio-ssl-support-a3e27b6f/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/crypto-36ec1aea/Sources/libbcrypt/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown
var iterator = [1].enumerated().makeIterator() _ = iterator.next()
var a = AnyCollection([1,2,3]) let idxs = a.indices print(idxs)
DefaultIndices<AnyCollection<Int>>(_elements: Swift.AnyCollection<Swift.Int>(_box: Swift._RandomAccessCollectionBox<Swift.Array<Swift.Int>>), _startIndex: (), _endIndex: ())
stderr:warning: the Swift runtime was unable to demangle the type of field '_startIndex'. the mangled type name is '5IndexSlQz'. this field will show up as an empty tuple in Mirrors warning: the Swift runtime was unable to demangle the type of field '_endIndex'. the mangled type name is '5IndexSlQz'. this field will show up as an empty tuple in Mirrors
protocol P {} extension P { typealias Concrete = S } struct S : P {} let a: P = .Concrete.self print(a)
swift: /home/buildnode/jenkins/workspace/oss-swift-4.2-package-linux-ubuntu-16_04/llvm/include/llvm/Support/Casting.h:255: typename cast_retty<X, Y *>::ret_type llvm::cast(Y *) [X = swift::MetatypeType, Y = swift::TypeBase]: Assertion `isa<X>(Val) && "cast<Ty>() argument of incompatible type!"' failed. #0 0x000000000410b054 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x410b054) #1 0x0000000004108ee2 llvm::sys::RunSignalHandlers() (/usr/bin/swift+0x4108ee2) #2 0x000000000410b202 SignalHandler(int) (/usr/bin/swift+0x410b202) #3 0x00007f045adde390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x00007f045951d428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #5 0x00007f045951f02a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #6 0x00007f0459515bd7 (/lib/x86_64-linux-gnu/libc.so.6+0x2dbd7) #7 0x00007f0459515c82 (/lib/x86_64-linux-gnu/libc.so.6+0x2dc82) #8 0x0000000000c7225a swift::Lowering::SILGenBuilder::createMetatype(swift::SILLocation, swift::SILType) (/usr/bin/swift+0xc7225a) #9 0x0000000000cafec9 swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) (/usr/bin/swift+0xcafec9) #10 0x0000000000ca2c28 swift::Lowering::SILGenFunction::emitRValueAsSingleValue(swift::Expr*, swift::Lowering::SGFContext) (/usr/bin/swift+0xca2c28) #11 0x0000000000cbdfdf swift::Lowering::ManagedValue llvm::function_ref<swift::Lowering::ManagedValue (swift::Lowering::SGFContext)>::callback_fn<(anonymous namespace)::RValueEmitter::visitErasureExpr(swift::ErasureExpr*, swift::Lowering::SGFContext)::$_8>(long, swift::Lowering::SGFContext) (/usr/bin/swift+0xcbdfdf) #12 0x0000000000c8a59a std::_Function_handler<void (swift::SILValue), swift::Lowering::SILGenFunction::emitExistentialErasure(swift::SILLocation, swift::CanType, swift::Lowering::TypeLowering const&, swift::Lowering::TypeLowering const&,
<stdin>:7:13: error: type of expression is ambiguous without more context let a: P = .Concrete.self ~^~~~~~~~
protocol P {} extension P { typealias Concrete = S } struct S : P {} let a: P = .Concrete() print(a)
<stdin>:7:13: error: member 'Concrete' is not a function let a: P = .Concrete() ^ ~~
protocol Hoge { associatedtype Fuga func piyo(_ index: Int) -> Fuga } extension Array: Hoge where Element == String { typealias Fuga = String func piyo(_ index: Int) -> Fuga { return self[index] } } extension Array: Hoge where Element == Int { typealias Fuga = Int func piyo(_ index: Int) -> Fuga { return self[index] } }
(edited)<stdin>:15:13: error: invalid redeclaration of 'Fuga' typealias Fuga = Int ^ <stdin>:8:13: note: 'Fuga' previously declared here typealias Fuga = String ^ <stdin>:9:30: error: 'Fuga' is ambiguous for type lookup in this context func piyo(_ index: Int) -> Fuga { ^~~~ <stdin>:8:13: note: found this candidate typealias Fuga = String ^ <stdin>:15:13: note: found this candidate typealias Fuga = Int ^ <stdin>:16:30: error: 'Fuga' is ambiguous for type lookup in this context func piyo(_ index: Int) -> Fuga { ^~~~ <stdin>:8:13: note: found this candidate typealias Fuga = String ^ <stdin>:15:13: note: found this candidate typealias Fuga = Int ^ <stdin>:7:1: error: type 'Array<Element>' does not conform to protocol 'Hoge' extension Array: Hoge where Element == String { ^ <stdin>:2:18: note: multiple matching types named 'Fuga' associatedtype Fuga ^ <stdin>:8:13: note: possibly intended match typealias Fuga = String ^ <stdin>:15:13: note: possibly intended match typealias Fuga = Int ^ <stdin>:14:18: error: conflicting conformance of 'Array<Element>' to protocol 'Hoge'; there cannot be more than one conformance, even with different conditional bounds extension Array: Hoge where Element == Int { ^ <stdin>:7:1: note: 'Array<Element>' declares conformance to protocol 'Hoge' here extension Array: Hoge where Element == String { ^
(edited)protocol Hoge { associatedtype Fuga func piyo(_ index: Int) -> Fuga } extension Array: Hoge where Element == String { typealias Fuga = String func piyo(_ index: Int) -> String { return self[index] + "でーす" } } extension Array: Hoge where Element == Int { typealias Fuga = Int func piyo(_ index: Int) -> Int { return self[index] + 10 } }
<stdin>:15:13: error: invalid redeclaration of 'Fuga' typealias Fuga = Int ^ <stdin>:8:13: note: 'Fuga' previously declared here typealias Fuga = String ^ <stdin>:7:1: error: type 'Array<Element>' does not conform to protocol 'Hoge' extension Array: Hoge where Element == String { ^ <stdin>:2:18: note: multiple matching types named 'Fuga' associatedtype Fuga ^ <stdin>:8:13: note: possibly intended match typealias Fuga = String ^ <stdin>:15:13: note: possibly intended match typealias Fuga = Int ^ <stdin>:14:18: error: conflicting conformance of 'Array<Element>' to protocol 'Hoge'; there cannot be more than one conformance, even with different conditional bounds extension Array: Hoge where Element == Int { ^ <stdin>:7:1: note: 'Array<Element>' declares conformance to protocol 'Hoge' here extension Array: Hoge where Element == String { ^
class Animal {} class Cat<T>: Animal {} func foo(_: Animal) { print("Animal") } func foo<T>(_: Cat<T>) { print("Cat") } let cat = Cat<Int>() :constraints debug on foo(cat)
Stack dump: 0. Program arguments: swift -frontend -I /Libraries/.build/x86_64-unknown-linux/debug -L /Libraries/.build/x86_64-unknown-linux/debug -lLibraries -DDEBUG -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOZlib.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOZlib/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOHTTPParser/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOOpenSSL.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio-ssl-93eb7dfa/Sources/CNIOOpenSSL/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CCryptoOpenSSL.build/module.modulemap -I /Libraries/.build/checkouts/crypto-36ec1aea/Sources/CCryptoOpenSSL/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/crypto-36ec1aea/Sources/CBcrypt/include/module.modulemap -I /Libraries/.build/checkouts/crypto-36ec1aea/Sources/CBcrypt/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/crypto-36ec1aea/Sources/CBase32/include/module.modulemap -I /Libraries/.build/checkouts/crypto-36ec1aea/Sources/CBase32/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio-ssl-support-a3e27b6f/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOSHA1/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOAtomics/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIODarwin/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinu
1. while processing REPL source: class Animal {} [0mLLVMSymbolizer: error reading file: No such file or directory. LLVMSymbolizer: error reading file: No such file or directory. LLVMSymbolizer: error reading file: No such file or directory. #0 0x000000000459a4b4 (swift+0x459a4b4) #1 0x0000000004598280 (swift+0x4598280) #2 0x000000000459a662 (swift+0x459a662) #3 0x00007f494a31e390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x00007f494a74e000
class Animal {} class Cat<T>: Animal {} func foo(_: Animal) { print("Animal") } func foo<T>(_: Cat<T>) { print("Cat") } let cat = Cat<Int>() :constraints debug on foo(cat)
(edited)// cat : Cat<Int> = REPL.Cat<Swift.Int> Animal
stderr:---Constraint solving for the expression at [<REPL Input>:1:1 - line:1:8]--- (overload set choice binding $T1 := Cat<Int>) ---Initial constraints for the given expression--- (call_expr type='()' location=<REPL Input>:1:1 range=[<REPL Input>:1:1 - line:1:8] arg_labels=_: (overloaded_decl_ref_expr type='$T0' location=<REPL Input>:1:1 range=[<REPL Input>:1:1 - line:1:1] name=foo number_of_decls=2 function_ref=single decls=[ REPL.(file).foo@<REPL Input>:1:6, REPL.(file).foo@<REPL Input>:1:6]) (paren_expr type='(Cat<Int>)' location=<REPL Input>:1:5 range=[<REPL Input>:1:4 - line:1:8] (declref_expr type='Cat<Int>' location=<REPL Input>:1:5 range=[<REPL Input>:1:5 - line:1:5] decl=REPL.(file).cat@<REPL Input>:1:5 direct_to_storage function_ref=unapplied))) Score: 0 0 0 0 0 0 0 0 0 0 0 Type Variables: $T0 [lvalue allowed] subtype_of_existential involves_type_vars bindings={} @ locator@0x81d2e10 [OverloadedDeclRef@<REPL Input>:1:1] $T1 [lvalue allowed] as Cat<Int> @ locator@0x81d2f60 [DeclRef@<REPL Input>:1:5] Active Constraints: Inactive Constraints: disjunction [[locator@0x81d2e10 [OverloadedDeclRef@<REPL Input>:1:1]]]:$T0 bound to decl REPL.(file).foo@<REPL Input>:1:6 : (Animal) -> () at <REPL Input>:1:6 [[locator@0x81d2e10 [OverloadedDeclRef@<REPL Input>:1:1]]]; or $T0 bound to decl REPL.(file).foo@<REPL Input>:1:6 : <T> (Cat<T>) -> () at <REPL Input>:1:6 [[locator@0x81d2e10 [OverloadedDeclRef@<REPL Input>:1:1]]]; (Cat<Int>) -> () applicable fn $T0 [[locator@0x81d2fe0 [Call@<REPL Input>:1:1 -> apply function]]]; Resolved overloads: selected overload set choice cat: $T1 == Cat<Int> (assuming $T0 bound to decl REPL.(file).foo@<REPL Input>:1:6 : (Animal) -> () at <REPL Input>:1:6 [[locator@0x81d2e10 [OverloadedDeclRef@<REPL Input>:1:1]]]; (overload set choice binding $T0 := (Animal) -> ()) (found solution 0 0 0 0 0 0 0 0 0 0 0) ) (assuming $T0 bound to decl REPL.(file).
(edited)var f: (() -> Void)? class Cat { deinit { f?() } } func main() { let cat = Cat() f = { [weak cat] in print(cat == nil) // true } } main()
(edited)error: unable to invoke subcommand: /usr/bin/swift-
swift (No such file or directory) ```var f: (() -> Void)? class Cat { deinit { f?() } } func main() { let cat = Cat() f = { [weak cat] in print(cat == nil) // true } } main()
class A { typealias Aliased = String } class B : A { typealias Aliased = Double } let str: String.Type = B.Aliased.self let dbl: Double.Type = B.Aliased.self print(str) print(dbl)
class A { typealias Aliased = String } class B : A { typealias Aliased = Double } let str: String.Type = B.Aliased.self let dbl: Double.Type = B.Aliased.self print(str) print(dbl)
swift-4.1.1-RELEASE
String Double
B.Aliased
という式でオーバーロード?されてる?B.Aliased
を型推論させると当然のように Double
に解決されるんですけどね。class A { typealias Aliased = String } class B : A { typealias Aliased = Double } let a: A.Type = B.self print(a.Aliased.self)
class A { typealias Aliased = String } class B : A { typealias Aliased = Double } let a: A.Type = B.self print(a.Aliased.self)
swift-4.1.1-RELEASE
String
protocol P { static var Aliased: String.Type { get } } extension P { static var Aliased: String.Type { return String.self } } class A: P {} class B: A { static var Aliased: Double.Type { return Double.self } } let str: String.Type = B.Aliased.self let dbl: Double.Type = B.Aliased.self print(str) print(dbl)
String Double
protocol P { static var value: Int { get } } extension P { static var value: Int { return 3 } } protocol Q { static var value: Bool { get } } extension Q { static var value: Bool { return true } } class A : P { } class B : A, Q { } class C : B { static var value: String = "str" } let a: Int = C.value let b: Bool = C.value let c: String = C.value print(a, b, c)
protocol P { var a: Int { get } } extension P { var a: Int { return 42 } } protocol Q { var a: Bool { get } } extension Q { var a: Bool { return true } } struct S: P, Q {} let s = S() let x: Int = s.a let y: Bool = s.a print(x) print(y)
subscript
もできるんだし。protocol P { var a: Int { get set } } extension P { var a: Int { get { return 42 } set {} } } protocol Q { var a: Bool { get set } } extension Q { var a: Bool { get { return true } set {} } } struct S: P, Q {} var s = S() s.a = true as Bool
(edited)struct RGBA<Channel> { var red: Channel var green: Channel var blue: Channel var alpha: Channel } let rgbaArray = [RGBA(red: 255, green: 127, blue: 0, alpha: 255)] rgbaArray.withUnsafeBufferPointer { rgbaPointer in print(rgbaPointer[0]) rgbaPointer.withMemoryRebound(to: UInt8.self) { uint8Pointer in print(uint8Pointer[0]) } }
(edited)struct RGBA<Channel> { var red: Channel var green: Channel var blue: Channel var alpha: Channel } let rgbaArray = [RGBA(red: 255, green: 127, blue: 0, alpha: 255)] rgbaArray.withUnsafeBufferPointer { rgbaPointer in print(rgbaPointer[0]) rgbaPointer.withMemoryRebound(to: UInt8.self) { uint8Pointer in print(uint8Pointer[0]) } }
swift-4.1.1-RELEASE
Fatal error: Current stack trace: 0 libswiftCore.so 0x00007f1674d19750 _swift_stdlib_reportFatalError + 171 1 libswiftCore.so 0x00007f1674a87ad6 <unavailable> + 1366742 2 libswiftCore.so 0x00007f1674cc2383 <unavailable> + 3703683 3 libswiftCore.so 0x00007f1674a87ad6 <unavailable> + 1366742 4 libswiftCore.so 0x00007f1674bf3d80 <unavailable> + 2858368 5 libswiftCore.so 0x00007f1674bbbded <unavailable> + 2629101 6 libswiftCore.so 0x00007f1674bbbc20 UnsafeBufferPointer.withMemoryRebound<A, B>(to:_:) + 42 10 libswiftCore.so 0x00007f1674a81e30 Array.withUnsafeBufferPointer<A>(_:) + 172 12 swift 0x0000000000fed1ce <unavailable> + 12505550 13 swift 0x0000000000ff1692 <unavailable> + 12523154 ...
RGBA<Int>(red: 255, green: 127, blue: 0, alpha: 255) 255
print("hello")
struct Stone { var x: Int { get { return 1 } _modify { var x: Int = 3 yield &x y = x } } var y: Int = 0 } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) print(a.y) } main()
<stdin>:7:9: error: expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition _modify { ^ <stdin>:23:9: error: cannot pass immutable value as inout argument: 'x' is a get-only property mod(&a.x) ^~~~
struct Stone { var x: Int { get { return 1 } _modify { var x: Int = 3 yield &x y = x } } var y: Int = 0 } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) print(a.y) } main()
print("hello world")
(edited)import Foundation import SwiftBacktrace enablePrettyStackTrace() let group = DispatchGroup() var array = [Int]() DispatchQueue.global().async(group: group) { for i in 0...1000000 { array.append(i) } print("end 1: \(array.count)") } DispatchQueue.global().async(group: group) { for i in 0...1000000 { array.append(i) } print("end 2: \(array.count)") } group.wait()
/Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(callStackSymbols<A>(_:transform:)+0x9f) [0x00007ff40d7e71bf] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(backtrace(_:formatter:)+0x102) [0x00007ff40d7e6cd2] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(closure #1 in closure #1 in variable initialization expression of _enablePrettyStackTrace+0x2f) [0x00007ff40d7ebc5f] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(runSignalHandlers()+0x34d) [0x00007ff40d7edbcd] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(signalHandler(signal:)+0x1c4) [0x00007ff40d7ed3a4] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(@objc signalHandler(signal:)+0x9) [0x00007ff40d7ed1d9] /lib/x86_64-linux-gnu/libpthread.so.0(__restore_rt+0x0) [0x00007ff4150c5390] /lib/x86_64-linux-gnu/libc.so.6(strerror_l+0x500) [0x00007ff41386e870] /usr/lib/swift/linux/libswiftSwiftOnoneSupport.so(specialized _ArrayBufferProtocol._arrayOutOfPlaceUpdate<A>(_:_:_:_:)+0x16d) [0x00007ff40cd688cd] /usr/lib/swift/linux/libswiftSwiftOnoneSupport.so(specialized Array._copyToNewBuffer(oldCount:)+0x3f) [0x00007ff40cd5fbef] /usr/lib/swift/linux/libswiftSwiftOnoneSupport.so(specialized Array._copyToNewBuffer(oldCount:)+0x25) [0x00007ff40cd5ffa5] /usr/lib/swift/linux/libswiftSwiftOnoneSupport.so(specialized Array.append(_:)+0x78) [0x00007ff40cd5e7c8] /usr/lib/swift/linux/libswiftSwiftOnoneSupport.so(specialized Array.append(_:)+0x10) [0x00007ff40cd5e740] -(+0x0) [0x00007ff4154f57b8] -(+0x0) [0x00007ff4154f55f7] /usr/lib/swift/linux/libdispatch.so(_dispatch_call_block_and_release+0x7) [0x00007ff40cfd48c7] -(+0x0) [0x00007ff4154f57ae]#0 0x000000000410b054 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x410b054) #1 0x0000000004108ee2 llvm::sys::RunSignalHandlers() (/usr/bin/swift+0x4108ee2) #2 0x000000000410b202 SignalHandler(int) (/usr/bin/swift+0x410b202) #3 0x00007ff4150c5390 __restore_rt (/lib/x86_64-
Fatal error: UnsafeMutablePointer.deinitialize with negative count Current stack trace: 0 libswiftCore.so 0x00007f166750b810 _swift_stdlib_reportFatalError + 171 1 libswiftCore.so 0x00007f1667279a86 <unavailable> + 1366662 2 libswiftCore.so 0x00007f16674b4453 <unavailable> + 3703891 3 libswiftCore.so 0x00007f1667279a86 <unavailable> + 1366662 4 libswiftCore.so 0x00007f16673e5ec0 <unavailable> + 2858688 5 libswiftCore.so 0x00007f1667279660 _fatalErrorMessage(_:_:file:line:flags:) + 19 6 libswiftSwiftOnoneSupport.so 0x00007f1664062fda <unavailable> + 163802 7 libswiftSwiftOnoneSupport.so 0x00007f1664058166 <unavailable> + 119142 8 libswiftSwiftOnoneSupport.so 0x00007f1664058100 specialized Array._copyToNewBuffer(oldCount:) + 23 9 libswiftSwiftOnoneSupport.so 0x00007f16640551a2 <unavailable> + 106914 10 libswiftSwiftOnoneSupport.so 0x00007f16640553f0 specialized Array.append(_:) + 16 13 libdispatch.so 0x00007f1663fed977 <unavailable> + 301431 14 libdispatch.so 0x00007f1663ffcd33 <unavailable> + 363827 15 libpthread.so.0 0x00007f166c5626ba <unavailable> + 30394 16 libc.so.6 0x00007f166ad7d3b0 clone + 109 /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(callStackSymbols<A>(_:transform:)+0x87) [0x00007f1664a969c7] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(backtrace(_:formatter:)+0xd8) [0x00007f1664a962d8] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(closure #1 in closure #1 in variable initialization expression of _enablePrettyStackTrace+0x27) [0x00007f1664a90fe7] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.so(runSignalHandlers()+0x324) [0x00007f1664a92e04] /Libraries/.build/x86_64-unknown-linux/debug/libLibraries.s
// @escaping だけど同期的にクロージャが実行されるだけの関数 func run(_ body: @escaping () -> Void) { body() } // 値型を非同期的に更新するための機能を提供 struct Updater<Object: AnyObject, Target> { let object: Object let keyPath: ReferenceWritableKeyPath<Object, Target> func update(_ body: (inout Target) throws -> Void) rethrows { try body(&object[keyPath: keyPath]) } } // 値型、これの状態を @escaping をまたいで更新したい struct FooState { var a: Int = 0 mutating func incrementA<Object: AnyObject>(with updater: Updater<Object, FooState>) { run { // @escaping なのでこの中では `self` を更新できない updater.update { state in // Updater を使って更新 state.a += 1 } } } } // FooState を保持する参照型 class Foo { var state: FooState = FooState() func bar() { state.incrementA(with: Updater<Foo, FooState>(object: self, keyPath: \Foo.state)) } } let foo = Foo() foo.bar() print(foo.state.a)
Simultaneous accesses to 0x7e0f7e0, but modification requires exclusive access. Previous access (a modification) started at (0x7f4374754523). Current access (a read) started at: 0 libswiftCore.so 0x00007f437005a950 swift_beginAccess + 521 3 libswiftCore.so 0x00007f436ffff1e8 <unavailable> + 3588584 4 libswiftCore.so 0x00007f436feef4a1 <unavailable> + 2475169 5 libswiftCore.so 0x00007f436feef05d <unavailable> + 2474077 6 libswiftCore.so 0x00007f436fef1600 _projectKeyPathReferenceWritable<A, B>(root:keyPath:) + 155 14 swift 0x0000000001043efe <unavailable> + 12861182 15 swift 0x0000000001048022 <unavailable> + 12877858 16 swift 0x00000000004f8b42 <unavailable> + 1018690 17 swift 0x00000000004df0bb <unavailable> + 913595 18 swift 0x00000000004da3f0 <unavailable> + 893936 19 swift 0x000000000048a348 <unavailable> + 566088 20 libc.so.6 0x00007f4372a4e740 __libc_start_main + 240 21 swift 0x0000000000488009 <unavailable> + 557065 Fatal access conflict detected. #0 0x000000000410b054 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x410b054) #1 0x0000000004108ee2 llvm::sys::RunSignalHandlers() (/usr/bin/swift+0x4108ee2) #2 0x000000000410b202 SignalHandler(int) (/usr/bin/swift+0x410b202) #3 0x00007f4374324390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x00007f4372a63428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #5 0x00007f4372a6502a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #6 0x00007f437005a742 (/usr/lib/swift/linux/libswiftCore.so+0x3c7742) #7 0x00007f437005ac38 (/usr/lib/swift/linux/libswiftCore.so+0x3c7c38) #8 0x00007f43747543d9 #9 0x00007f43747549c
Swift version 4.2.1 (swift-4.2.1-RELEASE) Target: x86_64-unknown-linux-gnu
protocol A { associatedtype ARelated } protocol B: A { associatedtype BRelated: Codable } extension B where Self.ARelated: Codable { typealias BRelated = Self.ARelated } struct AImpl: A, B { typealias BRelated = ARelated struct ARelated: Codable { let val: Int } }
(edited)import Foundation print(String(format: "%@", "hello" as NSString))
(edited)<stdin>:3:36: error: argument type 'NSString' does not conform to expected type 'CVarArg' print(String(format: "%@", "hello" as NSString)) ~~~~~~~~^~~~~~~~~~~ as! CVarArg
(edited)swift-DEVELOPMENT-SNAPSHOT-2018-11-13-a
でビルドできなくなった。swift-DEVELOPMENT-SNAPSHOT-2018-11-14-a
で久しぶりにCI通ったけど、ボットとして動かなかったのでswift-DEVELOPMENT-SNAPSHOT-2018-10-03-a
までロールバック。import Foundation class Cat { @objc func nya() -> Int { return 3 } } class Dog { @objc func wan() -> Int { return 4 } } func f(_ a: AnyObject) { let x = a.nya() let y = a.wan?() print(type(of: x), x) // Int 3 print(type(of: y), y) // Optional<Int> nil } f(Cat())
<stdin>:15:24: warning: expression implicitly coerced from 'Int?' to 'Any' print(type(of: y), y) // Optional<Int> nil ^ <stdin>:15:24: note: provide a default value to avoid this warning print(type(of: y), y) // Optional<Int> nil ^ ?? <#default value#> <stdin>:15:24: note: force-unwrap the value to avoid this warning print(type(of: y), y) // Optional<Int> nil ^ ! <stdin>:15:24: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(type(of: y), y) // Optional<Int> nil ^ as Any <unknown>:0: error: fatal error encountered during compilation; please file a bug report with your project and the crash log <unknown>:0: note: Program used external function 'sel_registerName' which could not be resolved! #0 0x000000000410ac94 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x410ac94) #1 0x0000000004108b22 llvm::sys::RunSignalHandlers() (/usr/bin/swift+0x4108b22) #2 0x000000000410ae42 SignalHandler(int) (/usr/bin/swift+0x410ae42) #3 0x00007fddc4398390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x00007fddc2ad7428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #5 0x00007fddc2ad902a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #6 0x00000000004dfb25 (/usr/bin/swift+0x4dfb25) #7 0x00000000040a35ff llvm::report_fatal_error(llvm::Twine const&, bool) (/usr/bin/swift+0x40a35ff) #8 0x000000000105591b llvm::RuntimeDyldImpl::resolveExternalSymbols() (/usr/bin/swift+0x105591b) #9 0x00000000010542e6 llvm::RuntimeDyldImpl::resolveRelocations() (/usr/bin/swift+0x10542e6) #10 0x0000000001041fcd llvm::MCJIT::finalizeObject() (/usr/bin/swift+0x1041fcd) #11 0x00000000004f88de swift::RunImmediately(swift::CompilerInstance&, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<st
import Foundation class Cat { @objc func nya() -> Int { return 3 } } class Dog { @objc func wan() -> Int { return 4 } } func f(_ a: AnyObject) { let x = a.nya() let y = a.wan?() print(type(of: x), x) // Int 3 print(type(of: y), y) // Optional<Int> nil }
(edited)<stdin>:15:24: warning: expression implicitly coerced from 'Int?' to 'Any' print(type(of: y), y) // Optional<Int> nil ^ <stdin>:15:24: note: provide a default value to avoid this warning print(type(of: y), y) // Optional<Int> nil ^ ?? <#default value#> <stdin>:15:24: note: force-unwrap the value to avoid this warning print(type(of: y), y) // Optional<Int> nil ^ ! <stdin>:15:24: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(type(of: y), y) // Optional<Int> nil ^ as Any
(edited)import Foundation try! JSONDecoder().decode([Int].self, from: "".data(using: .utf8)!)
(edited)<stdin>:2:6: error: use of unresolved identifier 'JSONDecoder' try! JSONDecoder().decode([Int].self, from: "".data(using: .utf8)!) ^~~~~~~~~~~
import Foundation do { _ = try JSONDecoder().decode([Int].self, from: "".data(using: .utf8)!) } catch let error { print(error) }
⚠️ [DecodingError.dataCorrupted: The given data was not valid JSON.]
#if swift(>=4.2.1) print("4.2.1") #elseif swift(>=4.2) print("4.2") #endif
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
DEVELOPMENT-SNAPSHOT-2018-12-07-a
5.0-DEVELOPMENT-SNAPSHOT-2018-12-07-a
import Foundation // column 1 2 3 4 5 6 7 8 9 10 11 // line 1 L I N E 1 _ 6 7 あ \n // line 2 L I N E 2 _ 7 8 9 0 \n // line 3 L I N E 3 _ 8 9 0 1 \n let string = "LINE1_67あ\nLINE2_7890\nLINE3_8901\n" let rangeOfFirstLine = string.lineRange(for: string.startIndex..<string.startIndex) let firstLine = string[rangeOfFirstLine] print(string.distance(from: rangeOfFirstLine.lowerBound, to: rangeOfFirstLine.upperBound)) print(firstLine == "LINE1_67あ\n")
Fatal error: String index is out of bounds Current stack trace: 0 libswiftCore.so 0x00007f2fb98a75e0 _swift_stdlib_reportFatalError + 69 1 libswiftCore.so 0x00007f2fb97ac1b6 <unavailable> + 3125686 2 libswiftCore.so 0x00007f2fb97ac535 <unavailable> + 3126581 3 libswiftCore.so 0x00007f2fb97b1a39 <unavailable> + 3148345 4 libswiftCore.so 0x00007f2fb97b518b <unavailable> + 3162507 5 libswiftCore.so 0x00007f2fb983a050 String.distance(from:to:) + 9 7 swift 0x0000000000cee8be <unavailable> + 9365694 8 swift 0x0000000000cf2ad2 <unavailable> + 9382610 9 swift 0x000000000051612f <unavailable> + 1138991 10 swift 0x00000000004eafb5 <unavailable> + 962485 11 swift 0x00000000004e6456 <unavailable> + 943190 12 swift 0x000000000048d88e <unavailable> + 579726 13 libc.so.6 0x00007f2fbc4c9740 __libc_start_main + 240 14 swift 0x000000000048b6c9 <unavailable> + 571081 Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOZlib/include -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio-ssl-93eb7dfa/Sources/CNIOOpenSSL/include -I /Libraries/.build/checkouts/crypto-36ec1aea/Sources/CCryptoOpenSSL/include -I /Libraries/.build/checkouts/crypto-36ec1aea/Sources/CBcrypt/include -I /Libraries/.build/checkouts/crypto-36ec1aea/Sources/CBase32/include -I /Libraries/.build/checkouts/swift-nio-b68c973e/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio-b68c973e/S
let rain = #"The "rain" in "Spain" falls mainly on the Spaniards."# print(rain)
The "rain" in "Spain" falls mainly on the Spaniards.
let keypaths = #"Swift keypaths such as \Person.name hold uninvoked references to properties."# print(keypaths)
Swift keypaths such as \Person.name hold uninvoked references to properties.
let answer = 42 let dontpanic = #"The answer to life, the universe, and everything is \#(answer)."# print(dontpanic)
The answer to life, the universe, and everything is 42.
let str = ##"My dog said "woof"#gooddog"## print(str)
My dog said "woof"#gooddog
let answer = 42 let multiline = #""" The answer to life, the universe, and everything is \#(answer). """# print(multiline)
(edited)let answer = 42 let multiline = #""" The answer to life, the universe, and everything is \#(answer). """# print(multiline)
The answer to life, the universe, and everything is 42.
let regex2 = #"\\[A-Z]+[A-Za-z]+\.[a-z]+"# print(regex2)
\\[A-Z]+[A-Za-z]+\.[a-z]+
let times = [ "Hudson": "38", "Clarke": "42", "Robinson": "35", "Hartis": "DNF" ] let finishers1 = times.compactMapValues { Int($0) } let finishers2 = times.compactMapValues(Int.init) print(finishers1) print(finishers2)
["Robinson": 35, "Hudson": 38, "Clarke": 42] ["Hudson": 38, "Clarke": 42, "Robinson": 35]
let times = [ "Hudson": "38", "Clarke": "42", "Robinson": "35", "Hartis": "DNF" ] let finishers1 = times.compactMapValues { Int($0) } let finishers2 = times.compactMapValues(Int.init) print(finishers1) print(finishers2)
["Hudson": 38, "Clarke": 42, "Robinson": 35] ["Hudson": 38, "Robinson": 35, "Clarke": 42]
let times1 = [ "Hudson": "38", "Clarke": "42", "Robinson": "35", "Hartis": "DNF" ] print(times1) let times2 = [ "Hudson": "38", "Clarke": "42", "Robinson": "35", "Hartis": "DNF" ] print(times2)
["Hartis": "DNF", "Hudson": "38", "Clarke": "42", "Robinson": "35"] ["Robinson": "35", "Hudson": "38", "Clarke": "42", "Hartis": "DNF"]
let scores = [100, 80, 85] let passCount = scores.count { $0 >= 85 } print(passCount)
(edited)print(3.isMultiple(of: 3))
(edited):print_decl Result
@_frozen enum Result<Success, Failure> where Failure : Error { case success(Success) case failure(Failure) func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> Result<NewSuccess, Failure> func mapError<NewFailure>(_ transform: (Failure) -> NewFailure) -> Result<Success, NewFailure> where NewFailure : Error func flatMap<NewSuccess>(_ transform: (Success) -> Result<NewSuccess, Failure>) -> Result<NewSuccess, Failure> func flatMapError<NewFailure>(_ transform: (Failure) -> Result<Success, NewFailure>) -> Result<Success, NewFailure> where NewFailure : Error func get() throws -> Success } extension Result where Failure == Error { init(catching body: () throws -> Success) } extension Result : Equatable where Success : Equatable, Failure : Equatable { static func == (a: Result<Success, Failure>, b: Result<Success, Failure>) -> Bool } extension Result : Hashable where Success : Hashable, Failure : Hashable { var hashValue: Int { get } func hash(into hasher: inout Hasher) }
Swifrt5のproposalを総ナメしてて、荒らしみたいになってるw
問題ないかと。どうしても気になるなら、ダイレクトメッセージをボットに送るとよいです。func doubleOptionalInt() throws -> Int?? { return 3 } let x = try? doubleOptionalInt() print(x as Any)
(edited)enum Result<Value, Error> { case success(Value) case failure(Error) } extension Result: Equatable where Value: Equatable, Error: Equatable { static func == (lhs: Result, rhs: Result) -> Bool { switch (lhs, rhs) { case let (.success(lhs), .success(rhs)): return lhs == rhs case let (.failure(lhs), .failure(rhs)): return lhs == rhs case (.success, .failure), (.failure, .success): return false } } } extension Result: Hashable where Value: Hashable, Error: Hashable { var hashValue: Int { switch self { case let .success(value): return value.hashValue case let .failure(error): return error.hashValue } } } let foo = Result<Int, Never>.success(1) let bar = Result<Int, Never>.success(1) print(foo == bar)
(edited)<stdin>:33:11: error: type 'Never' does not conform to protocol 'Equatable' print(foo == bar) ^ <stdin>:33:11: error: '<Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool' requires that 'Never' conform to 'Equatable' print(foo == bar) ^ <stdin>:33:11: note: requirement specified as 'Never' : 'Equatable' print(foo == bar) ^ <stdin>:33:11: note: requirement from conditional conformance of 'Result<Int, Never>' to 'Equatable' print(foo == bar) ^
(edited)print(DictionaryLiteral<String, String>(dictionaryLiteral: ("hoge", "fuga")))
(edited)DictionaryLiteral<String, String>(_elements: [("hoge", "fuga")])
(edited)print(KeyValuePairs<String, String>(dictionaryLiteral: ("hoge", "fuga")))
(edited)print(DictionaryLiteral<String, String>(dictionaryLiteral: ("hoge", "fuga")))
["hoge": "fuga"]
stderr:<stdin>:2:7: warning: 'DictionaryLiteral' is deprecated: renamed to 'KeyValuePairs' print(DictionaryLiteral<String, String>(dictionaryLiteral: ("hoge", "fuga"))) ^ <stdin>:2:7: note: use 'KeyValuePairs' instead print(DictionaryLiteral<String, String>(dictionaryLiteral: ("hoge", "fuga"))) ^~~~~~~~~~~~~~~~~ KeyValuePairs
#if swift(<5.1) print("OK") #endif #if compiler(<5.1) print("OK") #endif
<stdin>:2:11: error: unexpected platform condition argument: expected a unary comparison, such as '>=2.2' #if swift(<5.1) ^ <stdin>:6:15: error: unexpected platform condition argument: expected a unary comparison, such as '>=2.2' #if compiler(<5.1) ^
var x = 1 x.self = 2 print(x.self) // prints 2 let id = \Int.self x[keyPath: id] = 3 print(x[keyPath: id]) // prints 3
(edited)<stdin>:6:11: error: invalid component of Swift key path let id = \Int.self ^ <stdin>:6:10: error: expression type 'WritableKeyPath<_, _>' is ambiguous without more context let id = \Int.self ^~~~~~~~~
(edited)// Example 1: // Users expect `0xffff_ffff_ffff_ffff` to be coerced to type `UInt`. print(UInt(0xffff_ffff_ffff_ffff as UInt)) print(UInt(0xffff_ffff_ffff_ffff))
(edited)<stdin>:6:12: error: integer literal '18446744073709551615' overflows when stored into 'Int' print(UInt(0xffff_ffff_ffff_ffff)) ^
(edited)import Foundation if [1] == [1] { print("OK") }
(edited)<stdin>:4:8: error: ambiguous use of operator '==' if [1] == [1] { ^ Foundation.IndexPath:28:24: note: found this candidate public static func == (lhs: Foundation.IndexPath, rhs: Foundation.IndexPath) -> Bool ^ Foundation.IndexSet:2:24: note: found this candidate public static func == (lhs: Foundation.IndexSet, rhs: Foundation.IndexSet) -> Bool ^
<stdin>:4:8: error: ambiguous use of operator '==' if [1] == [1] { ^ Foundation.IndexPath:28:24: note: found this candidate public static func == (lhs: Foundation.IndexPath, rhs: Foundation.IndexPath) -> Bool ^ Foundation.IndexSet:2:24: note: found this candidate public static func == (lhs: Foundation.IndexSet, rhs: Foundation.IndexSet) -> Bool ^
<stdin>:4:8: error: ambiguous use of operator '==' if [1] == [1] { ^ Foundation.IndexPath:46:24: note: found this candidate public static func ==(lhs: Foundation.IndexPath, rhs: Foundation.IndexPath) -> Bool ^ Foundation.IndexSet:2:24: note: found this candidate public static func ==(lhs: Foundation.IndexSet, rhs: Foundation.IndexSet) -> Bool ^
import SwiftBacktrace print(swiftDemangleName("$S13ExampleNumber6isEven6numberSbSi_tF")) print(swiftSimplifiedDemangleName("$S13ExampleNumber6isEven6numberSbSi_tF"))
(edited)ExampleNumber.isEven(number: Swift.Int) -> Swift.Bool isEven(number:)
(edited)import Foundation public extension String.StringInterpolation { mutating func appendInterpolation(_ value: Date, _ formatter: DateFormatter) { appendLiteral(formatter.string(from: value)) } } public extension DateFormatter { static func format(date: Style, time: Style) -> DateFormatter { let formatter = DateFormatter() formatter.locale = Locale.current (formatter.dateStyle, formatter.timeStyle) = (date, time) return formatter } } let formatter = DateFormatter.format(date: .none, time: .long) print("\(Date(), formatter)")
3:11:18 PM GMT+9
import Foundation public extension String.StringInterpolation { mutating func appendInterpolation(_ value: Date, _ formatter: DateFormatter) { appendLiteral(formatter.string(from: value)) } } public extension DateFormatter { static func format(date: Style, time: Style, locale: Locale = .current) -> DateFormatter { let formatter = DateFormatter() formatter.locale = locale (formatter.dateStyle, formatter.timeStyle) = (date, time) return formatter } } let formatter = DateFormatter.format(date: .none, time: .long) print("\(Date(), formatter)")
3:17:13 PM GMT+9
:print_decl Result
@_frozen enum Result<Success, Failure> where Failure : Error { case success(Success) case failure(Failure) func map<NewSuccess>(_ transform: (Success) -> NewSuccess) -> Result<NewSuccess, Failure> func mapError<NewFailure>(_ transform: (Failure) -> NewFailure) -> Result<Success, NewFailure> where NewFailure : Error func flatMap<NewSuccess>(_ transform: (Success) -> Result<NewSuccess, Failure>) -> Result<NewSuccess, Failure> func flatMapError<NewFailure>(_ transform: (Failure) -> Result<Success, NewFailure>) -> Result<Success, NewFailure> where NewFailure : Error func get() throws -> Success } extension Result where Failure == Error { init(catching body: () throws -> Success) } extension Result : Equatable where Success : Equatable, Failure : Equatable { static func == (a: Result<Success, Failure>, b: Result<Success, Failure>) -> Bool } extension Result : Hashable where Success : Hashable, Failure : Hashable { var hashValue: Int { get } func hash(into hasher: inout Hasher) }
extension Result where Failure == Error { init(catching body: () throws -> Success) }
でコンパイルエラーになるんですよねenum MyResult<Success, Failure: Error> { case success(Success) case failure(Failure) } extension MyResult where Failure == Error { init(catching body: () throws -> Success) { do { self = .success(try body()) } catch { self = .failure(error) } } } print(type(of: MyResult { 1 }))
MyResult<Int, Error>
print(type(of: Result { 1 }))
Result<Int, Error>
let foo = Result<Int, Never>.success(1) let bar = Result<Int, Never>.success(1) print(foo == bar)
print(#"\a\b"#)
print(###"aaa"bbb#ccc"###)
import Foundation print(UUID().uuidString)
(edited)class Base { func foo(x: Int = 12) {} } class Derived : Base { override func foo(x: Int = 42) { print(x) } } func test1(obj: Base) { obj.foo() } func test2(obj: Derived) { obj.foo() } test1(obj: Derived()) test2(obj: Derived())
(edited)class Base { func foo(x: Int = 12) {} } class Derived : Base { override func foo(x: Int = 42) { print(x) } } func test1(obj: Base) { obj.foo() } func test2(obj: Derived) { obj.foo() } test1(obj: Derived()) test2(obj: Derived())
swift-4.2.1-RELEASE
12 42
class Base { class var defaultX: Int { return 12 } func foo(x: Int = defaultX) {} } class Derived : Base { override class var defaultX: Int { return 42 } override func foo(x: Int = defaultX) { print(x) } } func test1(obj: Base) { obj.foo() } func test2(obj: Derived) { obj.foo() } test1(obj: Derived()) test2(obj: Derived())
class Base { class func getDefaultFooX() -> Int { return 12 } func foo(x: Int = getDefaultFooX()) {} } class Derived : Base { override class func getDefaultFooX() -> Int { return 42 } override func foo(x: Int = getDefaultFooX()) { print(x) } } func test1(obj: Base) { obj.foo() } func test2(obj: Derived) { obj.foo() } test1(obj: Derived()) test2(obj: Derived())
class Base { func getDefaultFooX() -> Int { return 12 } func foo(x: Int? = nil) { let x = x ?? getDefaultFooX() print(x) } } class Derived : Base { override func getDefaultFooX() -> Int { return 42 } }
という事なのでしょうね。 (edited)import Foundation let a = Float80.init(6.8523015e+5) let b = 6.8523015e+5 as Float80 print(a) print(b) print(a == b)
685230.1500000000233 685230.15 false
685230.1500000000233 685230.15 false
685230.1500000000233 685230.15 false
Float80
だけバグってる。Float80.init(_ other: Double)
が呼ばれてる。import Foundation let a = Float80(6.8523015e+5) let b = 6.8523015e+5 as Float80 print(a) print(b) print(a == b)
(edited)Double
とFloat
はSE-0213導入前の挙動でも問題が起きていなかったと。protocol P { func hoge(_ a: Int) func hoge(_ a: String) } extension P { func hoge(_ a: Int) {} } struct S : P { func hoge<X>(_ a: X) {} } let s = S() :constraints debug on s.hoge(1) s.hoge("a")
// s : S = REPL.S()
stderr:---Constraint solving for the expression at [<REPL Input>:1:1 - line:1:9]--- (overload set choice binding $T0 := S) ---Initial constraints for the given expression--- (call_expr type='$T3' location=<REPL Input>:1:3 range=[<REPL Input>:1:1 - line:1:9] arg_labels=_: (unresolved_dot_expr type='$T1' location=<REPL Input>:1:3 range=[<REPL Input>:1:1 - line:1:3] field 'hoge' function_ref=single (declref_expr type='S' location=<REPL Input>:1:1 range=[<REPL Input>:1:1 - line:1:1] decl=REPL.(file).s@<REPL Input>:1:5 direct_to_storage function_ref=unapplied)) (paren_expr type='($T2)' location=<REPL Input>:1:8 range=[<REPL Input>:1:7 - line:1:9] (integer_literal_expr type='$T2' location=<REPL Input>:1:8 range=[<REPL Input>:1:8 - line:1:8] value=1))) Score: 0 0 0 0 0 0 0 0 0 0 0 Type Variables: $T0 [lvalue allowed] as S @ locator@0x8a91c18 [DeclRef@<REPL Input>:1:1] $T1 [lvalue allowed] subtype_of_existential involves_type_vars bindings={} @ locator@0x8a91c98 [UnresolvedDot@<REPL Input>:1:3 -> member] $T2 fully_bound literal=3 involves_type_vars bindings={(subtypes of) (default from ExpressibleByIntegerLiteral) Int} @ locator@0x8a91df0 [IntegerLiteral@<REPL Input>:1:8] $T3 fully_bound subtype_of_existential involves_type_vars bindings={} @ locator@0x8a91e98 [Call@<REPL Input>:1:3 -> function result] Active Constraints: Inactive Constraints: disjunction [[locator@0x8a91c98 [UnresolvedDot@<REPL Input>:1:3 -> member]]]:$T1 bound to decl REPL.(file).S.hoge@<REPL Input>:2:12 : <X> (S) -> (X) -> () at <REPL Input>:2:12 [[locator@0x8a91c98 [UnresolvedDot@<REPL Input>:1:3 -> member]]]; or $T1 bound to decl REPL.(file).P.hoge@<REPL Input>:2:12 : <Self where Self : P> (Self) -> (Int) -> () at <REPL Input>:2:12 [[locator@0x8a91c98 [UnresolvedDot@<REPL Input>:1:3 -> member]]]; $T2 literal conforms to ExpressibleByIntegerLiteral [[locator@0x8a91df0 [IntegerLiteral@<REPL Input>:1:8]]]; ($T2) -> $T3 applicable fn $T1 [[loc
<X> (S) -> (X) -> ()
と <Self where Self : P> (Self) -> (Int) -> ()
を比較して後者を選んでるぽいね。:constraints debug on
でs.hoge(1)
がどう選択されているか出力してる。pbpaste|swift -frontend -repl
として見るのが簡単。 (edited)import Foundation public class TestFunctionDeclDefaultArgument { func multipleArgument(argument1: Int = 1, argument2: String = "string") { } }
import Foundation public class TestFunctionDeclDefaultArgument { func multipleArgument(argument1: Int = 1, argument2: String = "string") { } }
{"id":49,"kind":"SourceFile","layout":[{"id":48,"kind":"CodeBlockItemList","layout":[{"id":6,"kind":"CodeBlockItem","layout":[{"id":5,"kind":"ImportDecl","layout":[null,null,{"id":1,"tokenKind":{"kind":"kw_import"},"leadingTrivia":[{"kind":"Newline","value":1}],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},null,{"id":4,"kind":"AccessPath","layout":[{"id":3,"kind":"AccessPathComponent","layout":[{"id":2,"tokenKind":{"kind":"identifier","text":"Foundation"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},null],"presence":"Present"}],"presence":"Present"}],"presence":"Present"},null,null],"presence":"Present"},{"id":46,"kind":"CodeBlockItem","layout":[{"id":45,"kind":"ClassDecl","layout":[null,{"id":9,"kind":"ModifierList","layout":[{"id":8,"kind":"DeclModifier","layout":[{"id":7,"tokenKind":{"kind":"kw_public"},"leadingTrivia":[{"kind":"Newline","value":2}],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},null,null,null],"presence":"Present"}],"presence":"Present"},{"id":10,"tokenKind":{"kind":"kw_class"},"leadingTrivia":[],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},{"id":11,"tokenKind":{"kind":"identifier","text":"TestFunctionDeclDefaultArgument"},"leadingTrivia":[],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},null,null,null,{"id":44,"kind":"MemberDeclBlock","layout":[{"id":12,"tokenKind":{"kind":"l_brace"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},{"id":42,"kind":"MemberDeclList","layout":[{"id":41,"kind":"MemberDeclListItem","layout":[{"id":40,"kind":"FunctionDecl","layout":[null,null,{"id":13,"tokenKind":{"kind":"kw_func"},"leadingTrivia":[{"kind":"Newline","value":1},{"kind":"Space","value":4}],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},{"id":14,"tokenKind":{"kind":"identifier","text":"multipleArgument"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},null,{"id":36,"kind":"FunctionSignature","layout"
import Foundation public class TestFunctionDeclNoReturn { func twoArgumentNoReturn(argument1: Int, argument2: String) { } }
{"id":42,"kind":"SourceFile","layout":[{"id":41,"kind":"CodeBlockItemList","layout":[{"id":6,"kind":"CodeBlockItem","layout":[{"id":5,"kind":"ImportDecl","layout":[null,null,{"id":1,"tokenKind":{"kind":"kw_import"},"leadingTrivia":[{"kind":"Newline","value":1}],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},null,{"id":4,"kind":"AccessPath","layout":[{"id":3,"kind":"AccessPathComponent","layout":[{"id":2,"tokenKind":{"kind":"identifier","text":"Foundation"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},null],"presence":"Present"}],"presence":"Present"}],"presence":"Present"},null,null],"presence":"Present"},{"id":39,"kind":"CodeBlockItem","layout":[{"id":38,"kind":"ClassDecl","layout":[null,{"id":9,"kind":"ModifierList","layout":[{"id":8,"kind":"DeclModifier","layout":[{"id":7,"tokenKind":{"kind":"kw_public"},"leadingTrivia":[{"kind":"Newline","value":2}],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},null,null,null],"presence":"Present"}],"presence":"Present"},{"id":10,"tokenKind":{"kind":"kw_class"},"leadingTrivia":[],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},{"id":11,"tokenKind":{"kind":"identifier","text":"TestFunctionDeclNoReturn"},"leadingTrivia":[],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},null,null,null,{"id":37,"kind":"MemberDeclBlock","layout":[{"id":12,"tokenKind":{"kind":"l_brace"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},{"id":35,"kind":"MemberDeclList","layout":[{"id":34,"kind":"MemberDeclListItem","layout":[{"id":33,"kind":"FunctionDecl","layout":[null,null,{"id":13,"tokenKind":{"kind":"kw_func"},"leadingTrivia":[{"kind":"Newline","value":1},{"kind":"Space","value":4}],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},{"id":14,"tokenKind":{"kind":"identifier","text":"twoArgumentNoReturn"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},null,{"id":29,"kind":"FunctionSignature","layout":[{"
import Foundation print(NSNumber(value: 1.2 as Float).description)
1.20000004768372
Fatal error: Unknown NSNumber Type: file /home/buildnode/jenkins/workspace/oss-swift-package-linux-ubuntu-16_04/swift-corelibs-foundation/Foundation/NSNumber.swift, line 1041 Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOZlib/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOZlib.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinux.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio-zlib-support/module.modulemap -module-name main -lLibraries #0 0x00000000047d58a4 PrintStackTraceSignalHan
Fatal error: Unknown NSNumber Type: file /home/buildnode/jenkins/workspace/oss-swift-5.0-package-linux-ubuntu-16_04/swift-corelibs-foundation/Foundation/NSNumber.swift, line 1041 Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOZlib/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOZlib.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinux.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio-zlib-support/module.modulemap -module-name main -lLibraries #0 0x0000000004621134 PrintStackTraceSigna
let data = """ {"data": 9223372036854775808} """ struct Foo: Codable { var data: UInt64 } import Foundation print(try! JSONDecoder().decode(Foo.self, from: data.data(using: .utf8)!))
Foo(data: 9223372036854775807)
$ pbpaste let data = """ {"data": 9223372036854775808} """ struct Foo: Codable { var data: UInt64 } import Foundation print(try! JSONDecoder().decode(Foo.self, from: data.data(using: .utf8)!))% $ pbpaste|xcrun --toolchain org.swift.40320171205a swift - Foo(data: 9223372036854775808) $ pbpaste|xcrun --toolchain org.swift.41320180727a swift - Foo(data: 9223372036854775808) $ pbpaste|xcrun --toolchain org.swift.42120181030a swift - Foo(data: 9223372036854775808) $ pbpaste|xcrun --toolchain org.swift.5020190116a swift - Foo(data: 9223372036854775808)
let data = """ {"data": 9223372036854775808} """ import Foundation dump(try! JSONSerialization.jsonObject(with: data.data(using: .utf8)!))
▿ 1 key/value pair ▿ (2 elements) - key: "data" ▿ value: 9223372036854775808 #0 - super: Foundation.NSValue - super: Foundation.NSObject ▿ _base: Foundation._CFInfo - info: 5766 - pad: 0 - _pad: 0
▿ 1 key/value pair ▿ (2 elements) - key: "data" ▿ value: 9223372036854775807 #0 - super: Foundation.NSValue - super: Foundation.NSObject ▿ _base: Foundation._CFInfo - info: 5763 - pad: 0 - _pad: 9223372036854775807
class Entity<Base> {} class Tweet: Entity<Tweet> {} print(Tweet())
Self
が使えるから、不要な事が多い。import Foundation public class TestFunctionDeclDefaultArgument { func multipleArgument(argument1: Int = 1, argument2: String = "string") { } }
{"kind":"SourceFile","layout":[{"kind":"CodeBlockItemList","layout":[{"kind":"CodeBlockItem","layout":[{"kind":"ImportDecl","layout":[null,null,{"tokenKind":{"kind":"kw_import"},"leadingTrivia":[{"kind":"Newline","value":1}],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},null,{"kind":"AccessPath","layout":[{"kind":"AccessPathComponent","layout":[{"tokenKind":{"kind":"identifier","text":"Foundation"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},null],"presence":"Present"}],"presence":"Present"}],"presence":"Present"},null],"presence":"Present"},{"kind":"CodeBlockItem","layout":[{"kind":"ClassDecl","layout":[null,{"kind":"ModifierList","layout":[{"kind":"DeclModifier","layout":[{"tokenKind":{"kind":"kw_public"},"leadingTrivia":[{"kind":"Newline","value":2}],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},{"kind":"TokenList","layout":[],"presence":"Present"}],"presence":"Present"}],"presence":"Present"},{"tokenKind":{"kind":"kw_class"},"leadingTrivia":[],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},{"tokenKind":{"kind":"identifier","text":"TestFunctionDeclDefaultArgument"},"leadingTrivia":[],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},null,null,null,{"kind":"MemberDeclBlock","layout":[{"tokenKind":{"kind":"l_brace"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},{"kind":"DeclList","layout":[{"kind":"FunctionDecl","layout":[null,null,{"tokenKind":{"kind":"kw_func"},"leadingTrivia":[{"kind":"Newline","value":1},{"kind":"Space","value":4}],"trailingTrivia":[{"kind":"Space","value":1}],"presence":"Present"},{"tokenKind":{"kind":"identifier","text":"multipleArgument"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},null,{"kind":"FunctionSignature","layout":[{"kind":"ParameterClause","layout":[{"tokenKind":{"kind":"l_paren"},"leadingTrivia":[],"trailingTrivia":[],"presence":"Present"},{"kind":"FunctionParameterList","layout":[{"kind":"Func
-emit-syntax
用にprettyPrintが欲しくなるな。import Foundation let u = NSURL()
<stdin>:4:9: error: cannot invoke initializer for type 'NSURL' with no arguments let u = NSURL() ^ <stdin>:4:9: note: overloads for 'NSURL' exist with these partially matching parameter lists: (coder: NSCoder), (fileURLWithPath: String, isDirectory: Bool, relativeTo: URL?), (fileURLWithPath: String, relativeTo: URL?), (fileURLWithPath: String, isDirectory: Bool), (fileURLWithPath: String), (fileURLWithFileSystemRepresentation: UnsafePointer<Int8>, isDirectory: Bool, relativeTo: URL?), (string: String), (string: String, relativeTo: URL?), (dataRepresentation: Data, relativeTo: URL?), (absoluteURLWithDataRepresentation: Data, relativeTo: URL?) let u = NSURL() ^
import Foundation let u = NSURL()
<stdin>:3:9: error: cannot invoke initializer for type 'NSURL' with no arguments let u = NSURL() ^ <stdin>:3:9: note: overloads for 'NSURL' exist with these partially matching parameter lists: (coder: NSCoder), (fileURLWithPath: String, isDirectory: Bool, relativeTo: URL?), (fileURLWithPath: String, relativeTo: URL?), (fileURLWithPath: String, isDirectory: Bool), (fileURLWithPath: String), (fileURLWithFileSystemRepresentation: UnsafePointer<Int8>, isDirectory: Bool, relativeTo: URL?), (string: String), (string: String, relativeTo: URL?), (dataRepresentation: Data, relativeTo: URL?), (absoluteURLWithDataRepresentation: Data, relativeTo: URL?) let u = NSURL() ^
let café = "café" let index = café.utf8.index(before: café.utf8.endIndex) // The last byte. let before = String(café[..<index]) let after = String(café[index...]) print(before + after) // “café” print(after.utf8.count) // 2 bytes?!?
String
の挙動、不安になってきた… https://bugs.swift.org/browse/SR-9802func printUnicodeScalars<S: StringProtocol>(_ string: S) { print(string.unicodeScalars.map { "\\u{\(String($0.value, radix: 16))}" }.joined()) } // https://emojipedia.org/family-man-woman-girl-boy/ let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}" printUnicodeScalars(family) let utf16Index = family.utf16.index(before: family.utf16.endIndex) let utf16Before = String(family[..<utf16Index]) printUnicodeScalars(utf16Before) let utf16After = String(family[utf16Index...]) printUnicodeScalars(utf16After) printUnicodeScalars(utf16Before + utf16After) print(utf16After.utf16.count)
(edited)\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466} \u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{fffd} \u{fffd} \u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466} 1
(edited)\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466} \u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d} \u{1f466} \u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466} 2
(edited)String.UTF16View.index(before:)
は、Characterの途中のIndexを指すこともあったぽい。 (edited)String.UTF8View.index(before:)
と同等の挙動。String.UTF16View
とString.UTF8View
両方のindex(before:)
の挙動が違う。UTF8View.Index
はUnicodeScalar
の境界に合わせられていました。 @swift-4.2.4
func printUnicodeScalars<S: StringProtocol>(_ string: S) { print(string.unicodeScalars.map { "\\u{\(String($0.value, radix: 16))}" }.joined()) } // https://emojipedia.org/family-man-woman-girl-boy/ let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}" printUnicodeScalars(family) let utf8Index = family.utf8.index(before: family.utf8.endIndex) let utf8Before = String(family[..<utf8Index]) printUnicodeScalars(utf8Before) let utf8After = String(family[utf8Index...]) printUnicodeScalars(utf8After) printUnicodeScalars(utf8Before + utf8After) print(utf8After.utf8.count)
\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466} \u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d} \u{1f466} \u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466} 4
UTF16View.Index
がUnicodeScalar
の境界に合わせられる様になった。UnicodeScalar
boundaries are: respected by: String.UTF8View.index(before:)
on Swift 4 String.UTF16View.index(before:)
on Swift 5 not respected by String.UTF16View.index(before:)
on Swift 4 String.UTF8View.index(before:)
on Swift 5内部表現ではない方のindexが、unicode scalar境界に畳み込まれる という意味では 一貫している?
そう言える。ランタイムの内部表現に依存してるかどうかまでは確かめてないですが。String.init(contentsOfFile:encoding:)
を使うと内部表現がUTF-16になってた。String.UTF8View.withContiguousStorageIfAvailable(_:)
を使った時、渡したクロージャが呼ばれたら内部表現はUTF-8、呼ばれなかったらUTF-16String.UnicodeScalarsView.map(_:)
でクラッシュ https://bugs.swift.org/browse/SR-9822
@swift-4.2.4 @swift-5.0.3 -frontend -repl // https://emojipedia.org/family-man-woman-girl-boy/ let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}" let utf8Index = family.utf8.index(before: family.utf8.endIndex) let utf8Before = String(family[..<utf8Index]) _ = utf8Before.unicodeScalars.map { $0 }
(edited)// family : String = "👨👩👧👦" // utf8Index : String.UTF8View.Index = Swift.String.Index(_compoundOffset: 39, _utf8Buffer: Swift._ValidUTF8Buffer<Swift.UInt32>(_biasedBits: 2811404529), _graphemeStrideCache: 0) // utf8Before : String = "👨👩👧"
(edited)Stack dump: 0. Program arguments: swift -frontend -I /Libraries/.build/x86_64-unknown-linux/debug -L /Libraries/.build/x86_64-unknown-linux/debug -lLibraries -DDEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOZlib.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOZlib/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinux.build/module.modulemap -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio-zlib-support/module.modulemap -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -repl 1. while processing REPL source: // https://emojipedia.org/family-man-woman-girl-boy/ let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}" let utf8Index = family.utf8.index(before: family.utf8.endIndex) [0
(edited)UTF8View.index(before:)
とUTF16View.index(before:)
は使ってはいけないモノだと言われている様に思えてくる。ランタイムの内部表現に依存してるかどうかまでは確かめてないですが。
依存してるぽい。stringUTF16Backend
を使うとtest()
内でクラッシュする。 import Foundation #if !compiler(>=5) private extension String.UTF8View { func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R? { return nil } } #endif extension String { var nativeEncoding: Encoding { return utf8.withContiguousStorageIfAvailable({$0}) != nil ? .utf8 : .utf16 } } func printUTF16<S: StringProtocol>(_ string: S, label: String) { print(label, string.utf16.map { "\\u{\(String($0, radix: 16))}" }.joined()) } func test(_ string: String) { let utf16Index = string.utf16.index(before: string.utf16.endIndex) let utf16Before = string[..<utf16Index] printUTF16(utf16Before, label: "before:") let utf16After = string[utf16Index...] printUTF16(utf16After, label: "after:") printUTF16(utf16Before + utf16After, label: "joined:") print(utf16After.utf8.count) print(utf16After.utf16.count) } // https://emojipedia.org/family-man-woman-girl-boy/ let string = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}" print(string.nativeEncoding) test(string) let tempfileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString) try string.write(to: tempfileURL, atomically: true, encoding: .utf16) let stringUTF16Backend = try String(contentsOfFile: tempfileURL.path) print(stringUTF16Backend.nativeEncoding) test(stringUTF16Backend) defer { try! FileManager.default.removeItem(at: tempfileURL) }
(edited)String.UTF8View
, String.UTF16View
を使ったString.Index
の操作は、UnicodeScalars
の境界に合わないIndex
を作る場合がある。(仕様)UnicodeScalars
の境界に合わないIndex
を使ったRangeでSubstring
を作ると、クラッシュする場合がある。(バグ)https://bugs.swift.org/browse/SR-6161 これを思い出しました。
を読んで、試して、ようやく理解したぽい。 問題となるのはindex(before:)
の挙動ではなく、String
, UTF8View
, UTF16View
それぞれのsubscript
がunicode scalarsの境界に合わないIndex
を持つRange
をどう扱うか、が変わっている事なのね。 (edited)import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
4.2.2-RELEASE
import Foundation [1, 2, 3] .map { ($0, $0) } .forEach { print("-") } [1, 2, 3] .map { ($0, $0) } .forEach { print($1) }
(edited)- - - 1 2 3
stderr:<stdin>:5:12: warning: expression of type '(Int, Int)' is unused .map { ($0, $0) } ^~~~~~~~
(edited)expression of type '(Int, Int)' is unused
このワーニングが RxSwift の map
でも出てきて驚いた (subscribe
で値を参照したら正しく警告が消えた)[1, 2, 3] .map { ($0, $0) } .forEach { print("-") }
sil_stage canonical import Builtin import Swift import SwiftShims // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = metatype $@thin Array<Int>.Type // user: %25 %3 = integer_literal $Builtin.Word, 3 // user: %5 // function_ref _allocateUninitializedArray<A>(_:) %4 = function_ref @$Ss27_allocateUninitializedArrayySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %5 %5 = apply %4<Int>(%3) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // users: %9, %6, %8 %6 = tuple_extract %5 : $(Array<Int>, Builtin.RawPointer), 0 // users: %25, %7 retain_value %6 : $Array<Int> // id: %7 %8 = tuple_extract %5 : $(Array<Int>, Builtin.RawPointer), 1 // user: %10 release_value %5 : $(Array<Int>, Builtin.RawPointer) // id: %9 %10 = pointer_to_address %8 : $Builtin.RawPointer to [strict] $*Int // users: %13, %20, %15 %11 = integer_literal $Builtin.Int64, 1 // user: %12 %12 = struct $Int (%11 : $Builtin.Int64) // user: %13 store %12 to %10 : $*Int // id: %13 %14 = integer_literal $Builtin.Word, 1 // user: %15 %15 = index_addr %10 : $*Int, %14 : $Builtin.Word // user: %18 %16 = integer_literal $Builtin.Int64, 2 // user: %17 %17 = struct $Int (%16 : $Builtin.Int64) // user: %18 store %17 to %15 : $*Int // id: %18 %19 = integer_literal $Builtin.Word, 2 // user: %20 %20 = index_addr %10 : $*Int, %19 : $Builtin.Word // user: %23 %21 = integer_literal $Builtin.Int64, 3 // user: %22 %22 = struct $Int (%21 : $Builtin.Int64) // user: %23 store %22 to %20 : $*Int // id: %23 // function_ref specialized Array.init(arrayLiter
()->Void
扱いでmapの結果が[Void]
と推論されているのでは? (edited)[1, 2, 3] .map { return ($0, $0) } .forEach { print("-") }
- - -
stderr:<stdin>:3:18: warning: expression of type '(Int, Int)' is unused .map { return ($0, $0) } ^~~~~~~~
[1, 2, 3] .map { return ($0, $0) } .forEach { _ in print("-") }
[1, 2, 3] .map { ($0, $0) } .forEach { () in print("") }
こうなってるのか (edited)[1, 2, 3] .map { a in return (a, a) } .forEach { print("-") }
これが通って [1, 2, 3] .map { a -> (Int, Int) in return (a, a) } .forEach { print("-") }
これがだめなのが謎return
で返してるのはどうなるんです?[1, 2, 3] .map { a -> Void in return (a, a) } .forEach { print("-") }
return ; ($0, $0)
な解釈ではfunc a(_ f: () -> Void) {} a { return 333 }
var a: () -> Void = { return (1, 2) }
(edited)<stdin>:3:10: warning: expression of type '(Int, Int)' is unused return (1, 2) ^~~~~~
(edited)let a: () -> Int = { return 3 } let b: () -> Void = a
(edited)<stdin>:3:21: error: cannot convert value of type '() -> Int' to specified type '() -> Void' let b: () -> Void = a ^
(edited)expression of type '(Int, Int)' is unused
だから暗黙変換系ではない[1, 2, 3] .map { a -> Void in return (a, a) } .forEach { print("-") }
[1, 2, 3] .map { a -> Void in return (a, a) } .forEach { print("-") }
- - -
stderr:<stdin>:3:32: warning: expression of type '(Int, Int)' is unused .map { a -> Void in return (a, a) } ^~~~~~
func a() -> Void { return; (1, 1) }
<stdin>:2:28: warning: expression of type '(Int, Int)' is unused func a() -> Void { return; (1, 1) } ^~~~~~ <stdin>:2:28: warning: code after 'return' will never be executed func a() -> Void { return; (1, 1) } ^
func fatal() -> Int { fatalError() } [1, 2, 3] .map { a -> Void in return (a, fatal()) } .forEach { print("-") }
<stdin>:4:32: warning: expression of type '(Int, Int)' is unused .map { a -> Void in return (a, fatal()) } ^~~~~~~~~~~~ Fatal error: : file <stdin>, line 2 Current stack trace: 0 libswiftCore.so 0x00007fce9010bfa0 _swift_stdlib_reportFatalErrorInFile + 215 1 libswiftCore.so 0x00007fce8fe645c1 <unavailable> + 1504705 2 libswiftCore.so 0x00007fce900a10c2 <unavailable> + 3850434 3 libswiftCore.so 0x00007fce8fe63d0a <unavailable> + 1502474 4 libswiftCore.so 0x00007fce900a0f5c <unavailable> + 3850076 5 libswiftCore.so 0x00007fce8fe63d0a <unavailable> + 1502474 6 libswiftCore.so 0x00007fce8fffda28 <unavailable> + 3181096 7 libswiftCore.so 0x00007fce8fe635a9 <unavailable> + 1500585 12 libswiftCore.so 0x00007fce8fe27640 Collection.map<A>(_:) + 527 14 swift 0x0000000001043efe <unavailable> + 12861182 15 swift 0x0000000001048022 <unavailable> + 12877858 16 swift 0x00000000004f8b42 <unavailable> + 1018690 17 swift 0x00000000004df0bb <unavailable> + 913595 18 swift 0x00000000004da3f0 <unavailable> + 893936 19 swift 0x000000000048a348 <unavailable> + 566088 20 libc.so.6 0x00007fce92ab0740 __libc_start_main + 240 21 swift 0x0000000000488009 <unavailable> + 557065 #0 0x000000000410ac94 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x410ac94) #1 0x0000000004108b22 llvm::sys::RunSignalHandlers() (/usr/bin/swift+0x4108b22) #2 0x000000000410ae42 SignalHandler(int) (/usr/bin/swift+0x410ae42) #3 0x00007fce94386390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x0
[1, 2, 3] .map { a -> Void in return (a, a) } .forEach { print("-") }
- - -
stderr:<stdin>:3:32: warning: expression of type '(Int, Int)' is unused .map { a -> Void in return (a, a) } ^~~~~~
- - -
stderr:<stdin>:3:32: warning: expression of type '(Int, Int)' is unused .map { a -> Void in return (a, a) } ^~~~~~
let a = { () -> Void in return 333 }
<stdin>:3:12: warning: integer literal is unused return 333 ^~~
[1, 2, 3] .map { return ($0, $0) } .forEach { print("-") }
.forEach { print("-") }
こいつはこの行だけで引数Voidが決定的だからlet a = { () -> Void in return 333 }
<stdin>:2:12: warning: integer literal is unused return 333 ^~~
{ ... in return <expr> }
は single expression closure と解釈されるlet _ : () -> Void = { return "test" }
が通るの自体はもはや仕様なので、エラー診断のバグという扱いになると思います。import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
4.2.3-RELEASE
import Foundation class Entity<Id: Hashable, Props> { let id: Id let data: Props init(id: Id, data: Props) { self.id = id self.data = data } } class User: Entity<User.Id, User.Props> { struct Id: Hashable { } struct Props { var name: String } } let user = User(id: .init(), data: .init(name: "user_name")) print(user, user.data.name)
main.User user_name
func defaultValue<T>() -> T { fatalError() } struct S<T> { let value1: T = defaultValue() let value2: Int } func main() { _ = S<Int>(value2: 2) }
(edited)swift: /home/buildnode/jenkins/workspace/oss-swift-package-linux-ubuntu-16_04/swift/lib/SILGen/SILGenConstructor.cpp:146: void emitImplicitValueConstructor(swift::Lowering::SILGenFunction &, swift::ConstructorDecl *): Assertion `fieldTy->isEqual(field->getParentInitializer()->getType()) && "Checked by sema"' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOZlib/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOZlib.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinux.build/module.modulemap -Xcc -fmodule-map-file=
(edited)class Some { lazy var thing = 1 } class Some2: Some { override lazy var thing = 2 } print(Some2().thing)
Cannot (Cannotとは言っていない)2
stderr:<stdin>:6:23: warning: cannot override with a stored property 'thing' override lazy var thing = 2 ^ <stdin>:2:14: note: attempt to override property here lazy var thing = 1 ^
import Foundation protocol Target { } protocol Foo { associatedtype Bar: Target } class TargetBase<X>: Target {} class Impl<X, TargetType>: Foo where TargetType: TargetBase<X> { typealias Bar = TargetType }
(edited)swift: /home/buildnode/jenkins/workspace/oss-swift-4.2-package-linux-ubuntu-16_04/swift/lib/AST/Type.cpp:3215: swift::Type swift::TypeBase::getSuperclassForDecl(const swift::ClassDecl *): Assertion `nominalDecl && "expected nominal type here"' failed. #0 0x000000000410acb4 PrintStackTraceSignalHandler(void*) (/usr/bin/swift+0x410acb4) #1 0x0000000004108b42 llvm::sys::RunSignalHandlers() (/usr/bin/swift+0x4108b42) #2 0x000000000410ae62 SignalHandler(int) (/usr/bin/swift+0x410ae62) #3 0x00007fefce714390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x00007fefcce53428 gsignal (/lib/x86_64-linux-gnu/libc.so.6+0x35428) #5 0x00007fefcce5502a abort (/lib/x86_64-linux-gnu/libc.so.6+0x3702a) #6 0x00007fefcce4bbd7 (/lib/x86_64-linux-gnu/libc.so.6+0x2dbd7) #7 0x00007fefcce4bc82 (/lib/x86_64-linux-gnu/libc.so.6+0x2dc82) #8 0x00000000017ff77c swift::TypeBase::getSuperclassForDecl(swift::ClassDecl const*) (/usr/bin/swift+0x17ff77c) #9 0x00000000017e357a swift::ProtocolConformance::subst(swift::Type, llvm::function_ref<swift::Type (swift::SubstitutableType*)>, llvm::function_ref<llvm::Optional<swift::ProtocolConformanceRef> (swift::CanType, swift::Type, swift::ProtocolType*)>) const (/usr/bin/swift+0x17e357a) #10 0x00000000013c9607 swift::ConformanceChecker::ensureRequirementsAreSatisfied(bool)::GatherConformancesListener::satisfiedConformance(swift::Type, swift::Type, swift::ProtocolConformanceRef) (/usr/bin/swift+0x13c9607) #11 0x00000000013a7582 swift::TypeChecker::checkGenericArguments(swift::DeclContext*, swift::SourceLoc, swift::SourceLoc, swift::Type, swift::ArrayRefView<swift::Type, swift::GenericTypeParamType*, swift::GenericTypeParamType* swift::staticCastHelper<swift::GenericTypeParamType>(swift::Type const&), true>, llvm::ArrayRef<swift::Requirement>, llvm::function_ref<swift::Type (swift::SubstitutableType*)>, llvm::function_ref<llvm::Optional<swift::ProtocolConformanceRef> (swift::CanType, swift::Type, swift::Prot
let a = "abc" let b = "cde" dump(b.difference(from: a))
(edited)▿ Swift.CollectionDifference<Swift.Character> ▿ insertions: 2 elements ▿ Swift.CollectionDifference<Swift.Character>.Change.insert ▿ insert: (3 elements) - offset: 1 - element: "d" - associatedWith: nil ▿ Swift.CollectionDifference<Swift.Character>.Change.insert ▿ insert: (3 elements) - offset: 2 - element: "e" - associatedWith: nil ▿ removals: 2 elements ▿ Swift.CollectionDifference<Swift.Character>.Change.remove ▿ remove: (3 elements) - offset: 0 - element: "a" - associatedWith: nil ▿ Swift.CollectionDifference<Swift.Character>.Change.remove ▿ remove: (3 elements) - offset: 1 - element: "b" - associatedWith: nil
(edited)struct S { func f() -> Self { return self } }
<stdin>:2:17: error: 'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S'? func f() -> Self { return self } ^~~~ S
class Base { let val: String = "string" } class Sub: Base {} let object = Sub() print(object[keyPath: \Base.val]) // "string" print(object[keyPath: \Sub.val]) // Crash!
class Base { let val: String = "string" } class Sub: Base {} let object = Sub() print(object[keyPath: \Base.val]) // "string" print(object[keyPath: \Sub.val]) // Crash!
class Base { let val: String = "string" } class Sub: Base {} let object = Sub() print(object[keyPath: \Base.val]) // "string" print(object[keyPath: \Sub.val]) // Crash!
string string
protocol P { associatedtype X } struct S<X>: P { }
(edited)<stdin>:6:8: error: type 'S<X>' does not conform to protocol 'P' struct S<X>: P { ^ <stdin>:2:20: note: protocol requires nested type 'X'; do you want to add it? associatedtype X ^
(edited)import Foundation let kp = \UUID.uuid let writable = kp as! WritableKeyPath<UUID, uuid_t> var uuid = UUID() print(uuid) var newUUID: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) uuid[keyPath: writable] = newUUID print(uuid)
(edited)A1717B4D-EE97-460A-B7C6-1149A2E2561A 00000000-0000-0000-0000-000000000000
(edited)protocol ProtoA {} protocol ProtoB { associatedtype T : ProtoA var stuff: Int { get } } extension ProtoB { var stuff: Int { return 0 } } class Foo<X: ProtoA> : ProtoB { typealias T = X }
swift: /home/buildnode/jenkins/workspace/oss-swift-5.0-package-linux-ubuntu-16_04/swift/lib/AST/ProtocolConformance.cpp:77: swift::ProtocolDecl *swift::ProtocolConformanceRef::getRequirement() const: Assertion `!isInvalid()' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOZlib/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOZlib.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinux.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio-zlib-support/module.modulemap -module-name main
protocol ProtoA {} protocol ProtoB { associatedtype T : ProtoA func stuff() -> Int } extension ProtoB { func stuff() -> Int { return 0 } } class Foo<X: ProtoA> : ProtoB { typealias T = X }
swift: /home/buildnode/jenkins/workspace/oss-swift-5.0-package-linux-ubuntu-16_04/swift/lib/AST/ProtocolConformance.cpp:77: swift::ProtocolDecl *swift::ProtocolConformanceRef::getRequirement() const: Assertion `!isInvalid()' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOZlib/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOZlib.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinux.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio-zlib-support/module.modulemap -module-name main
swift: /home/buildnode/jenkins/workspace/oss-swift-package-linux-ubuntu-16_04/swift/lib/AST/ProtocolConformance.cpp:77: swift::ProtocolDecl *swift::ProtocolConformanceRef::getRequirement() const: Assertion `!isInvalid()' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOZlib/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOZlib.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinux.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio-zlib-support/module.modulemap -module-name main -lL
let hello: Result<String, Error> = .success("Hello Swift 5!") print(try! hello.get())
(edited)let array = Array<Int>(unsafeUninitializedCapacity: 10) { for i in 0..<5 { $0[i] = i } $1 = 5 } dump(array)
▿ 5 elements - 0 - 1 - 2 - 3 - 4
import Foundation class _Foo { } protocol BarType { typealias BaseFoo = _Foo } class Bar: BarType { class Foo: BaseFoo {} } class FooImpl: Bar.Foo { } print(FooImpl())
(edited)<unknown>:0: error: 'super' members cannot be referenced in a root class
(edited)import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
4.2.4-RELEASE
protocol Q {} protocol P { associatedtype T : Q } class C<T> : P where T : Q {} func foo<U, T>(_: U, _: T) where U : C<T>, U : P {}
(edited)<stdin>:7:46: warning: redundant conformance constraint 'U': 'P' func foo<U, T>(_: U, _: T) where U : C<T>, U : P {} ^ <stdin>:7:36: note: conformance constraint 'U': 'P' implied here func foo<U, T>(_: U, _: T) where U : C<T>, U : P {} ^ <stdin>:7:38: error: type 'T' does not conform to protocol 'Q' func foo<U, T>(_: U, _: T) where U : C<T>, U : P {} ^
(edited)protocol Q {} protocol P { associatedtype T : Q } class C<T> : P where T : Q {} func foo<U, T>(_: U, _: T) where U : C<T>, U : P {}
(edited)<stdin>:7:46: warning: redundant conformance constraint 'U': 'P' func foo<U, T>(_: U, _: T) where U : C<T>, U : P {} ^ <stdin>:7:36: note: conformance constraint 'U': 'P' implied here func foo<U, T>(_: U, _: T) where U : C<T>, U : P {} ^ <stdin>:7:38: error: type 'T' does not conform to protocol 'Q' func foo<U, T>(_: U, _: T) where U : C<T>, U : P {} ^
(edited)protocol Q {} protocol P { associatedtype T : Q } class C<T> : P where T : Q {} func foo<U, T>(_: U, _: T) where U : C<T>, U : P {}
<stdin>:7:46: warning: redundant conformance constraint 'U': 'P' func foo<U, T>(_: U, _: T) where U : C<T>, U : P {} ^ <stdin>:7:36: note: conformance constraint 'U': 'P' implied here func foo<U, T>(_: U, _: T) where U : C<T>, U : P {} ^
protocol Q {} protocol P { associatedtype T : Q } class C<T> : P where T : Q {} func foo<U, T>(_: U, _: T) where U : P, U : C<T> {}
<stdin>:6:36: warning: redundant conformance constraint 'U': 'P' func foo<U, T>(_: U, _: T) where U : P, U : C<T> {} ^ <stdin>:6:43: note: conformance constraint 'U': 'P' implied here func foo<U, T>(_: U, _: T) where U : P, U : C<T> {} ^
protocol Q {} protocol P { associatedtype T : Q } class C<T> : P where T : Q {} func foo<U, T>(_: U, _: T) where U : P, U : C<T> {}
<stdin>:6:36: warning: redundant conformance constraint 'U': 'P' func foo<U, T>(_: U, _: T) where U : P, U : C<T> {} ^ <stdin>:6:43: note: conformance constraint 'U': 'P' implied here func foo<U, T>(_: U, _: T) where U : P, U : C<T> {} ^
let fn: @pseudogeneric () -> () = {}
public protocol P1 { associatedtype X } struct A { } protocol P2: P1 { associatedtype X = A func foo() } public struct B {} extension B: P2 { }
(edited)<stdin>:15:1: error: type 'B' does not conform to protocol 'P2' extension B: P2 { ^ Unhandled Decl kind UNREACHABLE executed at /home/buildnode/jenkins/workspace/oss-swift-5.0-package-linux-ubuntu-16_04/swift/lib/AST/DeclContext.cpp:893! Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinux.build/module.modulemap -module-name main -lLibraries /usr/bin/swift[0x462b784] /usr/bin/swift[0x4629550] /usr/bin/swift[0x462b932] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fdd299dc390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7fdd2811b428] /lib/x86_64-linux-gnu/libc.so.6(ab
(edited)<stdin>:15:1: error: type 'B' does not conform to protocol 'P2' extension B: P2 { ^ <stdin>:10:10: note: protocol requires function 'foo()' with type '() -> ()'; do you want to add a stub? func foo() ^
<stdin>:15:1: error: type 'B' does not conform to protocol 'P2' extension B: P2 { ^ <stdin>:15:1: error: type alias 'X' must be declared public because it matches a requirement in public protocol 'P1' extension B: P2 { ^ main.B:2:22: note: mark the type alias as 'public' to satisfy the requirement public typealias X = main.A ^ <stdin>:10:10: note: protocol requires function 'foo()' with type '() -> ()'; do you want to add a stub? func foo() ^
if #available(macOS 10.14, *) { print("macOS", terminator: " ") } if #available(iOS 12.3, *) { print("iOS", terminator: " ") } if #available(tvOS 12.3, *) { print("tvOS", terminator: " ") } if #available(watchOS 5.2, *) { print("watchOS", terminator: " ") }
macOS iOS tvOS watchOS
macOS iOS tvOS watchOS
macOS iOS tvOS watchOS
macOS iOS tvOS watchOS
macOS iOS tvOS watchOS
let a = [1,2,3] let b = [2] let diff = a.difference(from: b) dump(diff)
▿ Swift.CollectionDifference<Swift.Int> ▿ insertions: 2 elements ▿ Swift.CollectionDifference<Swift.Int>.Change.insert ▿ insert: (3 elements) - offset: 0 - element: 1 - associatedWith: nil ▿ Swift.CollectionDifference<Swift.Int>.Change.insert ▿ insert: (3 elements) - offset: 2 - element: 3 - associatedWith: nil - removals: 0 elements
let a = [1,2,3] let b = [2] let diff = a.difference(from: b) print(diff)
CollectionDifference<Int>(insertions: [Swift.CollectionDifference<Swift.Int>.Change.insert(offset: 0, element: 1, associatedWith: nil), Swift.CollectionDifference<Swift.Int>.Change.insert(offset: 2, element: 3, associatedWith: nil)], removals: [])
class C { @inlinable func f() {} // error }
import UIKit protocol Component: UIView { associatedtype Model func activate(with model: Model) func deactivate() } class ImageComponent: UIImageView, Component { typealias Model = UIImage func activate(with model: ImageComponent.Model) { image = model } func deactivate() { image = nil } }
<stdin>:1:8: error: no such module 'UIKit' import UIKit ^
$ pbpaste import UIKit protocol Component: UIView { associatedtype Model func activate(with model: Model) func deactivate() } class ImageComponent: UIImageView, Component { typealias Model = UIImage func activate(with model: ImageComponent.Model) { image = model } func deactivate() { image = nil } $ pbpaste|swiftc -sdk $(xcrun -show-sdk-path -sdk iphonesimulator) -target x86_64-apple-ios12.2-simulator - -v Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5) Target: x86_64-apple-ios12.2-simulator /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c -primary-file - -target x86_64-apple-ios12.2-simulator -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk -color-diagnostics -module-name main -o /var/folders/kt/2mwy9b_56_7993x190pl_1fh0000gn/T/--eec0d7.o /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld /var/folders/kt/2mwy9b_56_7993x190pl_1fh0000gn/T/--eec0d7.o /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/clang/lib/darwin/libclang_rt.ios.a -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk -lobjc -lSystem -arch x86_64 -L /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator -ios_simulator_version_min 12.2.0 -no_objc_category_merging -o main $ ./main dyld: Library not loaded: /System/Library/Frameworks/UIKit.framework/UIKit Referenced from: /Users/norio/github/docker-swift/./main Reason: image not found [1] 91007 abort ./main
swiftc -sdk $(xcrun -show-sdk-path -sdk iphonesimulator) -target x86_64-apple-ios12.2-simulator
でビルド出来る。DYLD
の環境変数を調整すれば、実行も出来るかな?$ swiftc -emit-library m.swift $ swiftc -L . -lm -I . a.swift -Xlinker -rpath -Xlinker /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx $ ./a
@rpath
を使わずにリンクされてるから、それは効かないですね。 $ otool -L main main: /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.250.1) /System/Library/Frameworks/UIKit.framework/UIKit (compatibility version 1.0.0, current version 61000.0.0) @rpath/libswiftCore.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftCoreFoundation.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftCoreGraphics.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftCoreImage.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftDarwin.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftDispatch.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftFoundation.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftMetal.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftObjectiveC.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftQuartzCore.dylib (compatibility version 1.0.0, current version 1001.0.82) @rpath/libswiftUIKit.dylib (compatibility version 1.0.0, current version 1001.0.82)
install_name_tool
でUIKit
のパスを変えたら、@rpath/libswiftCore.dylib
をロードできないと言われた。 $ install_name_tool -change /System/Library/Frameworks/UIKit.framework/UIKit $(xcrun --show-sdk-platform-path --sdk iphoneos)/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/Frameworks/UIKit.framework/UIKit main $ ./main dyld: Library not loaded: @rpath/libswiftCore.dylib Referenced from: /Users/norio/github/docker-swift/./main Reason: image not found [1] 95202 abort ./main
(edited)rpath
を設定したらUIKit
にリンクされてるDocumentManager
をロードできないと言われ、ここで「実行時の環境を変えないとダメだ。」となりinstall_name_tool
を使う方法は終了。 $ pbpaste|swiftc -sdk $(xcrun --show-sdk-path --sdk iphonesimulator) -target x86_64-apple-ios12.2-simulator - -Xlinker -rpath -Xlinker $(xcrun --show-sdk-platform-path --sdk iphoneos)/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift $ install_name_tool -change /System/Library/Frameworks/UIKit.framework/UIKit $(xcrun --show-sdk-platform-path --sdk iphoneos)/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/Frameworks/UIKit.framework/UIKit main $ ./main dyld: Library not loaded: /System/Library/PrivateFrameworks/DocumentManager.framework/DocumentManager Referenced from: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot//System/Library/Frameworks/UIKit.framework/UIKit Reason: image not found [1] 95440 abort ./main
simctl
はアプリケーションバンドルを起動するコマンドしかないから、chroot的な仕組みを使うしか無さげ。/Users/norio/Library/Developer/XCPGDevices/8B3C76D2-C6BA-49FA-A03F-76AA29054FF3/data/Containers/Bundle/Application/269B83DA-876D-4C78-8197-D055CD0E0B5C/PlayNow-20190418-86360-2.app/PlayNow-20190418
DYLD
操作で実行出来た。 $ DYLD_FRAMEWORK_PATH=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks DYLD_FALLBACK_LIBRARY_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_FALLBACK_FRAMEWORK_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks DYLD_LIBRARY_PATH= ./main
rpath
設定は必要。 $ pbpaste import UIKit print("UIKit") $ pbpaste|swiftc -sdk $(xcrun --show-sdk-path --sdk iphonesimulator) -target x86_64-apple-ios12.2-simulator - -Xlinker -rpath -Xlinker $(xcrun --show-sdk-platform-path --sdk iphoneos)/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift $ DYLD_FRAMEWORK_PATH=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks DYLD_FALLBACK_LIBRARY_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_FALLBACK_FRAMEWORK_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks DYLD_LIBRARY_PATH= ./main UIKit
UIKit
をリンクして動かすことは出来た。DYLD_*
環境変数は、playgroundが実行してるアプリケーションに渡されてたものを全部記述しました。 (edited)ps axe|grep プロセス名
ですね。grep
のプロセスの情報が出ます。 (edited)DYLD_FALLBACK_LIBRARY_PATH
にusr/lib/swift
の分も追加すれば、rpath
指定無しでいける。 $ ROOT_PATH=$(xcrun --show-sdk-platform-path --sdk iphoneos)/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot && \ DYLD_FALLBACK_FRAMEWORK_PATH=$ROOT_PATH/System/Library/Frameworks \ DYLD_FALLBACK_LIBRARY_PATH=$ROOT_PATH/usr/lib:$ROOT_PATH/usr/lib/swift \ DYLD_LIBRARY_PATH= \ DYLD_ROOT_PATH=$ROOT_PATH \ ./main
(edited)DYLD_LIBRARY_PATH=
は無くても良さげ。simctl
とjq
で.simruntime
の場所を取得する方法に書き換えると $ ROOT_PATH=$(xcrun simctl list -j runtimes ios|jq -r '.runtimes[-1]|.bundlePath')/Contents/Resources/RuntimeRoot && \ DYLD_FALLBACK_FRAMEWORK_PATH=$ROOT_PATH/System/Library/Frameworks \ DYLD_FALLBACK_LIBRARY_PATH=$ROOT_PATH/usr/lib:$ROOT_PATH/usr/lib/swift \ DYLD_ROOT_PATH=$ROOT_PATH \ ./main
が一番シンプルな記述かな。 (edited)$ pbpaste import UIKit protocol Component: UIView { associatedtype Model func activate(with model: Model) func deactivate() } class ImageComponent: UIImageView, Component { typealias Model = UIImage func activate(with model: ImageComponent.Model) { image = model } func deactivate() { image = nil } } print("UIKit") $ pbpaste|swiftc -sdk $(xcrun --show-sdk-path --sdk iphonesimulator) -target x86_64-apple-ios12.2-simulator - $ ROOT_PATH=$(xcrun simctl list -j runtimes ios|jq -r '.runtimes[-1]|.bundlePath')/Contents/Resources/RuntimeRoot && \ DYLD_FALLBACK_FRAMEWORK_PATH=$ROOT_PATH/System/Library/Frameworks \ DYLD_FALLBACK_LIBRARY_PATH=$ROOT_PATH/usr/lib:$ROOT_PATH/usr/lib/swift \ DYLD_ROOT_PATH=$ROOT_PATH \ ./main UIKit
-target x86_64-apple-ios12.2-simulator
が決め打ちになっちゃうのだけ気持ちが悪いな。swiftc
へ渡す-target
って任意なの?-target x86_64-apple-ios12
までは短く出来たけど、無くすまでは無理だった。-Xlinker
で-ios_simulator_version_min
を指定する必要が出てきそうです。$ pbpaste|swiftc -sdk $(xcrun --show-sdk-path --sdk iphonesimulator) -target x86_64-apple-ios - -v <unknown>:0: error: Swift requires a minimum deployment target of iOS 7
$ jq -r .Version $(xcrun --show-sdk-path --sdk iphonesimulator)/SDKSettings.json 12.2
辺りかな。 (edited)/System/iOSSupport/System/Library/Frameworks/UIKit.framework
とかMojaveにあるし。/System/iOSSupport
を渡すとこんな感じ。 $ ROOT_PATH=/System/iOSSupport && \ DYLD_FALLBACK_FRAMEWORK_PATH=$ROOT_PATH/System/Library/Frameworks \ DYLD_FALLBACK_LIBRARY_PATH=$ROOT_PATH/usr/lib:$ROOT_PATH/usr/lib/swift \ DYLD_ROOT_PATH=$ROOT_PATH \ ./main dyld: mach-o, but built for simulator (not macOS) [1] 7681 abort DYLD_FALLBACK_FRAMEWORK_PATH=$ROOT_PATH/System/Library/Frameworks = = ./main
$ otool -l /System/iOSSupport/System/Library/Frameworks/UIKit.framework/UIKit … Load command 7 cmd LC_BUILD_VERSION cmdsize 32 platform iosmac sdk 10.14 minos 12.0 ntools 1 tool ld version 450.1 … $ otool -l /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/UIKit.framework/UIKit … Load command 7 cmd LC_BUILD_VERSION cmdsize 32 platform iossimulator sdk 12.2 minos 12.2 ntools 1 tool ld version 450.1
platform iosmac
swift-5.1-DEVELOPMENT-SNAPSHOT-2019-04-16-a
が出た。 @swift-5.1.5 -versionSwift version 5.0-dev (LLVM f961e3dd74, Swift 85a776dac0) Target: x86_64-unknown-linux-gnu
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
5.1-DEVELOPMENT-SNAPSHOT-2019-04-16-a
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
protocol Animal {} struct Cat: Animal {} func makeAnimal() -> some Animal { return Cat() } print(makeAnimal())
(edited)<stdin>:3:26: error: consecutive statements on a line must be separated by ';' func makeAnimal() -> some Animal { ^ ; <stdin>:3:22: error: use of undeclared type 'some' func makeAnimal() -> some Animal { ^~~~ <stdin>:3:27: error: 'Animal' cannot be constructed because it has no accessible initializers func makeAnimal() -> some Animal { ^
protocol P {} extension Int : P {} func f() -> some P { return 3 }
(edited)<stdin>:3:17: error: consecutive statements on a line must be separated by ';' func f() -> some P { return 3 } ^ ; <stdin>:3:13: error: use of undeclared type 'some' func f() -> some P { return 3 } ^~~~ <stdin>:3:18: error: 'P' cannot be constructed because it has no accessible initializers func f() -> some P { return 3 } ^
protocol Animal {} struct Cat: Animal {} func makeAnimal() -> some Animal { return Cat() } print(makeAnimal())
<stdin>:3:26: error: consecutive statements on a line must be separated by ';' func makeAnimal() -> some Animal { ^ ; <stdin>:3:22: error: use of undeclared type 'some' func makeAnimal() -> some Animal { ^~~~ <stdin>:3:27: error: 'Animal' cannot be constructed because it has no accessible initializers func makeAnimal() -> some Animal { ^
print("👶".unicodeScalars.first?.properties.isEmoji)
<stdin>:1:36: error: value of type 'Unicode.Scalar.Properties' has no member 'isEmoji' print("👶".unicodeScalars.first?.properties.isEmoji)
"👶".unicodeScalars.first!.properties.isEmoji
(edited)<stdin>:1:41: error: value of type 'Unicode.Scalar.Properties' has no member 'isEmoji' "👶".unicodeScalars.first!.properties.isEmoji
(edited)let scalars: [Unicode.Scalar] = ["😎", "$", "0"] for s in scalars { print(s, "-->", s.isEmoji) } // 😎 --> true // $ --> false // 0 --> true
<stdin>:3:23: error: value of type 'Unicode.Scalar' has no member 'isEmoji' print(s, "-->", s.isEmoji) ~ ^~~~~~~
let scalars: [Unicode.Scalar] = ["😎", "$", "0"] scalars.forEach { dump($0.properties) }
(edited)▿ Swift.Unicode.Scalar.Properties - _scalar: "\u{0001F60E}" ▿ Swift.Unicode.Scalar.Properties - _scalar: "$" ▿ Swift.Unicode.Scalar.Properties - _scalar: "0"
(edited)import Foundation print("👶".unicodeScalars.first?.properties)
(edited)Optional(Swift.Unicode.Scalar.Properties(_scalar: "\u{0001F476}"))
stderr:<stdin>:2:7: warning: expression implicitly coerced from 'Unicode.Scalar.Properties?' to 'Any' print("👶".unicodeScalars.first?.properties) <stdin>:2:36: note: provide a default value to avoid this warning print("👶".unicodeScalars.first?.properties) <stdin>:2:36: note: force-unwrap the value to avoid this warning print("👶".unicodeScalars.first?.properties) <stdin>:2:36: note: explicitly cast to 'Any' with 'as Any' to silence this warning print("👶".unicodeScalars.first?.properties)
(edited)#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // FIXME: These properties were introduced in ICU 57, but Ubuntu 16.04 comes // with ICU 55 so the values won't be correct there. Exclude them on // non-Darwin platforms for now; bundling ICU with the toolchain would resolve // this and other inconsistencies (https://bugs.swift.org/browse/SR-6076). /// A Boolean value indicating whether the scalar has an emoji /// presentation, whether or not it is the default. 略 @available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *) public var isEmoji: Bool { return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI) }
some
が入るのは次かな。 @swift-5.1.5
protocol Animal {} struct Cat: Animal {} func makeAnimal() -> some Animal { return Cat() } print(makeAnimal())
(edited)<stdin>:3:26: error: consecutive statements on a line must be separated by ';' func makeAnimal() -> some Animal { ^ ; <stdin>:3:22: error: use of undeclared type 'some' func makeAnimal() -> some Animal { ^~~~ <stdin>:3:27: error: 'Animal' cannot be constructed because it has no accessible initializers func makeAnimal() -> some Animal { ^
(edited)protocol Animal {} struct Cat: Animal {} func makeAnimal() -> some Animal { return Cat() } print(makeAnimal())
(edited)protocol P1 {} protocol P2 {} extension Int : P1 {} extension Int : P2 {} func f() -> some P1 { return 0 } func f() -> some P2 { return 0 }
swift: /home/buildnode/jenkins/workspace/oss-swift-package-linux-ubuntu-16_04/swift/lib/SIL/SILFunctionBuilder.cpp:112: swift::SILFunction *swift::SILFunctionBuilder::getOrCreateFunction(swift::SILLocation, swift::SILDeclRef, swift::ForDefinition_t, swift::ProfileCounter): Assertion `fn->getLoweredFunctionType() == constantType' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -module-name main 1. Swift version 5.0-dev (LLVM 082dec2e22, Swift f5ba89d372) 2. While emitting SIL for 'f()' (at <stdin>:6:1) /usr/bin/swift[0x48f7534] /usr/bin/swift[0x48f5150] /usr/bin/swift[0x48f7958] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fc231aaf390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7fc2301ee428] /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7fc2301f002a] /lib/x86_64-linux-gnu/libc.so.6(+0x2dbd7)[0x7fc2301e6bd7] /lib/x86_64-linux-gnu/libc.so.6(+0x2dc82)[0x7fc2301e6c82] /usr/bin/swift[0xdf2d10] /usr/bin/swift[0x893a8c] /usr/bin/swift[0x89433d] /usr/bin/swift[0x89a2ec] /usr/bin/swift[0x89b334] /usr/bin/swift[0x89b93b] /usr/bin/swift[0x508302] /usr/bin/swift[0x504b9f] /usr/bin/swift[0x4a002d] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fc2301d9830] /usr/bin/swift[0x49fb89]
protocol P1 {} protocol P2 {} extension Int : P1 {} extension Int : P2 {} func f() -> some P1 { return 0 } func f() -> some P2 { return 0 }
swift: /home/buildnode/jenkins/workspace/oss-swift-5.1-package-linux-ubuntu-16_04/swift/lib/SIL/SILFunctionBuilder.cpp:108: swift::SILFunction *swift::SILFunctionBuilder::getOrCreateFunction(swift::SILLocation, swift::SILDeclRef, swift::ForDefinition_t, swift::ProfileCounter): Assertion `fn->getLoweredFunctionType() == constantType' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -module-name main 1. While emitting SIL for 'f()' (at <stdin>:6:1) /usr/bin/swift[0x48e9374] /usr/bin/swift[0x48e6f90] /usr/bin/swift[0x48e9798] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fcf15036390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7fcf13775428] /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7fcf1377702a] /lib/x86_64-linux-gnu/libc.so.6(+0x2dbd7)[0x7fcf1376dbd7] /lib/x86_64-linux-gnu/libc.so.6(+0x2dc82)[0x7fcf1376dc82] /usr/bin/swift[0xdda2b0] /usr/bin/swift[0x89124c] /usr/bin/swift[0x891afd] /usr/bin/swift[0x897d7c] /usr/bin/swift[0x898da4] /usr/bin/swift[0x8993ab] /usr/bin/swift[0x5081da] /usr/bin/swift[0x504a8f] /usr/bin/swift[0x4a000d] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fcf13760830] /usr/bin/swift[0x49fb89]
protocol P1 {} protocol P2 {} extension Int : P1 {} extension Int : P2 {} func f() -> some P1 { return Int(0) } func f() -> some P2 { return Int(0) }
swift: /home/buildnode/jenkins/workspace/oss-swift-package-linux-ubuntu-16_04/swift/lib/SIL/SILFunctionBuilder.cpp:112: swift::SILFunction *swift::SILFunctionBuilder::getOrCreateFunction(swift::SILLocation, swift::SILDeclRef, swift::ForDefinition_t, swift::ProfileCounter): Assertion `fn->getLoweredFunctionType() == constantType' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -module-name main 1. Swift version 5.0-dev (LLVM 082dec2e22, Swift f5ba89d372) 2. While emitting SIL for 'f()' (at <stdin>:6:1) /usr/bin/swift[0x48f7534] /usr/bin/swift[0x48f5150] /usr/bin/swift[0x48f7958] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7ff7202b0390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7ff71e9ef428] /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7ff71e9f102a] /lib/x86_64-linux-gnu/libc.so.6(+0x2dbd7)[0x7ff71e9e7bd7] /lib/x86_64-linux-gnu/libc.so.6(+0x2dc82)[0x7ff71e9e7c82] /usr/bin/swift[0xdf2d10] /usr/bin/swift[0x893a8c] /usr/bin/swift[0x89433d] /usr/bin/swift[0x89a2ec] /usr/bin/swift[0x89b334] /usr/bin/swift[0x89b93b] /usr/bin/swift[0x508302] /usr/bin/swift[0x504b9f] /usr/bin/swift[0x4a002d] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7ff71e9da830] /usr/bin/swift[0x49fb89]
func redeclaration() -> some P { return 0 } // expected-note{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 }
(edited)protocol P1 {} protocol P2 {} extension Int : P1 {} extension Int : P2 {} func f() -> some P1 { return Int(0) } func f() -> some P2 { return Int(0) }
protocol P1 {} protocol P2 {} extension Int : P1 {} extension Int : P2 {} func f() -> some P1 { return Int(0) } func f() -> some P2 { return Int(0) } func r<T: P1>(_ a: T) { print(a) } r(f())
(edited)swift: /home/buildnode/jenkins/workspace/oss-swift-5.1-package-linux-ubuntu-16_04/swift/lib/SIL/SILFunctionBuilder.cpp:108: swift::SILFunction *swift::SILFunctionBuilder::getOrCreateFunction(swift::SILLocation, swift::SILDeclRef, swift::ForDefinition_t, swift::ProfileCounter): Assertion `fn->getLoweredFunctionType() == constantType' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -module-name main 1. While emitting SIL for 'f()' (at <stdin>:6:1) /usr/bin/swift[0x48e9374] /usr/bin/swift[0x48e6f90] /usr/bin/swift[0x48e9798] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f0ffb06b390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7f0ff97aa428] /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7f0ff97ac02a] /lib/x86_64-linux-gnu/libc.so.6(+0x2dbd7)[0x7f0ff97a2bd7] /lib/x86_64-linux-gnu/libc.so.6(+0x2dc82)[0x7f0ff97a2c82] /usr/bin/swift[0xdda2b0] /usr/bin/swift[0x89124c] /usr/bin/swift[0x891afd] /usr/bin/swift[0x897d7c] /usr/bin/swift[0x898da4] /usr/bin/swift[0x8993ab] /usr/bin/swift[0x5081da] /usr/bin/swift[0x504a8f] /usr/bin/swift[0x4a000d] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f0ff9795830] /usr/bin/swift[0x49fb89]
import Foundation let data = Data([1, 2, 3]) print(data.range(of: Data([1, 2, 3])) ?? []) print(data.firstRange(of: Data([1, 2, 3])) ?? [])
(edited)import Foundation let data = Data([1, 2, 3, 2, 1]) print(data.range(of: Data([1]), options: .backwards) ?? []) print(data.lastRange(of: Data([1])) ?? [])
(edited)import Foundation let data = Data([1, 2, 3]) print(data.range(of: Data([1]), options: .backwards, in: data.startIndex..<data.endIndex) ?? []) print(data.lastRange(of: Data([1]), in: data.startIndex..<data.endIndex) ?? [])
(edited)Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -module-name main 1. Swift version 5.0-dev (LLVM 082dec2e22, Swift 87e1efd1a2) /usr/bin/swift[0x48fde14] /usr/bin/swift[0x48fba30] /usr/bin/swift[0x48fe238] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f02906e8390] /usr/lib/swift/linux/libFoundation.so($s10Foundation4DataV15_RepresentationOys5UInt8VSicig+0x1b3)[0x7f028930b133]
(edited)Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOLinux.build/module.modulemap -module-name main -lLibraries /usr/bin/swift[0x4626bd4] /usr/bin/swift[0x46249a0] /usr/bin/swift[0x4626d82] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f14d1559390] /usr/lib/swift/linux/libFoundation.so($s10Foundation4DataV15_RepresentationOys5UInt8VSicig+0x1b3)[0x7f14c9cc7203]
(edited)import Foundation let data = Data([1, 2, 3]) let tests = [Data([1]), Data([1, 2]), Data([1, 2, 3])] for test in tests { let range = data.firstRange(of: test) print("\(range)") }
Optional(Range(0..<1)) Optional(Range(0..<1)) nil
stderr:<stdin>:8:14: warning: string interpolation produces a debug description for an optional value; did you mean to make this explicit? print("\(range)") ^~~~~ <stdin>:8:14: note: use 'String(describing:)' to silence this warning print("\(range)") ^~~~~ String(describing: ) <stdin>:8:14: note: provide a default value to avoid this warning print("\(range)") ^~~~~ ?? <#default value#>
import Foundation let data = Data([1, 2, 3]) let tests = [Data([1]), Data([1, 2]), Data([1, 2, 3])] for test in tests { let range = (data as NSData).firstRange(of: test) print("\(range)") }
(edited)Optional(Range(0..<1)) Optional(Range(0..<2)) Optional(Range(0..<3))
stderr:<stdin>:8:14: warning: string interpolation produces a debug description for an optional value; did you mean to make this explicit? print("\(range)") ^~~~~ <stdin>:8:14: note: use 'String(describing:)' to silence this warning print("\(range)") ^~~~~ String(describing: ) <stdin>:8:14: note: provide a default value to avoid this warning print("\(range)") ^~~~~ ?? <#default value#>
(edited)last
は 最後
だと錯覚していたwwwDataProtocol.lastRange(of:)
の件、apple/swiftの(つまりDarwin用の)swift-5.0-branchだけ正しい状態だったので、まずapple/swiftのmasterに修正のPR出してみました https://github.com/apple/swift/pull/25065 (edited)import Foundation :print_decl URLSession import FoundationNetworking
@available(*, unavailable, message: "This type has moved to the FoundationNetworking module. Import that module to use it.") typealias URLSession = AnyObject
stderr:<REPL Input>:1:8: error: no such module 'FoundationNetworking' import FoundationNetworking ^
indirect enum A { case case1 case case2(A, B) case case3(A, A, B) } indirect enum B { case case4(B) case case5 case case6 } func foo(_ a: A) { switch a { case .case2: break } }
<stdin>:13:5: error: switch must be exhaustive switch a { ^ <stdin>:13:5: note: add missing case: '.case1' switch a { ^ <stdin>:13:5: note: add missing case: '.case3(_, _, _)' switch a { ^
<stdin>:13:5: error: switch must be exhaustive switch a { ^ <stdin>:13:5: note: add missing case: '.case1' switch a { ^ <stdin>:13:5: note: add missing case: '.case3(_, _, _)' switch a { ^
import Foundation public protocol NMBComparable { func NMB_compare(_ otherObject: NMBComparable!) -> ComparisonResult } extension NSNumber: NMBComparable { public func NMB_compare(_ otherObject: NMBComparable!) -> ComparisonResult { return compare(otherObject as! NSNumber) } } func take<T: Comparable>(_ a: T, _ b: T) {} func take<T: NMBComparable>(_ a: T, _ b: T) {} take(1, 2) take(NSNumber(value: 1), NSNumber(value: 2)) take(1, NSNumber(value: 2)) take(NSNumber(value: 1), 2)
(edited)<stdin>:17:1: error: ambiguous use of 'take' take(NSNumber(value: 1), NSNumber(value: 2)) ^ <stdin>:13:6: note: found this candidate func take<T: Comparable>(_ a: T, _ b: T) {} ^ <stdin>:14:6: note: found this candidate func take<T: NMBComparable>(_ a: T, _ b: T) {} ^ <stdin>:18:1: error: ambiguous use of 'take' take(1, NSNumber(value: 2)) ^ <stdin>:13:6: note: found this candidate func take<T: Comparable>(_ a: T, _ b: T) {} ^ <stdin>:14:6: note: found this candidate func take<T: NMBComparable>(_ a: T, _ b: T) {} ^ <stdin>:19:1: error: ambiguous use of 'take' take(NSNumber(value: 1), 2) ^ <stdin>:13:6: note: found this candidate func take<T: Comparable>(_ a: T, _ b: T) {} ^ <stdin>:14:6: note: found this candidate func take<T: NMBComparable>(_ a: T, _ b: T) {} ^
(edited)<stdin>:17:1: error: ambiguous use of 'take' take(NSNumber(value: 1), NSNumber(value: 2)) ^ <stdin>:13:6: note: found this candidate func take<T: Comparable>(_ a: T, _ b: T) {} ^ <stdin>:14:6: note: found this candidate func take<T: NMBComparable>(_ a: T, _ b: T) {} ^ <stdin>:18:1: error: ambiguous use of 'take' take(1, NSNumber(value: 2)) ^ <stdin>:13:6: note: found this candidate func take<T: Comparable>(_ a: T, _ b: T) {} ^ <stdin>:14:6: note: found this candidate func take<T: NMBComparable>(_ a: T, _ b: T) {} ^ <stdin>:19:1: error: ambiguous use of 'take' take(NSNumber(value: 1), 2) ^ <stdin>:13:6: note: found this candidate func take<T: Comparable>(_ a: T, _ b: T) {} ^ <stdin>:14:6: note: found this candidate func take<T: NMBComparable>(_ a: T, _ b: T) {} ^
(edited)import Foundation func take<T: Comparable>(_ a: T, _ b: T) {} take(NSNumber(value: 1), NSNumber(value: 2))
<stdin>:3:6: error: argument type 'NSNumber' does not conform to expected type 'Comparable' take(NSNumber(value: 1), NSNumber(value: 2)) ^
@ _propertyWrapper enum Lazy<Value> { case uninitialized(() -> Value) case initialized(Value) init(initialValue: @autoclosure @escaping () -> Value) { self = .uninitialized(initialValue) } var value: Value { mutating get { switch self { case .uninitialized(let initializer): let value = initializer() self = .initialized(value) return value case .initialized(let value): return value } } set { self = .initialized(newValue) } } } @Lazy var foo = 1738
func isOne(_ x: Int) -> Bool { return x == 1 } func test_assertionSuccess() { #assert(isOne(1)) #assert(isOne(1), "1 is not 1") } func test_assertionFailure() { #assert(isOne(2)) // expected-error{{assertion failed}} #assert(isOne(2), "2 is not 1") // expected-error{{2 is not 1}} }
<stdin>:11:3: error: assertion failed #assert(isOne(2)) // expected-error{{assertion failed}} ^ <stdin>:12:3: error: 2 is not 1 #assert(isOne(2), "2 is not 1") // expected-error{{2 is not 1}} ^
import FoundationNetworking
func f(g: () -> Int) -> String { "\(g())" } print(f { 42 })
@compilerEvaluable
にしなきゃいけなくて、 そうすると依存性切り離して使いたい関数を @compilerEvaluable
にするような運用はできないってことになるので、 普段使いできそうにないなーと#assert(1 < 2)
<stdin>:1:1: error: #assert is an experimental feature that is currently disabled #assert(1 < 2) ^
#assert(1 < 2)
swift: /home/buildnode/jenkins/workspace/oss-swift-5.1-package-linux-ubuntu-16_04/llvm/lib/Support/raw_ostream.cpp:735: uint64_t llvm::raw_fd_ostream::seek(uint64_t): Assertion `SupportsSeeking && "Stream does not support seeking!"' failed. Stack dump: 0. Program arguments: swift -frontend -c -enable-experimental-static-assert - swift[0x4938c34] swift[0x4936850] swift[0x4939058] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f7c86339390] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0x38)[0x7f7c84a78428] /lib/x86_64-linux-gnu/libc.so.6(abort+0x16a)[0x7f7c84a7a02a] /lib/x86_64-linux-gnu/libc.so.6(+0x2dbd7)[0x7f7c84a70bd7] /lib/x86_64-linux-gnu/libc.so.6(+0x2dc82)[0x7f7c84a70c82] swift[0x49196b0] swift[0x4919701] swift[0x4657dda] swift[0x4651a63] swift[0x45ed347] swift[0x1eaf048] swift[0x47b2e45] swift[0x47b3423] swift[0x5847c1] swift[0x50a4e4] swift[0x5058cf] swift[0x4a022d] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f7c84a63830] swift[0x49fda9]
class Animal { func foo() -> Int? { return nil } } class Cat: Animal { override func foo() -> Int { return 42 } } let animal: Animal = Cat() print(animal.foo()!)
class Animal { func foo() -> Int? { return nil } } class Cat: Animal { override func foo() -> Int { return 42 } override func foo() -> Int? { return nil } }
<stdin>:9:19: error: 'foo()' has already been overridden override func foo() -> Int? { return nil } ^ <stdin>:8:19: note: 'foo()' previously overridden here override func foo() -> Int { return 42 } ^
OpenCombine
https://github.com/broadwaylamb/OpenCombine をインポート出来るようにしました。 @swift-5.1.5
import OpenCombine let publisher = Just(28) _ = publisher .map { number in return "Antoine's age is \(number)" } .sink { (value) in print(value) }
(edited)Future
, Promise
は swift-nio 版のtypealias
+ extension https://github.com/vapor/core/blob/master/Sources/Async/Async%2BNIO.swift#L4-L8 swift-nioにはストリームぽいのは無かったと思う。 (edited)protocol Observable { associatedtype Element func subscribe(_ f: @escaping (Element) -> Void) } struct Just<T>: Observable { typealias Element = T let value: T func subscribe(_ f: @escaping (T) -> Void) { f(value) } } struct Map<Source: Observable, U>: Observable { typealias Element = U let source: Source let transformer: (Source.Element) -> U func subscribe(_ f: @escaping (U) -> Void) { source.subscribe { [transformer] element in f(transformer(element)) } } } extension Observable { func map<U>(_ f: @escaping (Element) -> U) -> Map<Self, U> { return Map(source: self, transformer: f) } } Just(value: 122) .map { $0.description } .map { $0.count } .subscribe { element in print(element.description) }
sil_stage canonical import Builtin import Swift import SwiftShims protocol Observable { associatedtype Element func subscribe(_ f: @escaping (Self.Element) -> ()) } struct Just<T> : Observable { typealias Element = T @_hasStorage let value: T { get } func subscribe(_ f: @escaping (T) -> ()) init(value: T) } struct Map<Source, U> : Observable where Source : Observable { typealias Element = U @_hasStorage let source: Source { get } @_hasStorage let transformer: (Source.Element) -> U { get } func subscribe(_ f: @escaping (U) -> ()) init(source: Source, transformer: @escaping (Source.Element) -> U) } extension Observable { func map<U>(_ f: @escaping (Self.Element) -> U) -> Map<Self, U> } // _swiftEmptyArrayStorage sil_global @_swiftEmptyArrayStorage : $_SwiftEmptyArrayStorage // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int64, 122 // user: %3 %3 = struct $Int (%2 : $Builtin.Int64) // users: %6, %4 debug_value %3 : $Int, let, name "$0", argno 1 // id: %4 %5 = alloc_stack $Int // users: %9, %8, %6 store %3 to %5 : $*Int // id: %6 // function_ref BinaryInteger.description.getter %7 = function_ref @$sSzsE11descriptionSSvg : $@convention(method) <τ_0_0 where τ_0_0 : BinaryInteger> (@in_guaranteed τ_0_0) -> @owned String // users: %32, %8 %8 = apply %7<Int>(%5) : $@convention(method) <τ_0_0 where τ_0_0 : BinaryInteger> (@in_guaranteed τ_0_0) -> @owned String // users: %51, %10, %11, %12, %14 dealloc_stack %5 : $*Int // id: %9 debug_value %8 : $String, let, name "element", argno 1 // id: %10 debug_value %8 : $String, let, name "element", argno 1 // id: %11 debug_value %8 : $String, let, name "$0", argno 1 // id: %12 // function_ref String.count
@inlinable
にした時点で実装が丸見えですからね。AppleがCombineをOSSにするつもりがなければ無理そう。import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
5.0.2-RELEASE
@available(macCatalyst 13.0, *) func f() {}
<stdin>:1:28: warning: unrecognized platform name 'macCatalyst' @available(macCatalyst 13.0, *) ^
import Foundation print(FileManager.default.fileExists(atPath: "/usr/bin/sourcekit-lsp"))
sourcekit-lsp
がtoolchainに含まれる様になったのか。struct Adder { var base: Int func callAsFunction(_ x: Int) -> Int { return x + base } } var adder = Adder(base: 3) print(adder(10)) // 13
call
に落ち着きそうだったんだけどcallFunction
になってcallAsFunction
になっていったfunc
の代わりに新しい予約語としてcall
で定義するとかの案もありました。 (edited)@callable
とかもあったな。struct Adder { var base: Int func callAsFunction(_ x: Int) -> Int { return x + base } } var adder = Adder(base: 3) [1].map(adder).forEach { print($0) }
<stdin>:10:5: error: cannot invoke 'map' with an argument list of type '(Adder)' [1].map(adder).forEach { print($0) } ^
struct Adder { var base: Int func callAsFunction(_ x: Int) -> Int { return x + base } } var adder = Adder(base: 3) [1].map(adder.callAsFunction).forEach { print($0) }
Swift version 5.0.3 (swift-5.0.3-RELEASE) Target: x86_64-unknown-linux-gnu
import SwiftyMath let a = RationalNumber(2, 3) print(a)
<unknown>:0: error: unknown argument: '--options="-I'
import SwiftyMath let a = RationalNumber(2, 3) print(a)
<stdin>:1:8: error: no such module 'SwiftyMath' import SwiftyMath ^
import SwiftyMath let a = RationalNumber(2, 3) print(a)
(edited)import SwiftyMath let a = RationalNumber(2, 3) print(a)
swift-4.2.1-RELEASE
/usercode/main.swift:1:8: error: no such module 'SwiftyMath' import SwiftyMath ^
import SwiftyMath let a = RationalNumber(2, 3) print(a)
import SwiftyMath let a = RationalNumber(2, 3) print(a)
swift-4.2.1-RELEASE
/usercode/main.swift:1:8: error: no such module 'SwiftyMath' import SwiftyMath ^
import SwiftyMath
import SwiftyMath typealias AlgebraicExtension<F, p: IrrPolynomialTP> = PolynomialQuotientRing<p> where p.CoeffRing == F typealias Q = RationalNumber typealias Qx = xPolynomial<Q> let x = Qx.indeterminate struct p1: IrrPolynomialTP { static let value = Qx(coeffs: -2, 0, 1) } typealias A = AlgebraicExtension<Q, p1> // A = Q[x]/p1 let α = A(x) print(α) print(α * α) print(α * α == 2) struct p2: IrrPolynomialTP { static let value = xPolynomial<Q>(coeffs: 1, 0, 1) } typealias B = AlgebraicExtension<Q, p2> // B = Q[x]/p2 let i = B(x) print(i) print(i * i) print(i * i == -1)
(edited)<stdin>:4:7: error: use of undeclared type 'PolynomialQuotientRing' = PolynomialQuotientRing<p> where p.CoeffRing == F ^~~~~~~~~~~~~~~~~~~~~~ <stdin>:7:16: error: use of undeclared type 'xPolynomial' typealias Qx = xPolynomial<Q> ^~~~~~~~~~~ <stdin>:11:8: error: type 'p1' does not conform to protocol 'PolynomialTP' struct p1: IrrPolynomialTP { ^ SwiftyMath.PolynomialTP:2:20: note: protocol requires nested type 'CoeffRing'; do you want to add it? associatedtype CoeffRing : Ring ^ SwiftyMath.PolynomialTP:3:20: note: protocol requires nested type 'x'; do you want to add it? associatedtype x : Indeterminate ^ <stdin>:24:24: error: use of unresolved identifier 'xPolynomial' static let value = xPolynomial<Q>(coeffs: 1, 0, 1) ^~~~~~~~~~~ SwiftyMath.MPolynomial:1:15: note: did you mean 'MPolynomial'? public struct MPolynomial<R> : Ring, Module where R : Ring { ^ SwiftyMath._Polynomial:1:15: note: did you mean '_Polynomial'? public struct _Polynomial<T, R, x> : Ring, Module where T : PolynomialType, R : Ring, x : Indeterminate { ^ SwiftyMath.Polynomial:1:18: note: did you mean 'Polynomial'? public typealias Polynomial<R, x> = SwiftyMath._Polynomial<SwiftyMath.NormalPolynomialType, R, x> ^ <stdin>:23:8: error: type 'p2' does not conform to protocol 'PolynomialTP' struct p2: IrrPolynomialTP { ^ SwiftyMath.PolynomialTP:2:20: note: protocol requires nested type 'CoeffRing'; do you want to add it? associatedtype CoeffRing : Ring ^ SwiftyMath.PolynomialTP:3:20: note: protocol requires nested type 'x'; do you want to add it? associatedtype x : Indeterminate ^
Swift version 5.1 (swift-5.1-RELEASE) Target: x86_64-unknown-linux-gnu
@dynamicMemberLookup struct Foo<Content> { let content: Content subscript<T>(dynamicMember keyPath: KeyPath<Content, T>) -> T { return content[keyPath: keyPath] } } print(Foo<Int>(content: 100).description)
struct Foo<Content> { let content: Content } @dynamicMemberLookup extension Foo { subscript<T>(dynamicMember keyPath: KeyPath<Content, T>) -> T { return content[keyPath: keyPath] } } print(Foo<Int>(content: 100).description)
<stdin>:5:1: error: '@dynamicMemberLookup' attribute cannot be applied to this declaration @dynamicMemberLookup ^~~~~~~~~~~~~~~~~~~~ <stdin>:12:30: error: value of type 'Foo<Int>' has no member 'description' print(Foo<Int>(content: 100).description) ~~~~~~~~~~~~~~~~~~~~~~ ^~~~~~~~~~~
class Parent { var id: Int init(id: Int) { self.id = id } } protocol Abstract: Parent { func printID() } class Child: Parent, Abstract { override init(id: Int) { super.init(id: id) } func printID() { print("Child: \(id)") } } let c = Child(id: 0) c.printID()
<stdin>:9:10: error: non-class type 'Abstract' cannot inherit from class 'Parent' protocol Abstract: Parent { ^ ~~~~~~
class Parent { var id: Int init(id: Int) { self.id = id } } protocol Abstract where Self: Parent { var name: String { get } } extension Abstract { func printProfile() { print("\(id) \(name)") } } class Child: Parent, Abstract { var name: String init(id: Int, name: String) { self.name = name super.init(id: id) } } let c = Child(id: 42, name: "hoge") c.printProfile()
import Foundation let locale = Locale(identifier: "ja") let data = try JSONEncoder().encode(locale) let decoded = try JSONDecoder().decode(Locale.self, from: data) print(locale == decoded) print(locale.hashValue == decoded.hashValue)
==
なのに hashValue
が同一にならないのはHashableとして誤りですねswift-3.0-RELEASE
から壊れてたのね。 https://github.com/apple/swift-corelibs-foundation/commit/80e0f056716497f30525ae423ab56602595d5b25Swift version 5.1.1 (swift-5.1.1-RELEASE) Target: x86_64-unknown-linux-gnu
@propertyWrapper struct Foo<Value> { var wrappedValue: Value var projectedValue: Self { self } } protocol Namespace { typealias MyFoo = Foo } struct Test { @Foo var val = 0 } struct MyTest: Namespace { @MyFoo var val = 0 } let t1 = Test() print(t1.val, t1.$val) let t2 = MyTest() print(t2.val, t2.$val)
(edited)<stdin>:18:5: error: unknown attribute 'MyFoo' @MyFoo ^ <stdin>:26:18: error: value of type 'MyTest' has no member '$val' print(t2.val, t2.$val) ~~ ^~~~
(edited)2019-10-13-a 5.1 5.0.3 5.0.2 5.0.1 5.0 4.2.2 4.2.1 4.1.3 4.1.2 4.1.1 4.1 4.0.3 4.0.2 4.0 3.1.1 3.1 3.0.2 3.0.1
let rows: [(id: Int, name1: String, name2: String)] = [ (0, "x", "y"), (1, "z", "w") ] let results1 = rows.flatMap { row in var entries = [(Int, String)]() entries.append((row.id, row.name1)) entries.append((row.id, row.name2)) return entries }
(edited)let rows: [(id: Int, name1: String, name2: String)] = [ (0, "x", "y"), (1, "z", "w") ] let results1 = rows.flatMap { row in var entries = [(Int, String)]() entries.append((row.id, row.name1)) entries.append((row.id, row.name2)) return entries }
swift-4.2.1-RELEASE
/usercode/main.swift:10:12: error: cannot convert return expression of type '[(Int, String)]' to return type 'String?' return entries ^~~~~~~ /usercode/main.swift:6:21: warning: 'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value let results1 = rows.flatMap { row in ^ /usercode/main.swift:6:21: note: use 'compactMap(_:)' instead let results1 = rows.flatMap { row in ^~~~~~~ compactMap
let rows: [(id: Int, name1: String, name2: String)] = [ (0, "x", "y"), (1, "z", "w") ] let results1 = rows.flatMap { row in var entries = [(Int, String)]() entries.append((row.id, row.name1)) entries.append((row.id, row.name2)) return entries }
let rows: [(id: Int, name1: String, name2: String)] = [ (0, "x", "y"), (1, "z", "w") ] let results1 = rows.flatMap { row in var entries = [(Int, String)]() entries.append((row.id, row.name1)) entries.append((row.id, row.name2)) return entries }
swift-5.1-RELEASE
/usercode/main.swift:10:12: error: cannot convert return expression of type '[(Int, String)]' to return type 'String?' return entries ^~~~~~~ /usercode/main.swift:6:21: error: 'flatMap' has been renamed to 'compactMap(_:)': Please use compactMap(_:) for the case where closure returns an optional value let results1 = rows.flatMap { row in ^~~~~~~ compactMap Swift.Collection:3:17: note: 'flatMap' was obsoleted in Swift 5.0 public func flatMap(_ transform: (Self.Element) throws -> String?) rethrows -> [String] ^
let rows = [10, 20] let results1 = rows.flatMap { row in var entries = [Int]() entries.append(row) return entries }
let rows = [10, 20] let results1 = rows.flatMap { row in var entries = [Int]() entries.append(row) return entries }
swift-5.1-RELEASE
/usercode/main.swift:5:12: error: cannot convert return expression of type '[Int]' to return type 'String?' return entries ^~~~~~~ /usercode/main.swift:2:21: error: 'flatMap' has been renamed to 'compactMap(_:)': Please use compactMap(_:) for the case where closure returns an optional value let results1 = rows.flatMap { row in ^~~~~~~ compactMap Swift.Collection:3:17: note: 'flatMap' was obsoleted in Swift 5.0 public func flatMap(_ transform: (Self.Element) throws -> String?) rethrows -> [String] ^
let rows = [10, 20] let results1 = rows.flatMap { row -> [Int] in var entries = [Int]() entries.append(row) return entries }
let rows = [10, 20] let results1 = rows.flatMap { row -> [Int] in var entries = [Int]() entries.append(row) return entries }
swift-5.1-RELEASE
let rows = [10, 20] let results1 = rows.flatMap { row in var entries = [Int]() entries.append(row) return entries }
let rows = [10, 20] let results1 = rows.flatMap { row in var entries = [Int]() entries.append(row) return entries }
swift-DEVELOPMENT-SNAPSHOT-2019-10-13-a
/usercode/main.swift:5:12: error: cannot convert return expression of type '[Int]' to return type 'String?' return entries ^~~~~~~ /usercode/main.swift:2:21: error: 'flatMap' has been renamed to 'compactMap(_:)': Please use compactMap(_:) for the case where closure returns an optional value let results1 = rows.flatMap { row in ^~~~~~~ compactMap Swift.Collection:3:17: note: 'flatMap' was obsoleted in Swift 5.0 public func flatMap(_ transform: (Self.Element) throws -> String?) rethrows -> [String] ^
struct View<Value> { typealias Value = Value var value: Value } print(View<Int>.Value.self)
<stdin>:2:23: error: type alias 'Value' references itself typealias Value = Value ^ <stdin>:2:15: note: type declared here typealias Value = Value ^
struct View<Value> { typealias Value = Value var value: Value } print(View<Int>.Value.self)
let a: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] let b = UnsafeRawPointer(a).load(fromByteOffset: 1, as: Int.self).littleEndian
let a: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] let b = UnsafeRawPointer(a).load(fromByteOffset: 1, as: Int.self).littleEndian
swift-5.1-RELEASE
Fatal error: load from misaligned raw pointer Current stack trace: 0 libswiftCore.so 0x00007fc6a04293c0 swift_reportError + 50 1 libswiftCore.so 0x00007fc6a049a230 _swift_stdlib_reportFatalError + 69 2 libswiftCore.so 0x00007fc6a0395c07 <unavailable> + 3349511 3 libswiftCore.so 0x00007fc6a02453c0 UnsafeRawPointer.load<A>(fromByteOffset:as:) + 88 5 swift 0x000000000052826e <unavailable> + 1213038 6 swift 0x000000000052cb52 <unavailable> + 1231698 7 swift 0x000000000051cc2f <unavailable> + 1166383 8 swift 0x000000000050b468 <unavailable> + 1094760 9 swift 0x0000000000506de1 <unavailable> + 1076705 10 swift 0x00000000004a022d <unavailable> + 655917 ...
let a: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] let b = UnsafeRawPointer(a).load(fromByteOffset: 8, as: Int.self).littleEndian
let a: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] let b = UnsafeRawPointer(a).load(fromByteOffset: 8, as: Int.self).littleEndian
swift-5.1-RELEASE
import Foundation let array: [UInt8] = [ 0x10, 0x20, 0x30, 0x40, 0x11, 0x21, 0x31, 0x41, 0x99] let a = array.withUnsafeBufferPointer { (buf) -> Int in buf.baseAddress!.withMemoryRebound(to: Int.self, capacity: 1) { (ip) in ip.pointee } } print(String(format: "%016llx", a), a == Int(bitPattern: 0x4131211140302010)) let b = array.withUnsafeBufferPointer { (buf) -> Int in buf.baseAddress!.advanced(by: 1).withMemoryRebound(to: Int.self, capacity: 1) { (ip) in ip.pointee } } print(String(format: "%016llx", b), b == Int(bitPattern: 0x9941312111403020)) print(MemoryLayout<Int>.size)
4131211140302010 true 9941312111403020 true 8
import Foundation let array: [UInt8] = [ 0x10, 0x20, 0x30, 0x40, 0x11, 0x21, 0x31, 0x41, 0x99] func reboundToInt(pointer: UnsafePointer<UInt8>) -> Int { return pointer.withMemoryRebound(to: Int.self, capacity: 1) { (ip) in ip.pointee } } func assumeToInt(pointer: UnsafePointer<UInt8>) -> Int { return UnsafeRawPointer(pointer).assumingMemoryBound(to: Int.self).pointee } let a = array.withUnsafeBufferPointer { (buf) -> Int in reboundToInt(pointer: buf.baseAddress!) } print(String(format: "%016llx", a), a == Int(bitPattern: 0x4131211140302010)) let b = array.withUnsafeBufferPointer { (buf) -> Int in reboundToInt(pointer: buf.baseAddress!.advanced(by: 1)) } print(String(format: "%016llx", b), b == Int(bitPattern: 0x9941312111403020)) let c = array.withUnsafeBufferPointer { (buf) -> Int in assumeToInt(pointer: buf.baseAddress!) } print(String(format: "%016llx", c), c == Int(bitPattern: 0x4131211140302010)) let d = array.withUnsafeBufferPointer { (buf) -> Int in assumeToInt(pointer: buf.baseAddress!.advanced(by: 1)) } print(String(format: "%016llx", d), d == Int(bitPattern: 0x9941312111403020))
4131211140302010 true 9941312111403020 true 4131211140302010 true 9941312111403020 true
import Foundation let array: [UInt8] = [ 0x10, 0x20, 0x30, 0x40, 0x11, 0x21, 0x31, 0x41, 0x99] func reboundToInt(pointer: UnsafePointer<UInt8>) -> Int { return pointer.withMemoryRebound(to: Int.self, capacity: 1) { (ip) in ip.pointee } } func assumeToInt(pointer: UnsafePointer<UInt8>) -> Int { let intp = UnsafeRawPointer(pointer).assumingMemoryBound(to: Int.self) print("[assume] p: \(Int(bitPattern: pointer))") print("[assume] intp: \(Int(bitPattern: intp))") return intp.pointee } let a = array.withUnsafeBufferPointer { (buf) -> Int in reboundToInt(pointer: buf.baseAddress!) } print(String(format: "%016llx", a), a == Int(bitPattern: 0x4131211140302010)) let b = array.withUnsafeBufferPointer { (buf) -> Int in reboundToInt(pointer: buf.baseAddress!.advanced(by: 1)) } print(String(format: "%016llx", b), b == Int(bitPattern: 0x9941312111403020)) let c = array.withUnsafeBufferPointer { (buf) -> Int in assumeToInt(pointer: buf.baseAddress!) } print(String(format: "%016llx", c), c == Int(bitPattern: 0x4131211140302010)) let d = array.withUnsafeBufferPointer { (buf) -> Int in assumeToInt(pointer: buf.baseAddress!.advanced(by: 1)) } print(String(format: "%016llx", d), d == Int(bitPattern: 0x9941312111403020))
4131211140302010 true 9941312111403020 true [assume] p: 156675312 [assume] intp: 156675312 4131211140302010 true [assume] p: 156675313 [assume] intp: 156675313 9941312111403020 true
import Foundation let array: [UInt8] = [ 0x10, 0x20, 0x30, 0x40, 0x11, 0x21, 0x31, 0x41, 0x99] func reboundToInt(pointer: UnsafePointer<UInt8>) -> Int { return pointer.withMemoryRebound(to: Int.self, capacity: 1) { (ip) in ip.pointee } } func assumeToInt(pointer: UnsafePointer<UInt8>) -> Int { let intp = UnsafeRawPointer(pointer).assumingMemoryBound(to: Int.self) print("[assume] p: \(Int(bitPattern: pointer))") print("[assume] intp: \(Int(bitPattern: intp))") return intp.pointee } func loadAsInt(pointer: UnsafePointer<UInt8>) -> Int { return UnsafeRawPointer(pointer).load(as: Int.self) } let a = array.withUnsafeBufferPointer { (buf) -> Int in reboundToInt(pointer: buf.baseAddress!) } print(String(format: "%016llx", a), a == Int(bitPattern: 0x4131211140302010)) let b = array.withUnsafeBufferPointer { (buf) -> Int in reboundToInt(pointer: buf.baseAddress!.advanced(by: 1)) } print(String(format: "%016llx", b), b == Int(bitPattern: 0x9941312111403020)) let c = array.withUnsafeBufferPointer { (buf) -> Int in assumeToInt(pointer: buf.baseAddress!) } print(String(format: "%016llx", c), c == Int(bitPattern: 0x4131211140302010)) let d = array.withUnsafeBufferPointer { (buf) -> Int in assumeToInt(pointer: buf.baseAddress!.advanced(by: 1)) } print(String(format: "%016llx", d), d == Int(bitPattern: 0x9941312111403020)) let e = array.withUnsafeBufferPointer { (buf) -> Int in loadAsInt(pointer: buf.baseAddress!) } print(String(format: "%016llx", e), e == Int(bitPattern: 0x4131211140302010)) let f = array.withUnsafeBufferPointer { (buf) -> Int in loadAsInt(pointer: buf.baseAddress!.advanced(by: 1)) } print(String(format: "%016llx", f), f == Int(bitPattern: 0x9941312111403020))
(edited)Fatal error: load from misaligned raw pointer Current stack trace: 0 libswiftCore.so 0x00007f98e95ea3c0 swift_reportError + 50 1 libswiftCore.so 0x00007f98e965b230 _swift_stdlib_reportFatalError + 69 2 libswiftCore.so 0x00007f98e9556c07 <unavailable> + 3349511 3 libswiftCore.so 0x00007f98e94063c0 UnsafeRawPointer.load<A>(fromByteOffset:as:) + 88 8 libswiftCore.so 0x00007f98e93633b0 Array.withUnsafeBufferPointer<A>(_:) + 38 10 swift 0x00000000005283fe <unavailable> + 1213438 11 swift 0x000000000052cce2 <unavailable> + 1232098 12 swift 0x000000000051cdbf <unavailable> + 1166783 13 swift 0x000000000050b5e8 <unavailable> + 1095144 14 swift 0x0000000000506f41 <unavailable> + 1077057 15 swift 0x00000000004a033d <unavailable> + 656189 16 libc.so.6 0x00007f98ec28a740 __libc_start_main + 240 17 swift 0x000000000049feb9 <unavailable> + 655033 Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux/debug -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/OpenCombine/Sources/COpenCombineHelpers/include -module-cache-path /Libraries/.build/x86_64-unknown-linux/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=
(edited)-Ounchecked
でも無効化しないです。 uncheckedで消せるのはprecondition。 (edited)4131211140302010 true 9941312111403020 true [assume] p: 4300947488 [assume] intp: 4300947488 4131211140302010 true [assume] p: 4300947489 [assume] intp: 4300947489 9941312111403020 true 4131211140302010 true 9941312111403020 true Program ended with exit code: 0
swift
ってsandbox内で動くのかな?Xcode Serverはどうしてるのだろう?if let line = readLine() { print(line) }
Swift version 5.1 (swift-5.1.2-RELEASE) Target: x86_64-unknown-linux-gnu
public extension Int {}
class Animal {} func f(_ a: AnyObject) { } f(Animal.self)
<stdin>:3:3: error: argument type 'Animal.Type' does not conform to expected type 'AnyObject' f(Animal.self) ^
Swift version 5.1.2 (swift-5.1.2-RELEASE) Target: x86_64-unknown-linux-gnu
struct Pair<T, U> { let values: (T, U) init(_ t: T, _ u: U) { values = (t, u) } } let pair = Pair(1, "2") print(pair[keyPath: \Pair.values.0]) print(pair[keyPath: \Pair.values.1])
<stdin>:9:7: error: value of type 'Pair<Int, String>' has no subscripts print(pair[keyPath: \Pair.values.0]) ^~~~ <stdin>:10:7: error: value of type 'Pair<Int, String>' has no subscripts print(pair[keyPath: \Pair.values.1]) ^~~~
Swift version 5.1.3 (swift-5.1.3-RELEASE) Target: x86_64-unknown-linux-gnu
let evens = (1...10).lazy .filter { ($0 % 2) == 0 } .filter { print($0, terminator: ","); return true } _ = evens.count
1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,
2,4,6,8,10,
let evens = (1...10).lazy .filter { ($0 % 2) == 0 } .filter { print($0, terminator: ","); return true } print("\nfirst", evens.first!, "\ncount:", evens.count)
1,2,1,2,3,4,5,6,7,8,9,10, first 2 count: 5
protocol A { func isEquatable() -> Bool } extension A { func isEquatable() -> Bool { return false } } extension A where Self: Equatable { func isEquatable() -> Bool { return true } } struct Foo: A { } extension String: A { } print(Foo().isEquatable()) print(String().isEquatable())
(edited)<T: P>
になってるコンテキストでちゃんと動くのかな?protocol A { func isEquatable() -> Bool } extension A { func isEquatable() -> Bool { return false } } extension A where Self: Equatable { func isEquatable() -> Bool { return true } } struct Foo: A { } struct Foo2: A, Equatable { } extension String: A { } print("direct") print(Foo().isEquatable()) print(Foo2().isEquatable()) print(String().isEquatable()) func generics<X: A>(arg: X) { print(arg.isEquatable()) } func existential(arg: A) { print(arg.isEquatable()) } print("from generics") generics(arg: Foo()) generics(arg: Foo2()) generics(arg: String()) print("from existential") existential(arg: Foo()) existential(arg: Foo2()) existential(arg: String())
(edited)direct false true true from generics false true true from existential false true true
(edited)protocol AnyEquatableBase { associatedtype Value var value: Value { get } func isEqual(to other: Self) -> Bool } extension AnyEquatableBase { func isEqual(to other: Self) -> Bool { false } } extension AnyEquatableBase where Value: Equatable { func isEqual(to other: Self) -> Bool { value == other.value } } struct AnyEquatable<T>: AnyEquatableBase { var value: T } print(AnyEquatable(value: "abc").isEqual(to: AnyEquatable(value: "abc"))) print(AnyEquatable(value: ()).isEqual(to: AnyEquatable(value: ()))) print(AnyEquatable(value: String.self).isEqual(to: AnyEquatable(value: String.self))) print(AnyEquatable(value: { }).isEqual(to: AnyEquatable(value: { })))
true false false false
protocol AnyEquatableBase { associatedtype Value var value: Value { get } func isEqual(to other: Self) -> Bool } extension AnyEquatableBase { func isEqual(to other: Self) -> Bool { false } } extension AnyEquatableBase where Value: Equatable { func isEqual(to other: Self) -> Bool { value == other.value } } struct AnyEquatable<T>: AnyEquatableBase { var value: T } print(AnyEquatable(value: "abc" as Any).isEqual(to: AnyEquatable(value: "abc" as Any)))
protocol AnyEquatableBase { associatedtype Value var value: Value { get } func isEqual(to other: Self) -> Bool } extension AnyEquatableBase { func isEqual(to other: Self) -> Bool { false } } extension AnyEquatableBase where Value: Equatable { func isEqual(to other: Self) -> Bool { value == other.value } } struct AnyEquatable<T>: AnyEquatableBase { var value: T } func check<T>(lhs: T, rhs: T) -> Bool { AnyEquatable(value: lhs).isEqual(to: AnyEquatable(value: rhs)) } print(check(lhs: "test", rhs: "test"))
protocol AnyEquatableBase { associatedtype Value var value: Value { get } func isEqual(to other: Self) -> Bool } extension AnyEquatableBase { func isEqual(to other: Self) -> Bool { false } } extension AnyEquatableBase where Value: Equatable { func isEqual(to other: Self) -> Bool { value == other.value } } struct AnyEquatable<T>: AnyEquatableBase { var value: T } func check<T>(lhs: T, rhs: T) { print(AnyEquatable(value: lhs)) print(AnyEquatable(value: lhs).isEqual(to: AnyEquatable(value: rhs))) } func check2(lhs: String, rhs: String) { print(AnyEquatable(value: lhs)) print(AnyEquatable(value: lhs).isEqual(to: AnyEquatable(value: rhs))) } check(lhs: "test", rhs: "test") check2(lhs: "test", rhs: "test")
AnyEquatable<String>(value: "test") false AnyEquatable<String>(value: "test") true
func check3<T: Equatable>(...) {}
protocol AnyEquatableBase { associatedtype Value var value: Value { get } func isEqual(to other: Self) -> Bool } extension AnyEquatableBase { func isEqual(to other: Self) -> Bool { false } } extension AnyEquatableBase where Value: Equatable { func isEqual(to other: Self) -> Bool { value == other.value } } protocol MaybeEquatable { } extension MaybeEquatable { func isEqual(to other: Self) -> Bool { AnyEquatable(value: self).isEqual(to: AnyEquatable(value: other)) } } struct AnyEquatable<T>: AnyEquatableBase { var value: T } extension String: MaybeEquatable {} func check<T: MaybeEquatable>(lhs: T, rhs: T) { print(lhs.isEqual(to: rhs)) } func check2(lhs: String, rhs: String) { print(AnyEquatable(value: lhs), AnyEquatable(value: lhs).isEqual(to: AnyEquatable(value: rhs))) } check(lhs: "test", rhs: "test") check2(lhs: "test", rhs: "test")
false AnyEquatable<String>(value: "test") true
extension Cat: MaybeEquatable {}
しておかないといけない。T: MaybeEquatable
した上でCat: MaybeEquatable
みたいな。T
から実行時に T: P
で分岐する事は不可能なのかな? (edited)// witness_table* swift_conformsToProtocol(type*, protocol*);
as? T
でいいよね。 (edited)public protocol MaybeEquatable { func eraseToOpaqueEquatable() -> ErasedOpaqueEquatable } extension MaybeEquatable { public func isEqual(to other: Any) -> Bool { eraseToOpaqueEquatable().isEqualTo(other) } } extension MaybeEquatable { public func eraseToOpaqueEquatable() -> ErasedOpaqueEquatable { ErasedOpaqueEquatable() } } extension MaybeEquatable where Self: Equatable { public func eraseToOpaqueEquatable() -> ErasedOpaqueEquatable { ErasedOpaqueEquatable(value: self) } } public struct ErasedOpaqueEquatable { var isEqualTo: (Any) -> Bool init() { isEqualTo = { _ in false } } init<T: Equatable>(value: T) { isEqualTo = { value == $0 as? T } } } // end user interface public func anyIsEqual(_ a: Any, _ b: Any) -> Bool { guard let a = a as? MaybeEquatable else { return false } return a.isEqual(to: b) } // you need to mark your type extension String: MaybeEquatable {} print(anyIsEqual("str", "str")) // => true print(anyIsEqual({}, {})) // => false
(Any)->Bool
を返すのもありだなfunc partialApplySelfToIsEqual() -> (Any) -> Bool
let possibleErrorTypes: [APIResponseErrorProtocol.Type] = [LoginError.self, ValidationError.self, ...]
protocol APIResponseErrorProtocol: Decodable { static var typeName: String { get } }
do { } catch { }
してるとき、いつもそうだから。APIResponseErrorProtocol.Type
になるから、 existential openを使わないと init(from decoder: Decoder)
が呼べないという話import Foundation let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2) @_silgen_name("foo") func foo() {} let fooPtr = { dlsym(RTLD_DEFAULT, "foo")!.assumingMemoryBound(to: (() -> Void).self) }() fooPtr.pointee
@convention(c)
使える。 import Foundation public func isEqual(_ lhs: Any, _ rhs: Any) -> Bool { let lhsType = type(of: lhs) let rhsType = type(of: rhs) guard lhsType == rhsType else { return false } guard let witnessTable = swift_conformsToProtocol(lhsType, EquatableProtocolDescriptor) else { return false } let theType = unsafeBitCast(lhsType, to: UnsafeRawPointer.self) return withUnsafePointer(to: lhs) { lhsPtr in withUnsafePointer(to: rhs) { rhsPtr in AnyEquatable_internalIsEqual(lhsPtr, rhsPtr, theType, witnessTable) } } } @_silgen_name("swift_conformsToProtocol") func swift_conformsToProtocol(_: Any.Type, _: UnsafeRawPointer) -> UnsafeRawPointer? func load<T>(symbol: String) -> T { if let sym = dlsym(dlopen(nil, RTLD_LAZY), symbol) { return unsafeBitCast(sym, to: T.self) } let errorString = String(validatingUTF8: dlerror()) fatalError("Finding symbol \(symbol) failed: \(errorString ?? "unknown error")") } let AnyEquatable_internalIsEqual: @convention(c) (UnsafeRawPointer, UnsafeRawPointer, UnsafeRawPointer, UnsafeRawPointer) -> Bool = load(symbol: "AnyEquatable_internalIsEqual") let EquatableProtocolDescriptor: UnsafeRawPointer = load(symbol: "$sSQMp") @_silgen_name("AnyEquatable_internalIsEqual") func _internalIsEqual<T: Equatable>(_ lhs: T, rhs: T) -> Bool { return lhs == rhs }
(edited)AnyEquatable_internalIsEqual
を見つけられないな。Swift version 5.2-dev (Swift 74df1132af) Target: x86_64-unknown-linux-gnu
struct SimpleCallable { func callAsFunction(_ x: Float) -> Float { return x } } let foo = SimpleCallable() print(foo(1)) print(foo(foo(1)))
func f(g: @escaping () -> Void) { } class C { var name = "tama" func main() { f { [self] in print(name) } } }
func f(g: @escaping () -> Void) { } class C { var name = "tama" func main() { f { [self] in print(name) } } }
<stdin>:7:13: error: reference to property 'name' in closure requires explicit 'self.' to make capture semantics explicit print(name) ^ self. <stdin>:6:10: warning: capture 'self' was never used f { [self] in ^
#if os(Linux) print("Running on Linux") #else print("Running on macOS") #endif
#if os(Linux) print("Running on Linux") #else print("Running on macOS") #endif
swift-5.1.3-RELEASE
Running on Linux
#if os(Linux) print("Running on Linux") #else print("Running on macOS") #endif
#if os(Linux) print("Running on Linux") #else print("Running on macOS") #endif
Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15) Target: x86_64-apple-darwin19.2.0
Running on macOS
class C {} let a = C.self as AnyObject
class C {} let a = C.self as AnyObject
Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15) Target: x86_64-apple-darwin19.2.0
class C {} func f(_ a: AnyObject) {} f(C.self)
(edited)class C {} func f(_ a: AnyObject) {} f(C.self)
swift-5.1.3-RELEASE
/usercode/main.swift:3:3: error: argument type 'C.Type' does not conform to expected type 'AnyObject' f(C.self) ^
class C {} func f(_ a: AnyObject) {} f(C.self)
class C {} func f(_ a: AnyObject) {} f(C.self)
Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15) Target: x86_64-apple-darwin19.2.0
struct Example { var value: some Equatable { 1 } } struct Foo { typealias Body = @_opaqueReturnTypeOf("$s4main7ExampleV5valueQrvp", 0) 🦸 } print(Foo.Body.self)
struct Example { var value: some Equatable { 1 } } struct Foo { typealias Body = @_opaqueReturnTypeOf("$s4main7ExampleV5valueQrvp", 0) 🦸 } print(Foo.Body.self)
swift-5.1.3-RELEASE
Int
@propertyWrapper struct Generics<T> { var wrappedValue: T { 100 as! T } init(_ type: T.Type = T.self) {} } struct Example { @Generics(Int.self) var value } print(Example().value)
@propertyWrapper struct Generics<T> { var wrappedValue: T { 100 as! T } init(_ type: T.Type = T.self) {} } struct Example { @Generics(Int.self) var value } print(Example().value)
swift-5.1.3-RELEASE
100
@propertyWrapper struct NoGenerics { var wrappedValue: Int { 100 } } struct Example { @NoGenerics var value } print(Example().value)
@propertyWrapper struct NoGenerics { var wrappedValue: Int { 100 } } struct Example { @NoGenerics var value } print(Example().value)
swift-5.1.3-RELEASE
/usercode/main.swift:7:21: error: type annotation missing in pattern @NoGenerics var value ^
@propertyWrapper struct NoGenerics { var wrappedValue: Int { 100 } } struct Example { @NoGenerics() var value } print(Example().value)
@propertyWrapper struct NoGenerics { var wrappedValue: Int { 100 } } struct Example { @NoGenerics() var value } print(Example().value)
swift-5.1.3-RELEASE
100
class Cat { private let _bow: String = "にゃー" var bow: String { get { _bow } _modify { yield &_bow } } } var tama = Cat() tama.a = "わん" print(tama.a)
<stdin>:8:20: error: cannot assign to property: '_bow' is a 'let' constant yield &_bow ^~~~ <stdin>:2:13: note: change 'let' to 'var' to make it mutable private let _bow: String = "にゃー" <stdin>:13:6: error: value of type 'Cat' has no member 'a' tama.a = "わん" <stdin>:14:12: error: value of type 'Cat' has no member 'a' print(tama.a) ~~~~ ^
class Cat { let _bow: String = "にゃー" var bow: String { get { _bow } _modify { yield &_bow } } } var tama = Cat() tama.bow = "わん" print(tama.bow)
<stdin>:8:20: error: cannot assign to property: '_bow' is a 'let' constant yield &_bow ^~~~ <stdin>:2:5: note: change 'let' to 'var' to make it mutable let _bow: String = "にゃー"
Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15) Target: x86_64-apple-darwin18.6.0
だと class Neko { private let _bow: String = "にゃん" var bow: String { get { _bow } _modify { yield &bow } } } let cat = Neko() cat.bow = "わん" print(cat.bow)
は通るっぽい、多分もう修正されてるってことかな<stdin>:5:30: error: type 'C2' constrained to non-protocol, non-class type 'Self.X' associatedtype X where C2: X ^
Swift version 5.1.4 (swift-5.1.4-RELEASE) Target: x86_64-unknown-linux-gnu
class Foo { private var fooPrivate = "private property" } extension Foo { func bar() -> String { return fooPrivate } } print(Foo().bar())
class Foo { private var fooPrivate = "private property" } extension Foo { func bar() -> String { return fooPrivate } } print(Foo().bar())
swift-3.0.1-RELEASE
/usercode/main.swift:7:16: error: 'fooPrivate' is inaccessible due to 'private' protection level return fooPrivate ^ /usercode/main.swift:2:17: note: 'fooPrivate' declared here private var fooPrivate = "private property" ^
@dynamicMemberLookup public protocol Entity { associatedtype Identifier associatedtype Props var id: Identifier { get } var props: Props { get set } } extension Entity { public typealias SegFaultHere<T> = T @inlinable public subscript <Value>(dynamicMember keyPath: WritableKeyPath<Props, Value>) -> Value { get { props[keyPath: keyPath] } set { props[keyPath: keyPath] = newValue } } }
protocol CallAsFunction { func callAsFunction() } struct Foo: CallAsFunction { func callAsFunction() { print("foo") } } func call<C: CallAsFunction>(_ caller: C) { caller() } call(Foo())
struct Value: Hashable { let id = 5 } struct Value2: Hashable { let id = 5 func hash(into hasher: inout Hasher) { hasher.combine(id) } } enum EnumValue: Hashable { case a(Int) case b(Int) } enum EnumValue2: Hashable { case a(Int) case b(Int) func hash(into hasher: inout Hasher) { switch self { case .a(let v): hasher.combine(v) case .b(let v): hasher.combine(v) } } } print(5.hashValue) print(Value().hashValue) print(Value2().hashValue) print(EnumValue.a(5).hashValue) print(EnumValue.b(5).hashValue) print(EnumValue2.a(5).hashValue) print(EnumValue2.b(5).hashValue)
struct Value: Hashable { let id = 5 } struct Value2: Hashable { let id = 5 func hash(into hasher: inout Hasher) { hasher.combine(id) } } enum EnumValue: Hashable { case a(Int) case b(Int) } enum EnumValue2: Hashable { case a(Int) case b(Int) func hash(into hasher: inout Hasher) { switch self { case .a(let v): hasher.combine(v) case .b(let v): hasher.combine(v) } } } print(5.hashValue) print(Value().hashValue) print(Value2().hashValue) print(EnumValue.a(5).hashValue) print(EnumValue.b(5).hashValue) print(EnumValue2.a(5).hashValue) print(EnumValue2.b(5).hashValue)
swift-5.1.3-RELEASE
-5563881854129666050 -5563881854129666050 -5563881854129666050 1174769019477244301 8537611810857838151 -5563881854129666050 -5563881854129666050
enum EnumValue: Hashable { case a(Int) case b(Int) } enum EnumValue2: Hashable { case a(Int) case b(Int) func hash(into hasher: inout Hasher) { switch self { case .a(let v): hasher.combine(0) hasher.combine(v) case .b(let v): hasher.combine(1) hasher.combine(v) } } } print(5.hashValue) print(EnumValue.a(5).hashValue) print(EnumValue.b(5).hashValue) print(EnumValue2.a(5).hashValue) print(EnumValue2.b(5).hashValue)
(edited)enum EnumValue: Hashable { case a(Int) case b(Int) } enum EnumValue2: Hashable { case a(Int) case b(Int) func hash(into hasher: inout Hasher) { switch self { case .a(let v): hasher.combine(0) hasher.combine(v) case .b(let v): hasher.combine(1) hasher.combine(v) } } } print(5.hashValue) print(EnumValue.a(5).hashValue) print(EnumValue.b(5).hashValue) print(EnumValue2.a(5).hashValue) print(EnumValue2.b(5).hashValue)
swift-5.1.3-RELEASE
3666440306759404138 7344323318427966468 4893249820943752864 7344323318427966468 4893249820943752864
import StandardLibraryPreview var numbers = [10, 12, -5, 14, -3, -9, 15] let negatives = numbers.subranges(where: { $0 < 0 }) print(negatives) numbers.moveSubranges(negatives, to: 0) print(numbers)
https://swift.org/blog/preview-package/RangeSet(2..<3, 4..<6) [-5, -3, -9, 10, 12, 14, 15]
RangeSet(2..<3, 4..<6) [-5, -3, -9, 10, 12, 14, 15]
RangeSet(2..<3, 4..<6) [-5, -3, -9, 10, 12, 14, 15]
import ArgumentParser struct Repeat: ParsableCommand { @Flag(help: "Include a counter with each repetition.") var includeCounter: Bool @Option(name: .shortAndLong, help: "The number of times to repeat 'phrase'.") var count: Int? @Argument(help: "The phrase to repeat.") var phrase: String } extension Repeat { func run() throws { let repeatCount = count ?? .max for i in 1...repeatCount { if includeCounter { print("\(i): \(phrase)") } else { print(phrase) } } } } Repeat.main()
(edited)USAGE: repeat [--include-counter] [--count <count>] <phrase> ARGUMENTS: <phrase> The phrase to repeat. OPTIONS: --include-counter Include a counter with each repetition. -c, --count <count> The number of times to repeat 'phrase'. -h, --help Show help information.
(edited)USAGE: repeat [--include-counter] [--count <count>] <phrase> ARGUMENTS: <phrase> The phrase to repeat. OPTIONS: --include-counter Include a counter with each repetition. -c, --count <count> The number of times to repeat 'phrase'. -h, --help Show help information.
(edited)error: multiple targets named 'TestHelpers' in: swift-argument-parser, swift-se0270-range-set
(edited)func f1(apple: Int..., banana: Int) {} f1(apple: 1, 2, banano: 2)
swift: /home/buildnode/jenkins/workspace/oss-swift-package-linux-ubuntu-16_04/swift/lib/Sema/CSSimplify.cpp:704: bool swift::constraints::matchCallArguments(SmallVectorImpl<AnyFunctionType::Param> &, ArrayRef<AnyFunctionType::Param>, const swift::ParameterListInfo &, bool, bool, swift::constraints::MatchCallArgumentListener &, SmallVectorImpl<ParamBinding> &): Assertion `args[fromArgIdx].getLabel().empty()' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOLinux.build/module.modulemap -module-name main -lLibraries 1. Swift version 5.2-dev (LLV
func f(aa: Int, bb: Int, cc: Int = 0) {} f(bbx: 0)
(edited)<stdin>:3:2: error: incorrect argument labels in call (have 'bbx:', expected 'aa:bb:cc:') f(bbx: 0) ^~~~ aa <stdin>:3:3: error: missing argument for parameter 'aa' in call f(bbx: 0) ^ aa: <#Int#>, <stdin>:1:6: note: 'f(aa:bb:cc:)' declared here func f(aa: Int, bb: Int, cc: Int = 0) {} ^
(edited)func f() {}
func f(){} f()
---Constraint solving at [<stdin>:2:1 - line:2:3]--- (overload set choice binding $T0 := () -> ()) ---Initial constraints for the given expression--- (call_expr type='()' location=<stdin>:2:1 range=[<stdin>:2:1 - line:2:3] arg_labels= (declref_expr type='() -> ()' location=<stdin>:2:1 range=[<stdin>:2:1 - line:2:1] decl=main.(file).f()@<stdin>:1:6 function_ref=single) (tuple_expr type='()' location=<stdin>:2:2 range=[<stdin>:2:2 - line:2:3])) Score: 0 0 0 0 0 0 0 0 0 0 0 0 Contextual Type: <null> Type Variables: $T0 [lvalue allowed] [noescape allowed] as () -> () @ locator@0x8d2bf90 [DeclRef@<stdin>:2:1] $T1 [noescape allowed] as () @ locator@0x8d2bff8 [Call@<stdin>:2:1 -> function result] Active Constraints: Inactive Constraints: Resolved overloads: selected overload set choice f: $T0 == () -> () (found solution 0 0 0 0 0 0 0 0 0 0 0 0) ---Solver statistics--- Total number of scopes explored: 1 Maximum depth reached while exploring solutions: 1 Time: 4.000000e+00ms ---Solution--- Fixed score: 0 0 0 0 0 0 0 0 0 0 0 0 Type variables: $T1 as () @ locator@0x8d2bff8 [Call@<stdin>:2:1 -> function result] $T0 as () -> () @ locator@0x8d2bf90 [DeclRef@<stdin>:2:1] Overload choices: locator@0x8d2bf90 [DeclRef@<stdin>:2:1] with main.(file).f()@<stdin>:1:6 as f: () -> () Constraint restrictions: Disjunction choices: ---Type-checked expression--- (call_expr type='()' location=<stdin>:2:1 range=[<stdin>:2:1 - line:2:3] arg_labels= (declref_expr type='() -> ()' location=<stdin>:2:1 range=[<stdin>:2:1 - line:2:1] decl=main.(file).f()@<stdin>:1:6 function_ref=single) (tuple_expr type='()' location=<stdin>:2:2 range=[<stdin>:2:2 - line:2:3]))
func f(aa: Int..., bb: Int, cc: Int) {} f(aa: 1, 2, 3, bbx: 4, cc: 5)
(edited)<stdin>:2:2: error: incorrect argument label in call (have 'aa:_:_:bbx:cc:', expected 'aa:_:_:bb:cc:') f(aa: 1, 2, 3, bbx: 4, cc: 5) ^ ~~~ bb
(edited)func f(aa: Int, bb: Int) {} f(aa: 1, aa: 2)
(edited)---Constraint solving at [<stdin>:2:1 - line:2:15]--- (overload set choice binding $T0 := (Int, Int) -> ()) (attempting fix [fix: re-label argument(s)] @ locator@0x95ce7c0 [Call@<stdin>:2:1 -> apply argument]) (increasing score due to attempting to fix the source) ---Initial constraints for the given expression--- (call_expr type='()' location=<stdin>:2:1 range=[<stdin>:2:1 - line:2:15] arg_labels=aa:aa: (declref_expr type='(Int, Int) -> ()' location=<stdin>:2:1 range=[<stdin>:2:1 - line:2:1] decl=main.(file).f(aa:bb:)@<stdin>:1:6 function_ref=single) (tuple_expr type='(aa: $T1, aa: $T2)' location=<stdin>:2:2 range=[<stdin>:2:2 - line:2:15] names=aa,aa (integer_literal_expr type='$T1' location=<stdin>:2:7 range=[<stdin>:2:7 - line:2:7] value=1 builtin_initializer=**NULL** initializer=**NULL**) (integer_literal_expr type='$T2' location=<stdin>:2:14 range=[<stdin>:2:14 - line:2:14] value=2 builtin_initializer=**NULL** initializer=**NULL**))) Score: 2 0 0 0 0 0 0 0 0 0 0 0 Contextual Type: <null> Type Variables: $T0 [lvalue allowed] [noescape allowed] as (Int, Int) -> () @ locator@0x95ce4e0 [DeclRef@<stdin>:2:1] $T1 [noescape allowed] literal=3 bindings={(subtypes of) (default from ExpressibleByIntegerLiteral) Int} @ locator@0x95ce530 [IntegerLiteral@<stdin>:2:7] $T2 [noescape allowed] literal=3 bindings={(subtypes of) (default from ExpressibleByIntegerLiteral) Int} @ locator@0x95ce5e8 [IntegerLiteral@<stdin>:2:14] $T3 [noescape allowed] as () @ locator@0x95ce6f8 [Call@<stdin>:2:1 -> function result] Active Constraints: Inactive Constraints: $T1 literal conforms to ExpressibleByIntegerLiteral [[locator@0x95ce530 [IntegerLiteral@<stdin>:2:7]]]; $T2 literal conforms to ExpressibleByIntegerLiteral [[locator@0x95ce5e8 [IntegerLiteral@<stdin>:2:14]]]; $T1 arg conv Int [[locator@0x95ce818 [Call@<stdin>:2:1 -> apply argument -> comparing call argument #0 to parameter #0]]]; $T2 arg conv Int [[locator@0x95ce8a8
(edited)protocol P { associatedtype T } func f(p: P) {}
<stdin>:2:11: error: protocol 'P' can only be used as a generic constraint because it has Self or associated type requirements func f(p: P) {} ^
/userdocs/diagnostics
を指定すると使える新機能があるので参照したかった。/share
とかにデプロイされるようになるといいな。swift_install_in_component(DIRECTORY diagnostics DESTINATION "share/doc/swift" COMPONENT compiler)
extension (Int, Int) {}
(edited)<stdin>:1:1: error: non-nominal type '(Int, Int)' cannot be extended extension (Int, Int) {} ^ ~~~~~~~~~~ Nominal types -------------- In Swift, a type is considered a nominal type if it is named. In other words, it has been defined by declaring the type somewhere in code. Examples of nominal types include classes, structs and enums, all of which must be declared before using them. Nominal types are an important concept in Swift because they can be extended, explicitly initialized using the 'MyType()' syntax, and may conform to protocols. In contrast, non-nominal types have none of these capabilities. A non-nominal type is any type which is not nominal. They are sometimes called “structural types” because they are usually obtained by composing other types. Examples include function types like '(Int) -> (String)', tuple types like '(Int, String)', metatypes like 'Int.Type', and special types like 'Any' and 'AnyObject'. Whether the name of a protocol refers to a nominal or non-nominal type depends on where it appears in code. When used in a declaration or extension like 'extension MyProtocol { … }', 'MyProtocol' refers to a protocol type, which is nominal. This means that it may be extended and conform to protocols. However, when written as the type of a constant or variable, 'MyProtocol' instead refers to a non-nominal, existential type. As a result, code like 'let value: MyProtocol = MyProtocol()' is not allowed because 'MyProtocol' refers to a non-nominal type in this context and cannot be explicitly initialized.
(edited)$ docker-swiftnightly-run ls -la /usr/share/doc/swift/diagnostics total 28 drwxr-xr-x 2 root root 4096 Mar 14 05:33 . drwxr-xr-x 3 root root 4096 Mar 14 05:33 .. -rw-r--r-- 1 root root 1898 Mar 14 04:05 associated-type-requirements.md -rw-r--r-- 1 root root 1162 Mar 14 04:05 complex-closure-inference.md -rw-r--r-- 1 root root 1501 Mar 14 04:05 dynamic-callable-requirements.md -rw-r--r-- 1 root root 1431 Mar 14 04:05 nominal-types.md -rw-r--r-- 1 root root 727 Mar 14 04:05 property-wrapper-requirements.md $ docker-swift52-run ls -la /usr/share/doc/swift/diagnostics total 16 drwxr-xr-x 2 root root 4096 Mar 15 09:30 . drwxr-xr-x 3 root root 4096 Mar 15 09:30 .. -rw-r--r-- 1 root root 1162 Mar 15 07:57 complex-closure-inference.md -rw-r--r-- 1 root root 1440 Mar 15 07:57 nominal-types.md
extension (Int, Int) {}
<stdin>:1:1 1 | extension (Int, Int) {} | ~~~~~~~~~~ | ^ error: non-nominal type '(Int, Int)' cannot be extended 2 |
$ la (dirname (xcrun --toolchain org.swift.52202003141a -find swift))/../share/doc/swift/diagnostics total 16 drwxr-xr-x 4 norio staff 128B 3 15 11:16 ./ drwxr-xr-x 3 norio staff 96B 3 15 11:16 ../ -rw-r--r-- 1 norio staff 1.1K 3 15 07:56 complex-closure-inference.md -rw-r--r-- 1 norio staff 1.4K 3 15 07:56 nominal-types.md
[omochi@omochi-iMacPro diagnostics]$ pwd /Applications/Xcode11.4.beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/share/doc/swift/diagnostics [omochi@omochi-iMacPro diagnostics]$ ls complex-closure-inference.md nominal-types.md
protocol P { associatedtype T } func f(p: P) {}
<stdin>:2:11: error: protocol 'P' can only be used as a generic constraint because it has Self or associated type requirements func f(p: P) {} ^ Using Protocols with 'Self' or Associated Type Requirements Protocols in Swift may be used as types, as part of a generic constraint, or as part of an opaque result type. // CustomStringConvertible can be used as a type. func foo(bar: CustomStringConvertible) { /* ... */ } // ...or as a generic constraint on 'T'. func bar<T: CustomStringConvertible>(baz: T) { /* ... */ } // ...or as part of an opaque result type. func baz() -> some CustomStringConvertible { /* ... */ } While all Swift protocols can be used as generic constraints and as part of opaque result types, not all protocols can be used as types in general. Specifically, if a protocol has a requirement which references 'Self' or an associated type, it cannot be used as a type. One such protocol is 'Identifiable', which has the requirement 'var id: ID { get }', where 'ID' is an associated type. As a result, the following code is not allowed: func foo(bar: Identifiable) { /* ... */ } // error: protocol 'Identifiable' can only be used as a generic constraint because it has Self or associated type requirements Protocols like 'Identifiable' which have 'Self' or associated type requirements cannot be used as types because such types would rarely be useful in practice. They would be unable to allow use of 'Self' or associated type requirements like 'var id: ID { get }' because the associated type is not specified. When working with protocols having 'Self' or associated type requirements constrained generics, opaque result types, or manual type erasure is sufficient to support most use cases. To learn more, see the [Protocols](https://docs.swift.org/swift-book/LanguageGuide/Protocols.html), [Generics](https://docs.swift.org/swift-book/LanguageGuide/Generics.html), and [Opaque Types](https://docs.swif
OTHER_SWIFT_FLAGS
に-Xfrontend -enable-educational-notes -Xfrontend -diagnostic-documentation-path -Xfrontend $TOOLCHAIN_DIR/usr/share/doc/swift/diagnostics
って設定してエラーを出させてみたけど、Xcodeのエラーログではmarkdown syntax認識されなかった。ANIMATED_ICON
guild has access to set an animated guild icon
だったかな。Swift version 5.3-dev (LLVM fa328efd5a, Swift 667bec0f21) Target: x86_64-unknown-linux-gnu
Swift version 5.0.3 (swift-5.0.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.2.4 (swift-4.2.4-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.1.5 (swift-5.1.5-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.1.3 (swift-4.1.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.0.3 (swift-4.0.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.2-dev (Swift 33150e32b4) Target: x86_64-unknown-linux-gnu
class Foo: Foo.Base { class Base {} }
<stdin>:1:7: error: circular reference class Foo: Foo.Base { ^ <stdin>:1:16: note: through reference here class Foo: Foo.Base { ^
class Foo: Foo.Base { class Base {} }
struct S { let a: Int = 1 } S(a: 2)
<stdin>:2:6: error: argument passed to call that takes no arguments S(a: 2) ^
class Foo { private let deinitBody: () -> Void init(_ deinitBody: @escaping () -> Void) { self.deinitBody = deinitBody } deinit { deinitBody() } } func main() { var a = 42 var foo = Foo {} foo = Foo { a = -1 } let _ = foo // to ignore warnings print(a) } main()
(edited)Swift version 5.3-dev (LLVM 38f04f051e, Swift 587da7ce60) Target: x86_64-unknown-linux-gnu
class Record { var storage: [String: Any] init(_ storage: [String: Any]) { self.storage = storage } } extension Record { @propertyWrapper public struct Field<Value> { @available(*, unavailable) public var wrappedValue: Value { fatalError("only works on instance properties of classes") } private let key: String public init(key: String) { self.key = key } public static subscript<Instance: Record>( _enclosingInstance instance: Instance, wrapped wrappedKeyPath: KeyPath<Instance, Value>, storage storageKeyPath: ReferenceWritableKeyPath<Instance, Self> ) -> Value { let field = instance[keyPath: storageKeyPath] return instance.storage[field.key] as! Value } } } class User: Record { @Field(key: "id") var id: Int } let user = User(["id": 100]) print(user.id)
(edited)class Record { var storage: [String: Any] init(_ storage: [String: Any]) { self.storage = storage } } extension Record { @propertyWrapper public struct Field<Value> { @available(*, unavailable) public var wrappedValue: Value { get { fatalError("only works on instance properties of classes") } set { fatalError("only works on instance properties of classes") } } private let key: String public init(key: String) { self.key = key } public static subscript<Instance: Record>( _enclosingInstance instance: Instance, wrapped wrappedKeyPath: ReferenceWritableKeyPath<Instance, Value>, storage storageKeyPath: ReferenceWritableKeyPath<Instance, Self> ) -> Value { get { let field = instance[keyPath: storageKeyPath] return instance.storage[field.key] as! Value } set {} } } } class User: Record { @Field(key: "id") var id: Int } let user = User(["id": 100]) print(user.id)
(edited)class Base { class var keyPath: AnyKeyPath { fatalError() } } final class Derived: Base { override class var keyPath: AnyKeyPath { \Self.value } var value: Int = 0 } print(Derived.keyPath)
Fatal error: could not demangle keypath type from '�: file /home/buildnode/jenkins/workspace/oss-swift-5.3-package-linux-ubuntu-16_04/swift/stdlib/public/core/KeyPath.swift, line 2623 Current stack trace: 0 libswiftCore.so 0x00007fa81bf3dc30 swift_reportError + 50 1 libswiftCore.so 0x00007fa81bfb01a0 _swift_stdlib_reportFatalErrorInFile + 115 2 libswiftCore.so 0x00007fa81bc7b465 <unavailable> + 1410149 3 libswiftCore.so 0x00007fa81bc7b0a7 <unavailable> + 1409191 4 libswiftCore.so 0x00007fa81bc7b642 <unavailable> + 1410626 5 libswiftCore.so 0x00007fa81bc79a70 _assertionFailure(_:_:file:line:flags:) + 523 6 libswiftCore.so 0x00007fa81bd55451 <unavailable> + 2303057 7 libswiftCore.so 0x00007fa81bd556ae <unavailable> + 2303662 8 libswiftCore.so 0x00007fa81bd54c97 <unavailable> + 2301079 9 libswiftCore.so 0x00007fa81bd54990 _swift_getKeyPath(pattern:arguments:) + 120 12 swift 0x0000000000599cdc <unavailable> + 1678556 13 swift 0x000000000058723f <unavailable> + 1602111 14 swift 0x000000000056c471 <unavailable> + 1492081 15 swift 0x000000000055fa38 <unavailable> + 1440312 16 swift 0x000000000055c87e <unavailable> + 1427582 17 swift 0x00000000004d653b <unavailable> + 877883 18 libc.so.6 0x00007fa81e044740 __libc_start_main + 240 19 swift 0x00000000004d5fe9 <unavailable> + 876521 Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftB
func foo(_ closure: () -> Void, defaultArg: Int = 0) { closure() } foo { print("foo") }
<stdin>:5:4: error: missing argument for parameter #1 in call foo { print("foo") } ^ (<#() -> Void#>) <stdin>:1:6: note: 'foo(_:defaultArg:)' declared here func foo(_ closure: () -> Void, defaultArg: Int = 0) { ^
protocol Dekiru { static var hoge: Dekiruzo { get } } enum Dekiruzo: Dekiru { case hoge }
(edited)protocol P { associatedtype T static var hoge: Types<T> { get } } enum Types<T>: P { case hoge }
protocol P { static var hoge: Types<Int> { get } } enum Types<T>: P { case hoge }
<stdin>:5:6: error: type 'Types<T>' does not conform to protocol 'P' enum Types<T>: P { ^ <stdin>:6:10: note: candidate has non-matching type '<T> (Types<T>.Type) -> Types<T>' case hoge ^ <stdin>:2:16: note: protocol requires property 'hoge' with type 'Types<Int>'; do you want to add a stub? static var hoge: Types<Int> { get } ^
protocol P { static var hoge: Types<Int> { get } } enum Types<T> { case hoge } extension Types: P where T == Int {} func use<T>(_ type: Types<T>) { print("1", type) } use(.hoge)
(edited)<stdin>:15:1: error: generic parameter 'T' could not be inferred use(.hoge) ^ <stdin>:11:6: note: in call to function 'use' func use<T>(_ type: Types<T>) { ^
(edited)protocol EntityProtocol { associatedtype ID init(id: ID) } class Entity<ID>: EntityProtocol { let id: ID required init(id: ID) { self.id = id } enum CodingKeys: CodingKey { case id(String) var stringValue: String { switch self { case .id(let id): return id } } var intValue: Int? { nil } init?(stringValue: String) { self = .id(stringValue) } init?(intValue: Int) { return nil } } class func codingKeysForID() -> CodingKeys { .id("id") } } extension EntityProtocol where Self: Decodable, ID: Decodable { init(from decoder: Decoder) throws { let type = Self.self as! Entity<ID>.Type let c = try decoder.container(keyedBy: type.CodingKeys.self) self.init(id: try c.decode(ID.self, forKey: type.codingKeysForID())) } }
(edited)struct MySet<Element: Hashable> { private var set: Set<Element> } extension MySet: Collection { subscript(idx: Set<Element>.Index) -> Element { set[idx] } var startIndex: Set<Element>.Index { set.startIndex } var endIndex: Set<Element>.Index { set.endIndex } func index(after i: Set<Element>.Index) -> Set<Element>.Index { set.index(after: i) } }
(edited)<stdin>:6:56: error: expected '{' to start setter definition subscript(idx: Set<Element>.Index) -> Element { set[idx] } ^ <stdin>:7:45: error: expected '{' to start setter definition var startIndex: Set<Element>.Index { set.startIndex } ^ <stdin>:8:43: error: expected '{' to start setter definition var endIndex: Set<Element>.Index { set.endIndex } ^
(edited)struct MySet<Element: Hashable> { private var _set: Set<Element> } extension MySet: Collection { subscript(idx: Set<Element>.Index) -> Element { _set[idx] } var startIndex: Set<Element>.Index { _set.startIndex } var endIndex: Set<Element>.Index { _set.endIndex } func index(after i: Set<Element>.Index) -> Set<Element>.Index { _set.index(after: i) } }
import Foundation protocol Foo: NSObjectProtocol { func a() } class Bar: NSObject, Foo { func a() { } } print(class_getInstanceMethod(Bar.self, Selector("a")))
<stdin>:13:7: error: use of unresolved identifier 'class_getInstanceMethod' print(class_getInstanceMethod(Bar.self, Selector("a"))) ^~~~~~~~~~~~~~~~~~~~~~~ <stdin>:13:41: error: use of unresolved identifier 'Selector' print(class_getInstanceMethod(Bar.self, Selector("a"))) ^~~~~~~~
class A { class var i: String { "i" } init() {} func setup() { a = { if let a = self.a { return a() } return Self.i } } var a: (() -> String)? } class Test { weak var a: A? init(a: A) { self.a = a a.setup() } func main() { print(a?.a?()) } } Test(a: A()).main()
<stdin>:21:15: warning: expression implicitly coerced from 'String?' to 'Any' print(a?.a?()) ^~~~~~~ <stdin>:21:19: note: provide a default value to avoid this warning print(a?.a?()) ~~~~^~~ ?? <#default value#> <stdin>:21:19: note: force-unwrap the value to avoid this warning print(a?.a?()) ~~~~^~~ ! <stdin>:21:19: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(a?.a?()) ~~~~^~~ as Any Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-m
class A { class var i: String { "i" } init() {} func setup() { a = { if let a = self.a { return a() } return Self.i } } var a: (() -> String)? } class Test { weak var a: A? init(a: A) { self.a = a a.setup() } func main() { print(a?.a?()) } } Test(a: A()).main()
<stdin>:21:15: warning: expression implicitly coerced from 'String?' to 'Any' print(a?.a?()) ^~~~~~~ <stdin>:21:19: note: provide a default value to avoid this warning print(a?.a?()) ~~~~^~~ ?? <#default value#> <stdin>:21:19: note: force-unwrap the value to avoid this warning print(a?.a?()) ~~~~^~~ ! <stdin>:21:19: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(a?.a?()) ~~~~^~~ as Any Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-m
struct NotEquatable {} func test() { struct A: Equatable { var value: NotEquatable static func == (lhs: A, rhs: A) -> Bool { true } } }
<stdin>:4:12: error: type 'A' does not conform to protocol 'Equatable' struct A: Equatable { ^ <stdin>:5:13: note: stored property type 'NotEquatable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'A' to 'Equatable' var value: NotEquatable ^ Swift.==:1:24: note: candidate would match if 'A' conformed to 'RawRepresentable' @inlinable public func == <T>(lhs: T, rhs: T) -> Bool where T : RawRepresentable, T.RawValue : Equatable ^ Swift.FloatingPoint:2:24: note: candidate would match if 'A' conformed to 'FloatingPoint' public static func == (lhs: Self, rhs: Self) -> Bool ^ Swift.BinaryInteger:2:24: note: candidate would match if 'A' conformed to 'BinaryInteger' public static func == <Other>(lhs: Self, rhs: Other) -> Bool where Other : BinaryInteger ^ Swift._Pointer:2:24: note: candidate would match if 'A' conformed to '_Pointer' public static func == (lhs: Self, rhs: Self) -> Bool ^ Swift.Strideable:3:35: note: candidate would match if 'A' conformed to 'Strideable' @inlinable public static func == (x: Self, y: Self) -> Bool ^ Swift.StringProtocol:2:35: note: candidate would match if 'A' conformed to 'StringProtocol' @inlinable public static func == <RHS>(lhs: Self, rhs: RHS) -> Bool where RHS : StringProtocol ^ Swift.SIMD:4:24: note: candidate would match if 'A' conformed to 'SIMD' public static func == (lhs: Self, rhs: Self) -> Bool ^ Swift.Equatable:2:17: note: protocol requires function '==' with type '(A, A) -> Bool' static func == (lhs: Self, rhs: Self) -> Bool ^
func contains(i: Int, lim: Int) -> Bool { (0..<lim).contains(i) } contains(1, 100)
<unknown>:0: error: option '-emit-ir' is not supported by 'swift'; did you mean to use 'swiftc'?
-frontend
の後に付けると動きます。 @swift-5.2.5 -frontend -emit-ir func contains(_ i: Int, _ lim: Int) -> Bool { (0..<lim).contains(i) } contains(1, 100)
; ModuleID = '-' source_filename = "-" target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-unknown-linux-gnu" module asm ".section .swift1_autolink_entries,\220x80000000\22" %TSnySiG = type <{ %TSi, %TSi }> %TSi = type <{ i64 }> @0 = private unnamed_addr constant [46 x i8] c"Can't form Range with upperBound < lowerBound\00" @1 = private unnamed_addr constant [112 x i8] c"/home/buildnode/jenkins/workspace/oss-swift-5.2-package-linux-ubuntu-16_04/swift/stdlib/public/core/Range.swift\00" @2 = private unnamed_addr constant [12 x i8] c"Fatal error\00" @__swift_reflection_version = linkonce_odr hidden constant i16 3 @_swift1_autolink_entries = private constant [49 x i8] c"-lswiftSwiftOnoneSupport\00-lswiftCore\00-lLibraries\00", section ".swift1_autolink_entries", align 8 @llvm.used = appending global [2 x i8*] [i8* bitcast (i16* @__swift_reflection_version to i8*), i8* getelementptr inbounds ([49 x i8], [49 x i8]* @_swift1_autolink_entries, i32 0, i32 0)], section "llvm.metadata", align 8 define protected i32 @main(i32, i8**) #0 { entry: %2 = bitcast i8** %1 to i8* %3 = call swiftcc i1 @"$s4main8containsySbSi_SitF"(i64 1, i64 100) ret i32 0 } define hidden swiftcc i1 @"$s4main8containsySbSi_SitF"(i64, i64) #0 { entry: %i.debug = alloca i64, align 8 %2 = bitcast i64* %i.debug to i8* call void @llvm.memset.p0i8.i64(i8* align 8 %2, i8 0, i64 8, i1 false) %lim.debug = alloca i64, align 8 %3 = bitcast i64* %lim.debug to i8* call void @llvm.memset.p0i8.i64(i8* align 8 %3, i8 0, i64 8, i1 false) %4 = alloca %TSnySiG, align 8 %5 = alloca %TSi, align 8 %6 = alloca %TSi, align 8 %7 = alloca %TSnySiG, align 8 %8 = alloca %TSi, align 8 store i64 %0, i64* %i.debug, align 8 store i64 %1, i64* %lim.debug, align 8 %9 = bitcast %TSnySiG* %4 to i8* call void @llvm.lifetime.start.p0i8(i64 16, i8* %9) br label %10 10: ; preds = %entry %11 = icmp slt i64 %1, 0
Swift version 5.2.4-dev (Swift b623e823d4) Target: x86_64-unknown-linux-gnu
swift-5.2.5-RELEASE
タグが付いたけど、やり直しになるパターンだ…swift -version
が5.2.4-devを返して来る。b623e823d4
ってコミットのハッシュではないのかな?#define
を参照してるだけだから、#define
の値をセットしてるのはそのCMakeList.txtですね。Swift version 5.2.5 (swift-5.2.5-RELEASE) Target: x86_64-unknown-linux-gnu
func asyncFunc() async { print(#function) } await asyncFunc()
asyncFunc()
protocol P {} struct S<T: P> {} func fun<T>(arg: S<T>) {}
import Foundation protocol P { var prev: P? { get set } } struct Foo: P, CustomStringConvertible { var prev: P? let uuid = UUID() var description: String { "Foo(prev: \(prev.map { String(describing: $0) } ?? "nil"), uuid: \(uuid.uuidString.prefix(4)))" } } func insert(_ p: P, into array: inout [P], _ prev: inout P?) { var p = p p.prev = prev prev = p print("new p =", p) array.append(p) } var p: P? var result: [P] = [] insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) for r in result { print("inserted =", r) } print("last 'p' =", p!)
(edited)new p = Foo(prev: nil, uuid: 5D6E) new p = Foo(prev: Foo(prev: nil, uuid: 5D6E), uuid: 0264) new p = Foo(prev: Foo(prev: Foo(prev: nil, uuid: 5D6E), uuid: 0264), uuid: B254) new p = Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 5D6E), uuid: 0264), uuid: B254), uuid: 5D51) new p = Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 5D6E), uuid: 0264), uuid: B254), uuid: 5D51), uuid: 0A52) new p = Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 5D6E), uuid: 0264), uuid: B254), uuid: 5D51), uuid: 0A52), uuid: 381A) inserted = Foo(prev: nil, uuid: 5D6E) inserted = Foo(prev: nil, uuid: 0264) inserted = Foo(prev: nil, uuid: B254) inserted = Foo(prev: nil, uuid: 5D51) inserted = Foo(prev: nil, uuid: 0A52) inserted = Foo(prev: nil, uuid: 381A) last 'p' = Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 5D6E), uuid: 0264), uuid: B254), uuid: 5D51), uuid: 0A52), uuid: 381A)
(edited)import Foundation protocol P { var prev: P? { get set } } struct Foo: P, CustomStringConvertible { var prev: P? let uuid = UUID() var description: String { "Foo(prev: \(prev.map { String(describing: $0) } ?? "nil"), uuid: \(uuid.uuidString.prefix(4)))" } } func insert(_ p: P, into array: inout [P], _ prev: inout P?) { var p = p p.prev = prev prev = p print("new p =", p) array.append(p) } var p: P? var result: [P] = [] insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) insert(Foo(), into: &result, &p) for r in result { print("inserted =", r) } print("last 'p' =", p!)
new p = Foo(prev: nil, uuid: 0628) new p = Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A) new p = Foo(prev: Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A), uuid: 85E7) new p = Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A), uuid: 85E7), uuid: 12A7) new p = Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A), uuid: 85E7), uuid: 12A7), uuid: 7C27) new p = Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A), uuid: 85E7), uuid: 12A7), uuid: 7C27), uuid: 6E9E) inserted = Foo(prev: nil, uuid: 0628) inserted = Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A) inserted = Foo(prev: Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A), uuid: 85E7) inserted = Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A), uuid: 85E7), uuid: 12A7) inserted = Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A), uuid: 85E7), uuid: 12A7), uuid: 7C27) inserted = Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A), uuid: 85E7), uuid: 12A7), uuid: 7C27), uuid: 6E9E) last 'p' = Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: Foo(prev: nil, uuid: 0628), uuid: A27A), uuid: 85E7), uuid: 12A7), uuid: 7C27), uuid: 6E9E)
import Foundation @propertyWrapper struct DefaultValue<Storage: DefaultValueStorage>: Decodable { var wrappedValue: Storage.Value = Storage.value } extension DefaultValue { init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() self.wrappedValue = try container.decode(Storage.Value.self) } } protocol DefaultValueStorage { associatedtype Value: Decodable static var value: Value { get } } enum DefaultValueStorages { enum Nil<T: Decodable>: DefaultValueStorage { static var value: T? { nil } } } // MARK: - 1. 直接書く struct S1 { @DefaultValue<DefaultValueStorages.Nil<String>> var string } // MARK: - 2. 別enumでtypealiasする enum Default { typealias Nil<T: Decodable> = DefaultValue<DefaultValueStorages.Nil<T>> } struct S2 { @Default.Nil<String> var string } // MARK: - 3. extension DefaultValueでtypealiasする extension DefaultValue { typealias Nil<T: Decodable> = DefaultValue<DefaultValueStorages.Nil<T>> } struct S3 { @DefaultValue.Nil<String> var string }
<stdin>:27:57: error: type annotation missing in pattern @DefaultValue<DefaultValueStorages.Nil<String>> var string ^ <stdin>:35:30: error: type annotation missing in pattern @Default.Nil<String> var string ^ swift: /home/buildnode/jenkins/workspace/oss-swift-5.2-package-linux-ubuntu-16_04/swift/lib/Sema/TypeCheckType.cpp:865: static swift::Type swift::TypeChecker::applyUnboundGenericArguments(swift::UnboundGenericType *, swift::GenericTypeDecl *, swift::SourceLoc, swift::TypeResolution, ArrayRef<swift::Type>): Assertion `!resultType->hasTypeParameter()' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libr
import Foundation @propertyWrapper struct DefaultValue<Storage: DefaultValueStorage>: Decodable { var wrappedValue: Storage.Value = Storage.value } extension DefaultValue { init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() self.wrappedValue = try container.decode(Storage.Value.self) } } protocol DefaultValueStorage { associatedtype Value: Decodable static var value: Value { get } } enum DefaultValueStorages { enum Nil<T: Decodable>: DefaultValueStorage { static var value: T? { nil } } } // MARK: - 1. 直接書く struct S1 { @DefaultValue<DefaultValueStorages.Nil<String>> var string } // MARK: - 2. 別enumでtypealiasする enum Default { typealias Nil<T: Decodable> = DefaultValue<DefaultValueStorages.Nil<T>> } struct S2 { @Default.Nil<String> var string } // MARK: - 3. extension DefaultValueでtypealiasする extension DefaultValue { typealias Nil<T: Decodable> = DefaultValue<DefaultValueStorages.Nil<T>> } struct S3 { @DefaultValue.Nil<String> var string }
(edited)swift: /home/buildnode/jenkins/workspace/oss-swift-5.3-package-linux-ubuntu-16_04/swift/lib/Sema/TypeCheckType.cpp:881: swift::Type swift::TypeChecker::applyUnboundGenericArguments(swift::UnboundGenericType *, swift::GenericTypeDecl *, swift::SourceLoc, swift::TypeResolution, ArrayRef<swift::Type>): Assertion `!resultType->hasTypeParameter()' failed. Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOLinux.build/module.modulemap -module-name main -lLibraries 1. Swift version 5.3-dev (LLVM b87e6c6a2b, Swift 6446e640ec) 2. While evaluating request TypeCh
(edited)Swift version 5.3 (swift-5.3-RELEASE) Target: x86_64-unknown-linux-gnu
struct Container<Value> { var value: Value init(value: Value) { self.value = value } func withValue(action: (Value) -> ()) { action(value) } } var container = Container<Any>(value: "foo") container.withValue { value in print(value) container.value = "bar" print(value) }
<stdin>:2:9: error: initializers may only be declared within a type init(value: Value) { ^ <stdin>:8:1: error: extraneous '}' at top level } ^ <stdin>:1:16: error: cannot find type 'Value' in scope var value: Value ^~~~~ <stdin>:5:29: error: cannot find type 'Value' in scope func withValue(action: (Value) -> ()) { ^~~~~ <stdin>:10:17: error: cannot find 'Container' in scope var container = Container<Any>(value: "foo") ^~~~~~~~~
class Container<Value> { var value: Value init(value: Value) { self.value = value } func withValue(action: (Value) -> ()) { action(value) } } let container = Container<Any>(value: "foo") container.withValue { value in print(value) container.value = "bar" print(value) }
(edited)<stdin>:2:9: error: initializers may only be declared within a type init(value: Value) { ^ <stdin>:8:1: error: extraneous '}' at top level } ^ <stdin>:1:16: error: cannot find type 'Value' in scope var value: Value ^~~~~ <stdin>:5:29: error: cannot find type 'Value' in scope func withValue(action: (Value) -> ()) { ^~~~~ <stdin>:10:17: error: cannot find 'Container' in scope let container = Container<Any>(value: "foo") ^~~~~~~~~
struct Container { var value: Any = "foo" func withValue(action: (Any) -> Void) { action(value) } } var container = Container() container.withValue { value in print(value) container.value = "bar" print(value) }
struct Container { var value: Any = "foo" func withValue(action: (Any) -> Void) { action(value) } } var container = Container() container.withValue { value in print(value) container.value = "bar" print(value) }
struct Container { var value: Any = "foo" func withValue(action: (Any) -> Void) { action(value) } } var container = Container() container.withValue { value in print(value) container.value = "bar" print(value) }
(edited)var global: Any = 1 func withValue(action: (Any) -> Void) { action(global) } withValue { value in print(value) global = 24 print(value) }
(edited)import Foundation func download(from url: URL) async throws -> Data { fatalError("Unimplemented yet.") } let url: URL! = nil @asyncHandler func onButtonPressed(_ sender: Any) { do { let data = try await download(from: url) print(data.count) } catch { print("\(error)") } }
<stdin>:3:29: error: consecutive statements on a line must be separated by ';' func download(from url: URL) async throws -> Data { ^ ; <stdin>:9:2: error: 'asyncHandler' attribute is only valid when experimental concurrency is enabled @asyncHandler ^ <stdin>:12:29: error: consecutive statements on a line must be separated by ';' let data = try await download(from: url) ^ ; <stdin>:3:6: error: expected '{' in body of function declaration func download(from url: URL) async throws -> Data { ^ <stdin>:3:30: error: cannot find 'async' in scope func download(from url: URL) async throws -> Data { ^~~~~ <stdin>:3:30: error: expected type before '->' func download(from url: URL) async throws -> Data { ^ <stdin>:3:46: error: expected type after '->' func download(from url: URL) async throws -> Data { ^ <stdin>:12:24: error: cannot find 'await' in scope let data = try await download(from: url) ^~~~~
async/await
なんかフラグがいるんだっけ (edited)-enable-experimental-concurrency
?import Foundation func download(from url: URL) async throws -> Data { fatalError("Unimplemented yet.") } let url: URL! = nil @asyncHandler func onButtonPressed(_ sender: Any) { do { let data = try await download(from: url) print(data.count) } catch { print("\(error)") } }
import Foundation func download(from url: URL) async throws -> Data { fatalError("Unimplemented yet.") } let url: URL! = nil @asyncHandler func onButtonPressed(_ sender: Any) { do { let data = try await download(from: url) print(data.count) } catch { print("\(error)") } }
sil_stage canonical import Builtin import Swift import SwiftShims import Foundation func download(from url: URL) async throws -> Data @_hasStorage @_hasInitialValue let url: URL! { get } @asyncHandler func onButtonPressed(_ sender: Any) // url sil_global hidden [let] @$s4main3url10Foundation3URLVSgvp : $Optional<URL> // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): alloc_global @$s4main3url10Foundation3URLVSgvp // id: %2 %3 = global_addr @$s4main3url10Foundation3URLVSgvp : $*Optional<URL> // user: %5 %4 = enum $Optional<URL>, #Optional.none!enumelt // user: %5 store %4 to %3 : $*Optional<URL> // id: %5 %6 = integer_literal $Builtin.Int32, 0 // user: %7 %7 = struct $Int32 (%6 : $Builtin.Int32) // user: %8 return %7 : $Int32 // id: %8 } // end sil function 'main' // download(from:) sil hidden @$s4main8download4from10Foundation4DataVAD3URLV_tYKF : $@convention(thin) (@guaranteed URL) -> (@owned Data, @error Error) { // %0 "url" // user: %1 bb0(%0 : $URL): debug_value %0 : $URL, let, name "url", argno 1 // id: %1 debug_value undef : $Error, var, name "$error", argno 2 // id: %2 %3 = string_literal utf8 "main/<stdin>" // user: %5 %4 = integer_literal $Builtin.Word, 12 // user: %9 %5 = builtin "ptrtoint_Word"(%3 : $Builtin.RawPointer) : $Builtin.Word // user: %9 br bb1 // id: %6 bb1: // Preds: bb0 %7 = integer_literal $Builtin.Int8, 2 // user: %9 br bb2 // id: %8 bb2: // Preds: bb1 %9 = struct $StaticString (%5 : $Builtin.Word, %4 : $Builtin.Word, %7 : $Builtin.Int8) // user: %28 %1
async/await
関連actor
関連struct Foo { init() async throws { fatalError() } }
(edited)<stdin>:2:12: error: initializer cannot be marked 'async' init() async throws { ^~~~~~
import Foundation @objc public protocol C { @objc optional var field1: ObjCBool { get set } } extension C { public func set(value: Bool) { self[keyPath: \C.field1] = ObjCBool(value) } }
SIL verification failed: keypath value type should match value type of keypath pattern: leafTy == pattern->getValueType().subst(patternSubs)->getCanonicalType() Verifying instruction: -> %6 = keypath $ReferenceWritableKeyPath<C, Optional<ObjCBool>>, (root $C; settable_property $ObjCBool, id #C.field1!getter.1 : <Self where Self : C> (Self) -> () -> ObjCBool, getter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTK : $@convention(thin) (@in_guaranteed C) -> @out ObjCBool, setter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTk : $@convention(thin) (@in_guaranteed ObjCBool, @in_guaranteed C) -> ()) // users: %20, %16 %16 = apply %15<C, Optional<ObjCBool>>(%11, %6, %13) : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @guaranteed ReferenceWritableKeyPath<τ_0_0, τ_0_1>, @in τ_0_1) -> () destroy_value %6 : $ReferenceWritableKeyPath<C, Optional<ObjCBool>> // id: %20 In function: // C.set(value:) sil [ossa] @$s4main1CPAAE3set5valueySb_tF : $@convention(method) <Self where Self : C> (Bool, @guaranteed Self) -> () { // %0 // users: %9, %2 // %1 // users: %4, %3 bb0(%0 : $Bool, %1 : @guaranteed $Self): debug_value %0 : $Bool, let, name "value", argno 1 // id: %2 debug_value %1 : $Self, let, name "self", argno 2 // id: %3 %4 = copy_value %1 : $Self // user: %5 %5 = init_existential_ref %4 : $Self : $Self, $C // user: %12 %6 = keypath $ReferenceWritableKeyPath<C, Optional<ObjCBool>>, (root $C; settable_property $ObjCBool, id #C.field1!getter.1 : <Self where Self : C> (Self) -> () -> ObjCBool, getter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTK : $@convention(thin) (@in_guaranteed C) -> @out ObjCBool, setter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTk : $@convention(thin) (@in_guaranteed ObjCBool, @in_guaranteed C) -> ()) // users: %20, %16 %7 = metatype $@thin ObjCBool.Type /
SIL verification failed: keypath value type should match value type of keypath pattern: leafTy == pattern->getValueType().subst(patternSubs)->getCanonicalType() Verifying instruction: -> %6 = keypath $ReferenceWritableKeyPath<C, Optional<ObjCBool>>, (root $C; settable_property $ObjCBool, id #C.field1!getter.1 : <Self where Self : C> (Self) -> () -> ObjCBool, getter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTK : $@convention(thin) (@in_guaranteed C) -> @out ObjCBool, setter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTk : $@convention(thin) (@in_guaranteed ObjCBool, @in_guaranteed C) -> ()) // users: %20, %16 %16 = apply %15<C, Optional<ObjCBool>>(%11, %6, %13) : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @guaranteed ReferenceWritableKeyPath<τ_0_0, τ_0_1>, @in τ_0_1) -> () destroy_value %6 : $ReferenceWritableKeyPath<C, Optional<ObjCBool>> // id: %20 In function: // C.set(value:) sil @$s4main1CPAAE3set5valueySb_tF : $@convention(method) <Self where Self : C> (Bool, @guaranteed Self) -> () { // %0 // users: %9, %2 // %1 // users: %4, %3 bb0(%0 : @trivial $Bool, %1 : @guaranteed $Self): debug_value %0 : $Bool, let, name "value", argno 1 // id: %2 debug_value %1 : $Self, let, name "self", argno 2 // id: %3 %4 = copy_value %1 : $Self // user: %5 %5 = init_existential_ref %4 : $Self : $Self, $C // user: %12 %6 = keypath $ReferenceWritableKeyPath<C, Optional<ObjCBool>>, (root $C; settable_property $ObjCBool, id #C.field1!getter.1 : <Self where Self : C> (Self) -> () -> ObjCBool, getter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTK : $@convention(thin) (@in_guaranteed C) -> @out ObjCBool, setter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTk : $@convention(thin) (@in_guaranteed ObjCBool, @in_guaranteed C) -> ()) // users: %20, %16 %7 = metatype $@thin ObjCBool.Type
SIL verification failed: keypath value type should match value type of keypath pattern Optional<ObjCBool> ObjCBool Verifying instruction: -> %6 = keypath $ReferenceWritableKeyPath<C, Optional<ObjCBool>>, (root $C; settable_property $ObjCBool, id #C.field1!getter : <Self where Self : C> (Self) -> () -> ObjCBool, getter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTK : $@convention(thin) (@in_guaranteed C) -> @out ObjCBool, setter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTk : $@convention(thin) (@in_guaranteed ObjCBool, @in_guaranteed C) -> ()) // users: %20, %16 %16 = apply %15<C, Optional<ObjCBool>>(%11, %6, %13) : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @guaranteed ReferenceWritableKeyPath<τ_0_0, τ_0_1>, @in τ_0_1) -> () destroy_value %6 : $ReferenceWritableKeyPath<C, Optional<ObjCBool>> // id: %20 In function: // C.set(value:) sil [ossa] @$s4main1CPAAE3set5valueySb_tF : $@convention(method) <Self where Self : C> (Bool, @guaranteed Self) -> () { // %0 "value" // users: %9, %2 // %1 "self" // users: %4, %3 bb0(%0 : $Bool, %1 : @guaranteed $Self): debug_value %0 : $Bool, let, name "value", argno 1 // id: %2 debug_value %1 : $Self, let, name "self", argno 2 // id: %3 %4 = copy_value %1 : $Self // user: %5 %5 = init_existential_ref %4 : $Self : $Self, $C // user: %12 %6 = keypath $ReferenceWritableKeyPath<C, Optional<ObjCBool>>, (root $C; settable_property $ObjCBool, id #C.field1!getter : <Self where Self : C> (Self) -> () -> ObjCBool, getter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTK : $@convention(thin) (@in_guaranteed C) -> @out ObjCBool, setter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTk : $@convention(thin) (@in_guaranteed ObjCBool, @in_guaranteed C) -> ()) // users: %20, %16 %7 = metatype $@thin ObjCBool.Type // user: %9 // function_ref ObjCBool.init(_:)
<stdin>:5:9: error: property cannot be marked @objc because its type cannot be represented in Objective-C var field1: ObjCBool { get set } ^ ~~~~~~~~ <stdin>:5:17: note: Swift structs cannot be represented in Objective-C var field1: ObjCBool { get set } ^~~~~~~~
SIL verification failed: keypath value type should match value type of keypath pattern Optional<ObjCBool> ObjCBool Verifying instruction: -> %6 = keypath $ReferenceWritableKeyPath<C, Optional<ObjCBool>>, (root $C; settable_property $ObjCBool, id #C.field1!getter : <Self where Self : C> (Self) -> () -> ObjCBool, getter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTK : $@convention(thin) (@in_guaranteed C) -> @out ObjCBool, setter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTk : $@convention(thin) (@in_guaranteed ObjCBool, @in_guaranteed C) -> ()) // users: %20, %16 %16 = apply %15<C, Optional<ObjCBool>>(%11, %6, %13) : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @guaranteed ReferenceWritableKeyPath<τ_0_0, τ_0_1>, @in τ_0_1) -> () destroy_value %6 : $ReferenceWritableKeyPath<C, Optional<ObjCBool>> // id: %20 In function: // C.set(value:) sil [ossa] @$s4main1CPAAE3set5valueySb_tF : $@convention(method) <Self where Self : C> (Bool, @guaranteed Self) -> () { // %0 "value" // users: %9, %2 // %1 "self" // users: %4, %3 bb0(%0 : $Bool, %1 : @guaranteed $Self): debug_value %0 : $Bool, let, name "value", argno 1 // id: %2 debug_value %1 : $Self, let, name "self", argno 2 // id: %3 %4 = copy_value %1 : $Self // user: %5 %5 = init_existential_ref %4 : $Self : $Self, $C // user: %12 %6 = keypath $ReferenceWritableKeyPath<C, Optional<ObjCBool>>, (root $C; settable_property $ObjCBool, id #C.field1!getter : <Self where Self : C> (Self) -> () -> ObjCBool, getter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTK : $@convention(thin) (@in_guaranteed C) -> @out ObjCBool, setter @$s4main1CP6field110Foundation8ObjCBoolVvpAaB_pTk : $@convention(thin) (@in_guaranteed ObjCBool, @in_guaranteed C) -> ()) // users: %20, %16 %7 = metatype $@thin ObjCBool.Type // user: %9 // function_ref ObjCBool.init(_:)
class Foo<T> {} class Bar: Foo<Bar> {} func foo<F: Foo<F>>(_ foo: F) {}
<stdin>:4:13: error: superclass constraint 'F' : 'Foo<F>' is recursive func foo<F: Foo<F>>(_ foo: F) {} ^
import Dispatch func suspendAsync<T>( _ body: (_ continuation: @escaping (T) -> ()) -> () ) async -> T { let semaphore = DispatchSemaphore(value: 0) var result: T! body { value in result = value semaphore.signal() } semaphore.wait() return result } extension DispatchQueue { func asyncAfter(deadline: DispatchTime) async { await suspendAsync { continuation in asyncAfter(deadline: deadline) { continuation(()) } } } } @asyncHandler func main() { print("A") await DispatchQueue.global().asyncAfter(deadline: .now() + 1) print("B") await DispatchQueue.global().asyncAfter(deadline: .now() + 1) print("C") } main()
func primes(upTo number: Int) -> [Int] { precondition(number >= 0) if number < 2 { return [] } var sieve: [Bool] = .init(repeating: false, count: number + 1) for m in stride(from: 3, through: Int(Double(number).squareRoot() + 1.5), by: 2) { if sieve[m] { continue } let maxK = number / m if maxK < 2 { continue } for k in 2 ... maxK { sieve[k * m] = true } } var result: [Int] = [2] for m in stride(from: 3, through: number, by: 2) { if sieve[m] { continue } result.append(m) } return result } print(primes(upTo: 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
func primes(upTo number: Int) -> [Int] { precondition(number >= 0) if number < 2 { return [] } var sieve: [Bool] = .init(repeating: false, count: number + 1) for m in stride(from: 3, through: Int(Double(number).squareRoot() + 1.5), by: 2) { if sieve[m] { continue } let maxK = number / m if maxK < 2 { continue } for k in 2 ... maxK { sieve[k * m] = true } } var result: [Int] = [2] for m in stride(from: 3, through: number, by: 2) { if sieve[m] { continue } result.append(m) } return result } print(primes(upTo: 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
print("Hello, World!")
Swift version 5.3.1 (swift-5.3.1-RELEASE) Target: x86_64-unknown-linux-gnu
import Foundation func measure(_ body: () -> Void) { let start = Date.timeIntervalSinceReferenceDate for _ in 0 ..< 10 { body() } let end = Date.timeIntervalSinceReferenceDate print((end - start) / 10) } extension Array { mutating func mySwapAt(_ i: Int, _ j: Int) { let t = self[i] self[i] = self[j] self[j] = t } } func swapBySwapAt(_ array: inout [Int]) { for i in array.indices.dropFirst() { array.swapAt(i - 1, i) } } func swapByT(_ array: inout [Int]) { for i in array.indices.dropFirst() { let t = array[i] array[i] = array[i - 1] array[i - 1] = t } } func swapByMySwapAt(_ array: inout [Int]) { for i in array.indices.dropFirst() { array.mySwapAt(i - 1, i) } } let n: Int = 10_000_000 + (1 ... 100).randomElement()! var a: [Int] = Array(1 ... n) measure { swapBySwapAt(&a) } measure { swapByT(&a) } measure { swapByMySwapAt(&a) } print(a.count)
0.07282540798187256 0.07877689599990845 0.0749101996421814 10000014
swapBySwapAt
が 10% くらい遅いんだけどなぁ。import Foundation func measure(_ body: () -> Void) { let start = Date.timeIntervalSinceReferenceDate for _ in 0 ..< 10 { body() } let end = Date.timeIntervalSinceReferenceDate print((end - start) / 10) } func mapFilter(_ n: Int) -> [Int] { precondition(n >= 1) return (1 ... n).map { $0 * $0 }.filter { $0 % 7 == 1 } } func lazyMapFilter(_ n: Int) -> [Int] { precondition(n >= 1) return Array((1 ... n).lazy.map { $0 * $0 }.filter { $0 % 7 == 1 }) } func mapFilterByLoop(_ n: Int) -> [Int] { precondition(n >= 1) var result: [Int] = [] for i in 1 ... n { let square = i * i guard square % 7 == 1 else { continue } result.append(square) } return result } let n: Int = 10_000_000 + (1 ... 100).randomElement()! var a = 0 measure { a += mapFilter(n).count } measure { a += lazyMapFilter(n).count } measure { a += mapFilterByLoop(n).count } print(a)
0.5088738918304443 0.09912219047546386 0.09465489387512208 85715100
import Foundation func measure(_ body: () -> Void) { let start = Date.timeIntervalSinceReferenceDate for _ in 0 ..< 10 { body() } let end = Date.timeIntervalSinceReferenceDate print((end - start) / 10) } func sumOfArray(_ a: [Int], indices: [Int]) -> Int { var sum = 0 for i in indices { sum &+= a[i] } return sum } func sumOfArraySlice(_ a: ArraySlice<Int>, indices: [Int]) -> Int { var sum = 0 for i in indices { sum &+= a[i] } return sum } let n: Int = 1_000_000 + (1 ... 100).randomElement()! let a: [Int] = .init(1 ... n) let b: ArraySlice<Int> = .init(a) let indices: [Int] = a.indices.shuffled() var sum = 0 measure { sum &+= sumOfArray(a, indices: indices) } measure { sum &+= sumOfArraySlice(b, indices: indices) } print(sum)
0.02275540828704834 0.022072792053222656 10002010101000
import Foundation func measure(_ body: () -> Void) { let start = Date.timeIntervalSinceReferenceDate for _ in 0 ..< 10 { body() } let end = Date.timeIntervalSinceReferenceDate print((end - start) / 10) } public func sumOfEvensByStride(_ n: Int) -> Int { var sum = 0 for m in stride(from: 0, through: n * 2, by: 2) { sum &+= m } return sum } public func sumOfEvensByRange(_ n: Int) -> Int { var sum = 0 for m in 0 ... n { sum &+= m * 2 } return sum } public func sumOfMultiplesByStride(_ n: Int, k: Int) -> Int { var sum = 0 for m in stride(from: 0, through: n * k, by: k) { sum &+= m } return sum } public func sumOfMultiplesByRange(_ n: Int, k: Int) -> Int { var sum = 0 for m in 0 ... n { sum &+= m * k } return sum } let n = 100_000_000 + (1 ... 100).randomElement()! var a = 0 measure { a &+= sumOfEvensByStride(n) } measure { a &+= sumOfEvensByRange(n) } measure { a &+= sumOfMultiplesByStride(n, k: 3) } measure { a &+= sumOfMultiplesByRange(n, k: 3) } print(a)
0.1298200011253357 0.0950276017189026 0.09767409563064575 0.09397300481796264 500000385000074100
// Ported from https://www.raywenderlich.com/741-swift-algorithm-club-swift-merge-sort func mergeSort<T: Comparable>(_ array: [T]) async -> [T] { guard array.count > 1 else { return array } let middleIndex = array.count / 2 async let leftArray = await mergeSort(Array(array[0..<middleIndex])) async let rightArray = await mergeSort(Array(array[middleIndex..<array.count])) return merge(await leftArray, await rightArray) } func merge<T: Comparable>(_ left: [T], _ right: [T]) -> [T] { var leftIndex = 0 var rightIndex = 0 var orderedArray: [T] = [] while leftIndex < left.count && rightIndex < right.count { let leftElement = left[leftIndex] let rightElement = right[rightIndex] if leftElement < rightElement { orderedArray.append(leftElement) leftIndex += 1 } else if leftElement > rightElement { orderedArray.append(rightElement) rightIndex += 1 } else { orderedArray.append(leftElement) leftIndex += 1 orderedArray.append(rightElement) rightIndex += 1 } } while leftIndex < left.count { orderedArray.append(left[leftIndex]) leftIndex += 1 } while rightIndex < right.count { orderedArray.append(right[rightIndex]) rightIndex += 1 } return orderedArray } func getRandomArray(n: Int) -> [Int] { var array = [Int]() for i in 0..<n { array.append(Int.random(in: 0..<1000)) } return array } func test(n: Int) async { let array = getRandomArray(n: n) let sortedArray = await mergeSort(array) print(sortedArray) } runAsyncAndBlock { await test(n: 100) }
(edited)[2, 19, 20, 28, 28, 52, 67, 69, 72, 89, 91, 103, 104, 106, 116, 125, 165, 175, 184, 187, 196, 198, 208, 211, 214, 235, 243, 247, 248, 251, 268, 293, 306, 309, 312, 321, 339, 339, 345, 364, 393, 396, 404, 406, 420, 425, 434, 446, 453, 455, 474, 478, 480, 483, 485, 487, 488, 493, 499, 511, 520, 528, 543, 604, 628, 636, 645, 650, 650, 666, 670, 673, 678, 690, 713, 716, 720, 721, 723, 730, 761, 764, 797, 811, 819, 832, 834, 839, 843, 844, 860, 885, 905, 916, 925, 931, 942, 959, 959, 986]
stderr:<stdin>:52:7: warning: immutable value 'i' was never used; consider replacing with '_' or removing it for i in 0..<n { ^ _
(edited)// // main.swift // ConcurrencyPlayground // // Created by Max Desiatov on 07/01/2021. // import _Concurrency import Foundation import FoundationNetworking struct UnknownError: Error {} func download(url: URL) async throws -> Data { try await withUnsafeThrowingContinuation { c in let task = URLSession.shared.dataTask(with: url) { data, _, error in switch (data, error) { case let (_, error?): return c.resume(throwing: error) case let (data?, _): return c.resume(returning: data) case (nil, nil): c.resume(throwing: UnknownError()) } } task.resume() } } runAsyncAndBlock { print("task started") let data = try! await download(url: URL(string: "https://httpbin.org/uuid")!) print(String(data: data, encoding: .utf8)!) } print("end of main")
(edited)task started end of main
Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. /usr/bin/swift-frontend[0x56a4d34] /usr/bin/swift-frontend[0x56a2bb0] /usr/bin/swift-frontend[0x56a4f1a] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f6d470ce390] /lib/x86_64-linux-gnu/libc.so.6(strlen+0x26)[0x7f6d45a89746] /lib/x86_64-linux-gnu/libc.so.6(__strdup+0xe)[0x7f6d45a8947e] /usr/lib/x86_64-linux-gnu/libcurl.so.4(+0x1de88)[0x7f6d3e9dde88] /usr/lib/x86_64-linux-gnu/libcurl.so.4(curl_easy_setopt+0x9e)[0x7f6d3e9ed8ae] /usr/lib/swift/linux/libFoundationNetworking.so($s20FoundationNetworking11_EasyHandleC3set3urly0A03URLV_tF+0xcc)[0x7f6d3ed25afc] /usr/lib/swift/linux/libFoundationNetworking.so($s20FoundationNetworking16_HTTPURLProtocolC19configureEasyHandle3for4bodyyAA10URLRequestV_AA14URLSessionTaskC5_BodyOtF+0x230)[0x7f6d3ecf65f0] /usr/lib/swift/linux/libFoundationNetworking.so(+0xd5bb3)[0x7f6d3ed04bb3] /usr/lib/swift/linux/libFoundationNetworking.so($s20FoundationNetworking14URLSessionTaskC7getBody10completionyyAC01_F0Oc_tF+0x128)[0x7f6d3ed14a48] /usr/lib/swift/linux/libFoundationNetworking.so($s20FoundationNetworking15_NativeProtocolC16startNewTransfer4withyAA10URLRequestV_tF+0xe1)[0x7f6d3ed02041] /usr/lib/swift/linux/libFoundationNetworking.so($s20FoundationNetworking15_NativeProtocolC6resumeyyF+0x28a)[0x7f6d3ed0233a] /usr/lib/swift/linux/libFoundationNetworking.so(+0xf04c7)[0x7f6d3ed1f4c7] /usr/lib/swift/linux/libFoundationNetworking.so(+0xa0c59)[0x7f6d3eccfc59] /usr/lib/swift/linux/libdispatch.so(+0x224e7)[0x7f6d3ef8d4e7] /usr/lib/swift/linux/libdispatch.so(+0x2de39)[0x7f6d3ef98e39] /usr/lib/swift/linux/libdispatch.so(+0x2eade)[0x7f6d3ef99ade] /usr/lib/swift/linux/libdispatch.so(+0x2dcd4)[0x7f6d3ef98cd4] /usr/lib/swift/linux/libdispatch.so(+0x2eade)[0x7f6d3ef99ade] /usr/lib/swift/linux/libdispatch.so(+0x36752)[0x7f6d3efa1752] /lib/x86_64-linux-gnu/libpthread.so.0(+0x76ba)[0x7f6d470c46ba] /li
Swift version 5.3-dev (LLVM 52eb795d06cc2c1, Swift eb8c8ecef009d64) Target: x86_64-unknown-linux-gnu
import Foundation print(ProcessInfo.processInfo.environment["SWIFT_VERSION"]!)
5.4-DEVELOPMENT-SNAPSHOT-2021-01-11-a
// // main.swift // ConcurrencyPlayground // // Created by Max Desiatov on 07/01/2021. // import _Concurrency import Foundation import FoundationNetworking struct UnknownError: Error {} func download(url: URL) async throws -> Data { await try withUnsafeThrowingContinuation { c in let task = URLSession.shared.dataTask(with: url) { data, _, error in switch (data, error) { case let (_, error?): return c.resume(throwing: error) case let (data?, _): return c.resume(returning: data) case (nil, nil): c.resume(throwing: UnknownError()) } } task.resume() } } runAsyncAndBlock { print("task started") let data = await try! download(url: URL(string: "https://httpbin.org/uuid")!) print(String(data: data, encoding: .utf8)!) } print("end of main")
(edited)print(Task.self)
print(await Task.currentPriority())
<stdin>:1:13: error: 'async' in a function that does not support concurrency print(await Task.currentPriority()) ^
print(Task.userInteractive)
<stdin>:1:12: error: type 'Task' has no member 'userInteractive' print(Task.userInteractive) ~~~~ ^~~~~~~~~~~~~~~
print(Task.Priority.self)
(edited)Priority
print(Task.Priority.init(rawValue: 0)!)
unspecified
print(Task.Priority.init(rawValue: 1)!)
main/<stdin>:1: Fatal error: Unexpectedly found nil while unwrapping an Optional value Current stack trace: 0 libswiftCore.so 0x00007f8d025ef150 swift_reportError + 50 1 libswiftCore.so 0x00007f8d026638f0 _swift_stdlib_reportFatalErrorInFile + 112 2 libswiftCore.so 0x00007f8d02343de6 <unavailable> + 1433062 3 libswiftCore.so 0x00007f8d02343a0f <unavailable> + 1432079 4 libswiftCore.so 0x00007f8d023437ac <unavailable> + 1431468 5 libswiftCore.so 0x00007f8d023432c0 _assertionFailure(_:_:file:line:flags:) + 441 7 swift-frontend 0x0000000000597635 <unavailable> + 1668661 8 swift-frontend 0x000000000056102e <unavailable> + 1445934 9 swift-frontend 0x000000000052c442 <unavailable> + 1229890 10 swift-frontend 0x000000000052baac <unavailable> + 1227436 11 swift-frontend 0x000000000051ee4d <unavailable> + 1175117 12 swift-frontend 0x00000000004b8f78 <unavailable> + 757624 13 libc.so.6 0x00007f8d0462a740 __libc_start_main + 240 14 swift-frontend 0x00000000004b8a49 <unavailable> + 756297 Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build
let handle: Task.Handle<Int, Never> = Task.runDetached { 42 } print(await handle.get())
(edited)<stdin>:1:18: error: generic type 'Handle' specialized with too many type parameters (got 2, but expected 1) let handle: Task.Handle<Int, Never> = Task.runDetached { 42 } ^ ~~~~~~~~~~~~ _Concurrency.Task:2:19: note: generic type 'Handle' declared here public struct Handle<Success> { ^
let handle: Task.Handle<Int> = Task.runDetached { 42 } print(try await handle.get())
(edited)<stdin>:2:17: error: 'async' in a function that does not support concurrency print(try await handle.get()) ^
(edited)_ = Task.runDetached { 42 }
func foo() async -> Int { 42 } @asyncHandler func bar() { let a = await foo() print(a) }
func foo() async -> Int { 3 } func main() async { async let a = foo() async let b = foo() print(await a + b) }
func foo() async -> Int { 3 } func main() async { async let a = foo() async let b = foo() print(await a + b) } runAsyncAndBlock { await main() }
(edited)func f() async throws -> Int { 1 } func g() async throws -> Int { let a = try await f() let b = await try f() return a + b }
<stdin>:4:13: warning: 'try' must precede 'await' let b = await try f() ^~~~~~ await
<stdin>:3:17: error: 'await' must precede 'try' let a = try await f() ^~~~~~ await
func foo() async -> Int { 42 } runAsyncAndBlock { await foo() }
(edited)<stdin>:2:26: warning: result of call to 'foo()' is unused runAsyncAndBlock { await foo() } ^ ~~
/usr/bin/lldb: error while loading shared libraries: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory
import Foundation import FoundationNetworking struct User: Identifiable, Codable { typealias ID = Int let id: ID var name: String var thumbnailURL: URL } func download(from url: URL, completion: @escaping (Data) -> Void) { let data: Data = try! Data(contentsOf: url) completion(data) } func fetchUser(for id: User.ID, completion: @escaping (User) -> Void) { let url: URL = URL(string: "https://koherent.org/async-await-challenge/api/user?id=\(id.description)")! download(from: url) { data in let user = try! JSONDecoder().decode(User.self, from: data) completion(user) } } fetchUser(for: 123) { user in print(user.name) }
import Foundation struct User: Identifiable, Codable { typealias ID = Int let id: ID var name: String var thumbnailURL: URL } func download(from url: URL) async -> Data { let data: Data = try! Data(contentsOf: url) return data } func fetchUser(for id: User.ID) async -> User { let url: URL = URL(string: "https://koherent.org/async-await-challenge/api/user?id=\(id.description)")! let data = await download(from: url) let user = try! JSONDecoder().decode(User.self, from: data) return user } runAsyncAndBlock { let user = await fetchUser(for: 123) print(user.name) }
(edited)Foundation/NSSwiftRuntime.swift:401: Fatal error: You must link or load module FoundationNetworking to load non-file: URL content using String(contentsOf:…), Data(contentsOf:…), etc. Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -enable-experimental-concurrency -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIODarwin.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-li
(edited)import Foundation import FoundationNetworking struct User: Identifiable, Codable { typealias ID = Int let id: ID var name: String var thumbnailURL: URL } func download(from url: URL) async -> Data { let data: Data = try! Data(contentsOf: url) return data } func fetchUser(for id: User.ID) async -> User { let url: URL = URL(string: "https://koherent.org/async-await-challenge/api/user?id=\(id.description)")! let data = await download(from: url) return try! JSONDecoder().decode(User.self, from: data) } runAsyncAndBlock { let user = await fetchUser(for: 123) print(user.name) }
import Foundation extension Process { struct RunResult { var output: Data var error: Data var status: Int32 } static func which(_ i: Int) throws -> RunResult { let p = Process() p.executableURL = URL(fileURLWithPath: "/usr/bin/which") p.arguments = ["which"] let g = DispatchGroup() var outData = Data() let outPipe = Pipe() p.standardOutput = outPipe g.enter() outPipe.fileHandleForReading.readabilityHandler = { (handle) in let availableData = handle.availableData outData.append(availableData) print("[\(i)] stdout \(availableData)") if availableData.isEmpty { outPipe.fileHandleForReading.readabilityHandler = nil g.leave() } } var errData = Data() let errPipe = Pipe() p.standardError = errPipe g.enter() errPipe.fileHandleForReading.readabilityHandler = { (handle) in let availableData = handle.availableData errData.append(availableData) print("[\(i)] stderr \(availableData)") if availableData.isEmpty { errPipe.fileHandleForReading.readabilityHandler = nil g.leave() } } try p.run() p.waitUntilExit() print("[\(i)] process end") guard case .success = g.wait(timeout: .now()+3) else { fatalError("[\(i)] timeout") } print("[\(i)] wait end") let status = p.terminationStatus let result = RunResult(output: outData, error: errData, status: status) print("[\(i)] end output=\(result.output) error=\(result.error)") return result } } DispatchQueue.concurrentPerform(iterations: 3) { i in _ = try! Process.which(i) } print("end")
Fatal error: [1] timeout: file main/<stdin>, line 46 Fatal error: [2] timeout: file main/<stdin>, line 46 Current stack trace: Current stack trace: Fatal error: [0] timeout: file main/<stdin>, line 46 Current stack trace: 0 libswiftCore.so 0x00007f76f2276df0 swift_reportError + 50 1 libswiftCore.so 0x00007f76f22ea160 _swift_stdlib_reportFatalErrorInFile + 115 2 libswiftCore.so 0x00007f76f1fcfeb5 <unavailable> + 1400501 3 libswiftCore.so 0x00007f76f1fcfaf7 <unavailable> + 1399543 4 libswiftCore.so 0x00007f76f1fd00e2 <unavailable> + 1401058 5 libswiftCore.so 0x00007f76f1fce530 _assertionFailure(_:_:file:line:flags:) + 517 8 libswiftDispatch.so 0x00007f76ee5f2bf1 <unavailable> + 117745 9 libswiftDispatch.so 0x00007f76ee5f2c14 <unavailable> + 117780 10 libdispatch.so 0x00007f76ee39560e <unavailable> + 128526 11 libdispatch.so 0x00007f76ee3ac787 <unavailable> + 223111 12 libpthread.so.0 0x00007f76f66ed6ba <unavailable> + 30394 13 libc.so.6 0x00007f76f4ef63b0 clone + 109 0 libswiftCore.so 0x00007f76f2276df0 swift_reportError + 50 0 libswiftCore.so 0x00007f76f2276df0 swift_reportError + 50 1 libswiftCore.so 0x00007f76f22ea160 _swift_stdlib_reportFatalErrorInFile + 115 2 libswiftCore.so 0x00007f76f1fcfeb5 <unavailable> + 1400501 3 libswiftCore.so 0x00007f76f1fcfaf7 <unavailable> + 1399543 4 libswiftCore.so 0x00007f76f1fd00e2 <unavailable> + 1401058 5 libswiftCore.so 0x00007f76f1fce530 _assertionFailure(_:_:file:line:flags:) + 517 8 libswiftDispatch.so 0x00007f76ee5f2bf1 <unavailable> + 117745 9 libswiftDispatch.so
import Foundation extension Process { struct RunResult { var output: Data var error: Data var status: Int32 } static func which(_ i: Int) throws -> RunResult { let p = Process() p.executableURL = URL(fileURLWithPath: "/usr/bin/which") p.arguments = ["which"] let g = DispatchGroup() var outData = Data() let outPipe = Pipe() p.standardOutput = outPipe g.enter() outPipe.fileHandleForReading.readabilityHandler = { (handle) in let availableData = handle.availableData outData.append(availableData) print("[\(i)] stdout \(availableData)") if availableData.isEmpty { outPipe.fileHandleForReading.readabilityHandler = nil g.leave() } } var errData = Data() let errPipe = Pipe() p.standardError = errPipe g.enter() errPipe.fileHandleForReading.readabilityHandler = { (handle) in let availableData = handle.availableData errData.append(availableData) print("[\(i)] stderr \(availableData)") if availableData.isEmpty { errPipe.fileHandleForReading.readabilityHandler = nil g.leave() } } try p.run() p.waitUntilExit() print("[\(i)] process end") guard case .success = g.wait(timeout: .now()+3) else { fatalError("[\(i)] timeout") } print("[\(i)] wait end") let status = p.terminationStatus let result = RunResult(output: outData, error: errData, status: status) print("[\(i)] end output=\(result.output) error=\(result.error)") return result } } DispatchQueue.concurrentPerform(iterations: 1) { i in _ = try! Process.which(i) } print("end")
Fatal error: [0] timeout: file main/<stdin>, line 46 Current stack trace: 0 libswiftCore.so 0x00007fe78a46edf0 swift_reportError + 50 1 libswiftCore.so 0x00007fe78a4e2160 _swift_stdlib_reportFatalErrorInFile + 115 2 libswiftCore.so 0x00007fe78a1c7eb5 <unavailable> + 1400501 3 libswiftCore.so 0x00007fe78a1c7af7 <unavailable> + 1399543 4 libswiftCore.so 0x00007fe78a1c80e2 <unavailable> + 1401058 5 libswiftCore.so 0x00007fe78a1c6530 _assertionFailure(_:_:file:line:flags:) + 517 8 libswiftDispatch.so 0x00007fe7867eabf1 <unavailable> + 117745 9 libswiftDispatch.so 0x00007fe7867eac14 <unavailable> + 117780 10 libdispatch.so 0x00007fe78658df60 <unavailable> + 130912 11 libdispatch.so 0x00007fe7865993aa <unavailable> + 177066 12 libdispatch.so 0x00007fe78658da40 dispatch_apply_f + 1044 13 libswiftDispatch.so 0x00007fe7867eaaa0 static DispatchQueue.concurrentPerform(iterations:execute:) + 204 15 swift 0x00000000005b4501 <unavailable> + 1787137 16 swift 0x00000000005a1d04 <unavailable> + 1711364 17 swift 0x0000000000587e88 <unavailable> + 1605256 18 swift 0x000000000057b322 <unavailable> + 1553186 19 swift 0x00000000005780ef <unavailable> + 1540335 20 swift 0x0000000000501c2c <unavailable> + 1055788 21 libc.so.6 0x00007fe78d007740 __libc_start_main + 240 22 swift 0x00000000005017a9 <unavailable> + 1054633 Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libr
import Foundation func print(_ item: String) { fputs(item + "\n", stderr) } extension Process { struct RunResult { var output: Data var status: Int32 } static func which(_ i: Int) throws -> RunResult { let p = Process() p.executableURL = URL(fileURLWithPath: "/usr/bin/which") p.arguments = ["which"] let g = DispatchGroup() var outData = Data() let outPipe = Pipe() p.standardOutput = outPipe g.enter() outPipe.fileHandleForReading.readabilityHandler = { (handle) in let availableData = handle.availableData outData.append(availableData) print("[\(i)] stdout \(availableData)") if availableData.isEmpty { outPipe.fileHandleForReading.readabilityHandler = nil g.leave() } } try p.run() p.waitUntilExit() print("[\(i)] process end") guard case .success = g.wait(timeout: .now()+3) else { fatalError("[\(i)] timeout") } print("[\(i)] wait end") let status = p.terminationStatus let result = RunResult(output: outData, status: status) print("[\(i)] end output=\(result.output)") return result } } DispatchQueue.concurrentPerform(iterations: 3) { i in _ = try! Process.which(i) } print("end")
[2] process end [0] stdout 15 bytes [2] stdout 15 bytes [1] process end [1] stdout 15 bytes [0] process end Fatal error: [2] timeout: file main/<stdin>, line 34 Current stack trace: 0 libswiftCore.so 0x00007fbd21293df0 swift_reportError + 50 1 libswiftCore.so 0x00007fbd21307160 _swift_stdlib_reportFatalErrorInFile + 115 2 libswiftCore.so 0x00007fbd20feceb5 <unavailable> + 1400501 3 libswiftCore.so 0x00007fbd20fecaf7 <unavailable> + 1399543 4 libswiftCore.so 0x00007fbd20fed0e2 <unavailable> + 1401058 5 libswiftCore.so 0x00007fbd20feb530 _assertionFailure(_:_:file:line:flags:) + 517 8 libswiftDispatch.so 0x00007fbd1d60fbf1 <unavailable> + 117745 9 libswiftDispatch.so 0x00007fbd1d60fc14 <unavailable> + 117780 10 libdispatch.so 0x00007fbd1d3b260e <unavailable> + 128526 11 libdispatch.so 0x00007fbd1d3c9787 <unavailable> + 223111 12 libpthread.so.0 0x00007fbd2570a6ba <unavailable> + 30394 13 libc.so.6 0x00007fbd23f133b0 clone + 109 /usr/bin/swift[0x50aee34] /usr/bin/swift[0x50ace00] /usr/bin/swift[0x50af11a] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7fbd25714390] /usr/lib/swift/linux/libswiftCore.so($ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_SSAHSus6UInt32VtF+0x212)[0x7fbd20feb742] [0x7fbd2594de50] [0x7fbd2594e209] /usr/lib/swift/linux/libswiftDispatch.so(+0x1cbf1)[0x7fbd1d60fbf1] /usr/lib/swift/linux/libswiftDispatch.so(+0x1cc14)[0x7fbd1d60fc14] /usr/lib/swift/linux/libdispatch.so(+0x1f60e)[0x7fbd1d3b260e] /usr/lib/swift/linux/libdispatch.so(+0x36787)[0x7fbd1d3c9787] /lib/x86_64-linux-gnu/libpthread.so.0(+0x76ba)[0x7fbd2570a6ba] /lib/x86_64-linux-gnu/libc.so.6(clone+0x6d)[0x7fbd23f1341d]
// // main.swift // ConcurrencyPlayground // // Created by Max Desiatov on 07/01/2021. // import Foundation import FoundationNetworking struct UnknownError: Error {} func download(url: URL) async throws -> Data { try await withUnsafeThrowingContinuation { c in let task = URLSession.shared.dataTask(with: url) { data, _, error in switch (data, error) { case let (_, error?): return c.resume(throwing: error) case let (data?, _): return c.resume(returning: data) case (nil, nil): c.resume(throwing: UnknownError()) } } task.resume() } } @main struct Main { static func main() async { print("task started") let data = try! await download(url: URL(string: "https://httpbin.org/uuid")!) print(String(data: data, encoding: .utf8)!) } }
task started { "uuid": "791fc520-32b9-40a9-bf49-77ca7f8e2d4e" }
import Foundation let formatter = NumberFormatter() formatter.numberStyle = .decimal print("1:", formatter.string(from: 100)) // Optional("100") formatter.formatWidth = 6 print("2:", formatter.string(from: 100)) // Optional(" 100") formatter.paddingPosition = .beforePrefix print("3:", formatter.string(from: 100)) // Optional(" 100") formatter.paddingPosition = .afterPrefix print("4:", formatter.string(from: 100)) // Optional(" 100") formatter.paddingPosition = .beforeSuffix print("5:", formatter.string(from: 100)) // Optional("100 ") formatter.paddingPosition = .afterSuffix print("6:", formatter.string(from: 100)) // Optional("100 ")
(edited)1: Optional("100") 2: Optional(" 100") 3: Optional(" 100") 4: Optional(" 100") 5: Optional("100 ") 6: Optional("100 ")
stderr:<stdin>:5:13: warning: expression implicitly coerced from 'String?' to 'Any' print("1:", formatter.string(from: 100)) // Optional("100") ^~~~~~~~~~~~~~~~~~~~~~~~~~~ <stdin>:5:23: note: provide a default value to avoid this warning print("1:", formatter.string(from: 100)) // Optional("100") ~~~~~~~~~~^~~~~~~~~~~~~~~~~ ?? <#default value#> <stdin>:5:23: note: force-unwrap the value to avoid this warning print("1:", formatter.string(from: 100)) // Optional("100") ~~~~~~~~~~^~~~~~~~~~~~~~~~~ ! <stdin>:5:23: note: explicitly cast to 'Any' with 'as Any' to silence this warning print("1:", formatter.string(from: 100)) // Optional("100") ~~~~~~~~~~^~~~~~~~~~~~~~~~~ as Any <stdin>:8:13: warning: expression implicitly coerced from 'String?' to 'Any' print("2:", formatter.string(from: 100)) // Optional(" 100") ^~~~~~~~~~~~~~~~~~~~~~~~~~~ <stdin>:8:23: note: provide a default value to avoid this warning print("2:", formatter.string(from: 100)) // Optional(" 100") ~~~~~~~~~~^~~~~~~~~~~~~~~~~ ?? <#default value#> <stdin>:8:23: note: force-unwrap the value to avoid this warning print("2:", formatter.string(from: 100)) // Optional(" 100") ~~~~~~~~~~^~~~~~~~~~~~~~~~~ ! <stdin>:8:23: note: explicitly cast to 'Any' with 'as Any' to silence this warning print("2:", formatter.string(from: 100)) // Optional(" 100") ~~~~~~~~~~^~~~~~~~~~~~~~~~~ as Any <stdin>:11:13: warning: expression implicitly coerced from 'String?' to 'Any' print("3:", formatter.string(from: 100)) // Optional(" 100") ^~~~~
(edited)import Foundation struct A: Encodable { var a1: Int = 1 var a2: Int = 2 } struct B: Encodable { var b1: Int = 3 var b2: Int = 4 } struct AAndB: Encodable { var a: A = .init() var b: B = .init() func encode(to encoder: Encoder) throws { try a.encode(to: encoder) try b.encode(to: encoder) } // func encode(to encoder: Encoder) throws { // do { // var c = encoder.singleValueContainer() // try c.encode(a) // } // do { // var c = encoder.singleValueContainer() // try c.encode(b) // } // } } func main() throws { let x = AAndB() let e = JSONEncoder() let j = try e.encode(x) print(String(decoding: j, as: UTF8.self)) } try! main()
{"a2":2,"b1":3,"a1":1,"b2":4}
let foo = Array {} print(type(of: foo))
init(arrayLiteral:)
って Array Literal 用のinitだから、let foo = Array arrayLiteral: {}
arrayLiteral:
が Xcodeによって表示されてれば、問題は解決する。let
の右に出てたらわかりやすいと思う。let
の右に出てたらわかりやすいと思う。 var foo : () -> Int foo = { foo() }
<stdin>:2:7: error: variable 'foo' captured by a closure before being initialized foo = { foo() } ^ <stdin>:1:5: note: variable defined here var foo : () -> Int ^
Set-Cookie: … set-cookie: …
を入れる様になり、使ってたライブラリ内で let headers = [String: Any](uniqueKeysWithValues: response.allHeaderFields.map { (($0.key as! String).lowercased(), $0.value) })
としてcase insensitive uniqueであることを期待してた箇所でランタイムエラーになってた。 (edited)!
使うのは危険ですね。!
の利用ではなく、init(uniqueKeysWithValues:)
APIへ外部データがcase insensitive uniqueだと無邪気に信じて単純な変換のみで渡したことですね。uniqueKeysWithValues
に渡すものがおかしいのは Logic Failure でいいと思うんですが、ユニーク化のときにユニークでない場合に Recoverable なエラーハンドリングができる簡単な方法があるといいですよね。 uniqueKeysWithValues
は割と踏みがちな気がするので・・・。guard let uniqueHeaderFields = response.allHeaderFields .map { (($0.key as! String).lowercased(), $0.value) } .unique(\.0) else { ... }
とか?allHeaderFields
がcase insensitiveなのか。Dictionary.init
の話ですか?
rethrows
がめっちゃ活きてますね。Set-Cookie
は[String]
としてallHeaderFields
に入るみたい。import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif guard let url = URL(string: "https://discordapp.com/api/v7/gateway/bot") else { exit(1) } let task = URLSession.shared.dataTask(with: url) { dataOrNil, responseOrNil, errorOrNil in guard let response = responseOrNil as? HTTPURLResponse else { exit(1) } let allHeaderFields = response.allHeaderFields.map { (key, value) in ((key as! String).lowercased(), value) } let headers = [String: Any](allHeaderFields, uniquingKeysWith: { (lhs, rhs) in switch (lhs, rhs) { case (let lhs as [String], let rhs as [String]): return lhs + rhs case (let lhs as [String], let rhs as String): return lhs + [rhs] case (let lhs as String, let rhs as [String]): return [lhs] + rhs case (let lhs as String, let rhs as String): return [lhs, rhs] default: return rhs } }) dump(headers) exit(0) } task.resume() dispatchMain()
(edited)▿ 16 key/value pairs ▿ (2 elements) - key: "date" - value: "Tue, 13 Apr 2021 04:26:24 GMT" ▿ (2 elements) - key: "strict-transport-security" - value: "max-age=31536000; includeSubDomains" ▿ (2 elements) - key: "cf-ray" - value: "63f1ef9dbf553806-IAD" ▿ (2 elements) - key: "connection" - value: "keep-alive" ▿ (2 elements) - key: "cf-request-id" - value: "096b1416900000380660129000000001" ▿ (2 elements) - key: "cf-cache-status" - value: "DYNAMIC" ▿ (2 elements) - key: "via" - value: "1.1 google" ▿ (2 elements) - key: "content-length" - value: "43" ▿ (2 elements) - key: "expect-ct" - value: "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"" ▿ (2 elements) - key: "report-to" - value: "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report?s=6nGtl8vxSfMGS4%2Fg8PcS6skF%2FlvqoTCQES4uLM5cC146gNRLzD%2FY8X%2BPide4V6MCz57kfNUXBY084%2BCGO3VO91oIQiMHHDyZNq6LzNs4kw%3D%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}" ▿ (2 elements) - key: "set-cookie" ▿ value: 2 elements - "__cfduid=d2062717f605ce464e7f88d444e655ede1618287984; expires=Thu, 13-May-21 04:26:24 GMT; path=/; domain=.discordapp.com; HttpOnly; SameSite=Lax" - "__dcfduid=8854356cde9c452195623d3534a3e91a; Expires=Thu, 13-May-2021 04:26:24 GMT; Max-Age=2592000; Secure; HttpOnly; Path=/" ▿ (2 elements) - key: "nel" - value: "{\"max_age\":604800,\"report_to\":\"cf-nel\"}" ▿ (2 elements) - key: "alt-svc" - value: "h3-27=\":443\"; ma=86400, h3-28=\":443\"; ma=86400, h3-29=\":443\"; ma=86400" ▿ (2 elements) - key: "x-envoy-upstream-service-time" - value: "5" ▿ (2 elements) - key: "server" - value: "cloudflare" ▿ (2 elements) - key: "content-type" - value: "application/json"
struct Box<T> {} @_functionBuilder struct MyBuilder { static func buildBlock(_ component: Box<Never>) -> Box<Never> { component } } func take(_ c: () -> Box<Never>) {} func takeBuild(@MyBuilder _ c: () -> Box<Never>) {} take { Box() } takeBuild { Box() }
<stdin>:19:5: error: cannot convert value of type 'Box<_>' to expected argument type 'Box<Never>' Box() ^ <stdin>:1:12: note: arguments to generic parameter 'T' ('_' and 'Never') are expected to be equal struct Box<T> {} ^ <stdin>:19:5: error: generic parameter 'T' could not be inferred Box() ^ <stdin>:1:12: note: 'T' declared as parameter to type 'Box' struct Box<T> {} ^ <stdin>:19:5: note: explicitly specify the generic arguments to fix this issue Box() ^ <Any>
struct Box<T> {} @_functionBuilder struct MyBuilder { static func buildExpression(_ expression: Box<Never>) -> Box<Never> { expression } static func buildBlock(_ component: Box<Never>) -> Box<Never> { component } } func take(_ c: () -> Box<Never>) {} func takeBuild(@MyBuilder _ c: () -> Box<Never>) {} func test() { take { Box() } takeBuild { Box() } }
struct Box<T> {} @_functionBuilder struct MyBuilder { static func buildBlock(_ component: Box<Never>) -> Box<Never> { component } } func take(_ c: () -> Box<Never>) {} func takeBuild(@MyBuilder _ c: () -> Box<Never>) {} take { Box() } takeBuild { Box() }
buildExpression(_:)
が必要ですね。buildExpression(_ expression: Expression) -> Component
is used to lift the results of expression-statements into the Component internal currency type. It is optional, but when provided it allows a result builder to distinguish Expression types from Component types or to provide contextual type information for statement-expressions.<メイン>+swift5.x@gmail.com
的なGmailのエリアスアドレスでサインアップしてたけど、Swift 5.5ボット用に新規アカウントをサインアップしようとしたら、メールアドレスで弾かれた… なのでSwift 5.5ボット立ち上げは少し遅れそう。(["value": Int?(1)] as [String: String?])
<stdin>:1:21: warning: coercion from '[String : Int?]' to '[String : String?]' may fail; use 'as?' or 'as!' instead (["value": Int?(1)] as [String: String?]) ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~ <stdin>:1:21: warning: expression of type '[String : String?]' is unused (["value": Int?(1)] as [String: String?]) ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~ SIL verification failed: branch argument types do not match arguments for dest bb: std::equal(BI->getArgs().begin(), BI->getArgs().end(), BI->getDestBB()->args_begin(), [&](SILValue branchArg, SILArgument *bbArg) { return verifyBranchArgs(branchArg, bbArg); }) Verifying instruction: %31 = enum $Optional<Int>, #Optional.some!enumelt, %30 : $Int // user: %32 -> br bb3(%31 : $Optional<Int>) // id: %32 In function: // main sil [ossa] @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Word, 1 // user: %4 // function_ref _allocateUninitializedArray<A>(_:) %3 = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %4 %4 = apply %3<(String, Optional<String>)>(%2) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %5 (%5, %6) = destructure_tuple %4 : $(Array<(String, Optional<String>)>, Builtin.RawPointer) // users: %40, %7 %7 = pointer_to_address %6 : $Builtin.RawPointer to [strict] $*(String, Optional<String>) // users: %9, %8 %8 = tuple_element_addr %7 : $*(String, Optional<String>), 0 // user: %16 %9 = tuple_element_addr %7 : $*(String, Optional<String>), 1 // user: %36 %10 = string_literal utf8 "value" // user: %15 %11 = integer_literal $Builtin.Word, 5 // user: %15 %12 = integer_literal $Builtin.I
_ = ["value": Int?(1)] as [String: String?]
<stdin>:1:24: warning: coercion from '[String : Int?]' to '[String : String?]' may fail; use 'as?' or 'as!' instead _ = ["value": Int?(1)] as [String: String?] ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~ SIL verification failed: branch argument types do not match arguments for dest bb: std::equal(BI->getArgs().begin(), BI->getArgs().end(), BI->getDestBB()->args_begin(), [&](SILValue branchArg, SILArgument *bbArg) { return verifyBranchArgs(branchArg, bbArg); }) Verifying instruction: %31 = enum $Optional<Int>, #Optional.some!enumelt, %30 : $Int // user: %32 -> br bb3(%31 : $Optional<Int>) // id: %32 In function: // main sil [ossa] @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Word, 1 // user: %4 // function_ref _allocateUninitializedArray<A>(_:) %3 = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %4 %4 = apply %3<(String, Optional<String>)>(%2) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %5 (%5, %6) = destructure_tuple %4 : $(Array<(String, Optional<String>)>, Builtin.RawPointer) // users: %40, %7 %7 = pointer_to_address %6 : $Builtin.RawPointer to [strict] $*(String, Optional<String>) // users: %9, %8 %8 = tuple_element_addr %7 : $*(String, Optional<String>), 0 // user: %16 %9 = tuple_element_addr %7 : $*(String, Optional<String>), 1 // user: %36 %10 = string_literal utf8 "value" // user: %15 %11 = integer_literal $Builtin.Word, 5 // user: %15 %12 = integer_literal $Builtin.Int1, -1 // user: %15 %13 = metatype $@thin String.Type // user: %15 // function_ref String.init(_builtinStringLiteral:utf8Cod
_ = ["value": Int?(1)] as [String: String?]
<stdin>:1:24: warning: coercion from '[String : Int?]' to '[String : String?]' may fail; use 'as?' or 'as!' instead _ = ["value": Int?(1)] as [String: String?] ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~ SIL verification failed: branch argument types do not match arguments for dest bb: std::equal(BI->getArgs().begin(), BI->getArgs().end(), BI->getDestBB()->args_begin(), [&](SILValue branchArg, SILArgument *bbArg) { return verifyBranchArgs(branchArg, bbArg); }) Verifying instruction: %31 = enum $Optional<Int>, #Optional.some!enumelt, %30 : $Int // user: %32 -> br bb3(%31 : $Optional<Int>) // id: %32 In function: // main sil [ossa] @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Word, 1 // user: %4 // function_ref _allocateUninitializedArray<A>(_:) %3 = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %4 %4 = apply %3<(String, Optional<String>)>(%2) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %5 (%5, %6) = destructure_tuple %4 : $(Array<(String, Optional<String>)>, Builtin.RawPointer) // users: %38, %7 %7 = pointer_to_address %6 : $Builtin.RawPointer to [strict] $*(String, Optional<String>) // users: %9, %8 %8 = tuple_element_addr %7 : $*(String, Optional<String>), 0 // user: %16 %9 = tuple_element_addr %7 : $*(String, Optional<String>), 1 // user: %36 %10 = string_literal utf8 "value" // user: %15 %11 = integer_literal $Builtin.Word, 5 // user: %15 %12 = integer_literal $Builtin.Int1, -1 // user: %15 %13 = metatype $@thin String.Type // user: %15 // function_ref String.init(_builtinStringLiteral:utf8Cod
<stdin>:1:15: error: cannot convert value of type 'Optional<Int>' to expected dictionary value type 'String' _ = ["value": Int?(1)] as [String: String?] ^
<stdin>:1:24: warning: coercion from '[String : Int?]' to '[String : String?]' may fail; use 'as?' or 'as!' instead _ = ["value": Int?(1)] as [String: String?] ~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~ SIL verification failed: branch argument types do not match arguments for dest bb: std::equal(BI->getArgs().begin(), BI->getArgs().end(), BI->getDestBB()->args_begin(), [&](SILValue branchArg, SILArgument *bbArg) { return verifyBranchArgs(branchArg, bbArg); }) Verifying instruction: %31 = enum $Optional<Int>, #Optional.some!enumelt, %30 : $Int // user: %32 -> br bb3(%31 : $Optional<Int>) // id: %32 In function: // main sil [ossa] @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Word, 1 // user: %4 // function_ref _allocateUninitializedArray<A>(_:) %3 = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %4 %4 = apply %3<(String, Optional<String>)>(%2) : $@convention(thin) <τ_0_0> (Builtin.Word) -> (@owned Array<τ_0_0>, Builtin.RawPointer) // user: %5 (%5, %6) = destructure_tuple %4 : $(Array<(String, Optional<String>)>, Builtin.RawPointer) // users: %38, %7 %7 = pointer_to_address %6 : $Builtin.RawPointer to [strict] $*(String, Optional<String>) // users: %9, %8 %8 = tuple_element_addr %7 : $*(String, Optional<String>), 0 // user: %16 %9 = tuple_element_addr %7 : $*(String, Optional<String>), 1 // user: %36 %10 = string_literal utf8 "value" // user: %15 %11 = integer_literal $Builtin.Word, 5 // user: %15 %12 = integer_literal $Builtin.Int1, -1 // user: %15 %13 = metatype $@thin String.Type // user: %15 // function_ref String.init(_builtinStringLiteral:utf8Cod
class MyCls {} let obj: MyCls = { obj }() print(obj)
<stdin>:2:20: error: variable used within its own initial value let obj: MyCls = { obj }() ^
Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIODarwin.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOLinux.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-name main -lLibraries 1. Swift version 5.4 (swift-5.4-RELEASE) 2. While running us
enum E: Codable { case a(Int) }
<stdin>:1:6: error: type 'E' does not conform to protocol 'Decodable' enum E: Codable { ^ <stdin>:1:6: error: type 'E' does not conform to protocol 'Encodable' enum E: Codable { ^ Swift.Decodable:2:5: note: protocol requires initializer 'init(from:)' with type '(from: Decoder)' init(from decoder: Decoder) throws ^ Swift.Encodable:2:10: note: protocol requires function 'encode(to:)' with type '(Encoder) throws -> ()' func encode(to encoder: Encoder) throws ^
release/5.5
ブランチにこれがマージ済みかどうかってGitHubでどうやって調べればいいんだろうrelease/5.5
に入ってそうgit branch -a --contains c03c3b266d411481d81a86d1591aa96ab1bfbcd7 | grep release/5.5
とかですかね
--contains
というのがあるんすね。[omochi@omochi-iMacPro Sandbox]$ swift --version Apple Swift version 5.5-dev (LLVM 32757f073852da0, Swift 976d23d3f72d24b) Target: x86_64-apple-macosx11.0 [omochi@omochi-iMacPro Sandbox]$ swift main.swift Killed: 9 [omochi@omochi-iMacPro Sandbox]$ swift dyld: Library not loaded: @rpath/Python3.framework/Versions/3.8/Python3 Referenced from: /Library/Developer/Toolchains/swift-5.5-DEVELOPMENT-SNAPSHOT-2021-06-02-a.xctoolchain/System/Library/PrivateFrameworks/LLDB.framework/Versions/A/LLDB Reason: image not found Abort trap: 6
/Library/Frameworks/Python.framework
で、 Python3.framework
じゃない。Load command 27 cmd LC_RPATH cmdsize 80 path /Applications/Xcode.app/Contents/Developer/Library/Frameworks/ (offset 12)
[omochi@omochi-iMacPro Library]$ ls /Applications/Xcode12.5.app/Contents/Developer/Library/Frameworks | grep Python3 Python3.framework
Xcode.app -> Xcode12.5.app
置いたけどまだ駄目だ[omochi@omochi-iMacPro Sandbox]$ swift error: failed to launch REPL process: process exited with status -1 (attach failed (Not allowed to attach to process. Look in the console messages (Console.app), near the debugserver entries when the attached failed. The subsystem that denied the attach permission will likely have logged an informative message about why it was denied.))
import Foundation enum E: Codable { case a(Int?) } let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let json = try encoder.encode(E.a(nil)) print(String(data: json, encoding: .utf8)!)
{ "a" : { } }
import Foundation enum E: Codable { case a(Int??) } let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let json = try encoder.encode(E.a(.some(.none))) print(String(data: json, encoding: .utf8)!)
{ "a" : { "_0" : null } }
.some(.some(1))
.some(.none)
.none
のどれもが異なるJSONになるので、import Foundation enum E: Codable { case a(Int???) } let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let value: [E] = [ .a(.none), .a(.some(.none)), .a(.some(.some(.none))), .a(.some(.some(.some(1)))) ] let json = try encoder.encode(value) print(String(data: json, encoding: .utf8)!)
(edited)<stdin>:10:6: error: enum case 'a' cannot be used as an instance member .a(.none) ~^~~~~~~~ E <stdin>:11:6: error: enum case 'a' cannot be used as an instance member .a(.some(.none)) ~~~~~^~~~~~~~~~~~~~~ E <stdin>:12:6: error: enum case 'a' cannot be used as an instance member .a(.some(.some(.none))) ~~~~~^~~~~~~~~~~~~~~~~~~~~~ E
import Foundation enum E: Codable { case a(Int???) } let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let value: [E] = [ .a(.none), .a(.some(.none)), .a(.some(.some(.none))), .a(.some(.some(.some(1)))) ] let json = try encoder.encode(value) print(String(data: json, encoding: .utf8)!)
[ { "a" : { } }, { "a" : { "_0" : null } }, { "a" : { "_0" : null } }, { "a" : { "_0" : 1 } } ]
a
で残ってるんでいいのですimport Foundation enum E: Codable { case a(Int???) } let decoder = JSONDecoder() let json = """ [ { "a" : { } }, { "a" : { "_0" : null } }, { "a" : { "_0" : null } }, { "a" : { "_0" : 1 } } ] """.data(using: .utf8)! let value = try decoder.decode([E].self, from: json) dump(value)
▿ 4 elements ▿ main.E.a - a: nil ▿ main.E.a - a: nil ▿ main.E.a - a: nil ▿ main.E.a ▿ a: Optional(Optional(Optional(1))) ▿ some: Optional(Optional(1)) ▿ some: Optional(1) - some: 1
"_0" : null
はnullという値があるっていう表現になるから合ってるのか。struct A { let i: Int } struct B { let a: A? = nil } let _: [Any] = [B()].compactMap(\.a?.i)
<stdin>:2:1: error: extraneous '}' at top level } ^ <stdin>:4:10: error: cannot find type 'A' in scope let a: A? = nil ^
struct A { let i: Int } struct B { let a: A? = nil } let _: [Any] = [B()].compactMap(\.a?.i)
swift-frontend: /home/buildnode/jenkins/workspace/oss-swift-package-linux-ubuntu-16_04/swift/lib/Sema/CSApply.cpp:4968: swift::Expr *(anonymous namespace)::ExprRewriter::visitKeyPathExpr(swift::KeyPathExpr *): Assertion `leafTy->getOptionalObjectType()->isEqual( componentTy->getWithoutSpecifierType())' failed. Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -Xllvm -enable-swifttailcc-musttail-check -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include -Xcc -fmodule-map-file=/Libraries/
@propertyWrapper struct Wrapper<T> { init(wrappedValue: T) { self.wrappedValue = wrappedValue } init(projectedValue: Self) { self.wrappedValue = projectedValue.wrappedValue } var wrappedValue: T var projectedValue: Self { return self } } let useWrapper: (Wrapper<Int>) -> Void = { $$0 in print($$0) print(_$0) }
$
が使えるのか (edited)protocol P1 {} protocol P2 { associatedtype X: P1 = Int }
extension Int: P1 {}
された場合、 X: P1
が成り立つケースはあるがinternalな場合はエラーでいい気がするfunc f() { var a: Int? = 1 guard let a = a else { return } _ = a + 1 }
<stdin>:2:7: warning: variable 'a' was never mutated; consider changing to 'let' constant var a: Int? = 1 ~~~ ^ let
<stdin>:3:13: error: definition conflicts with previous value guard let a = a else { return } ^ <stdin>:2:7: note: previous definition of 'a' is here var a: Int? = 1 ^ <stdin>:4:7: error: value of optional type 'Int?' must be unwrapped to a value of type 'Int' _ = a + 1 ^ <stdin>:4:7: note: coalesce using '??' to provide a default when the optional value contains 'nil' _ = a + 1 ^ ?? <#default value#> <stdin>:4:7: note: force-unwrap using '!' to abort execution if the optional value contains 'nil' _ = a + 1 ^ !
<stdin>:2:7: warning: variable 'a' was never mutated; consider changing to 'let' constant var a: Int? = 1 ~~~ ^ let
func f() { var a = 1 var a = 1 }
<stdin>:3:7: error: invalid redeclaration of 'a' var a = 1 ^ <stdin>:2:7: note: 'a' previously declared here var a = 1 ^
<stdin>:3:7: error: definition conflicts with previous value var a = 1 ^ <stdin>:2:7: note: previous definition of 'a' is here var a = 1 ^ <stdin>:2:7: warning: initialization of variable 'a' was never used; consider replacing with assignment to '_' or removing it var a = 1 ~~~~^ _ <stdin>:3:7: warning: initialization of variable 'a' was never used; consider replacing with assignment to '_' or removing it var a = 1 ~~~~^ _
<stdin>:3:7: error: invalid redeclaration of 'a' var a = 1 ^ <stdin>:2:7: note: 'a' previously declared here var a = 1 ^
import Foundation enum Foo: String, Codable { case bar = "bar" } let data = try! JSONEncoder().encode(Foo.bar) let string = String(data: data, encoding: .utf8)! print(string)
import Foundation enum Foo: Codable { case bar } let data = try! JSONEncoder().encode(Foo.bar) let string = String(data: data, encoding: .utf8)! print(string)
{"bar":{}}
func test(_ callback: () -> Void) { let x = callback x() }
https://forums.swift.org/t/an-odd-error-escaping-closure-captures-mutating-self/50118/10 (edited)<stdin>:2:13: error: non-escaping parameter 'callback' may only be called let x = callback ^ <stdin>:1:11: note: parameter 'callback' is implicitly non-escaping func test(_ callback: () -> Void) { ^ @escaping
import CoreFoundation print(CFSwapInt16HostToBig)
import Foundation print(CFSwapInt16HostToBig)
<stdin>:2:7: error: cannot find 'CFSwapInt16HostToBig' in scope print(CFSwapInt16HostToBig) ^~~~~~~~~~~~~~~~~~~~
import Foundation enum A: Hashable { case unix(path: Swift.String) @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) case url(_: URL) @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) case srv(_: Swift.String) }
struct Test { func left() async -> String { "l" } func right() async -> String { "r" } func test() async { async let (l, r) = (left(), right()) print(await l) print(await r) } }
<stdin>:6:9: error: 'async' modifier is only valid when experimental concurrency is enabled async let (l, r) = (left(), right()) ^ <stdin>:8:15: warning: no 'async' operations occur within 'await' expression print(await l) ^ <stdin>:9:15: warning: no 'async' operations occur within 'await' expression print(await r) ^ <stdin>:6:28: error: expression is 'async' but is not marked with 'await' async let (l, r) = (left(), right()) ^~~~~~~~~~~~~~~~~ await <stdin>:6:29: note: call is 'async' async let (l, r) = (left(), right()) ^ <stdin>:6:37: note: call is 'async' async let (l, r) = (left(), right()) ^
import Foundation struct LoggedInState {} struct LoggedOutState {} let date1 = Date() let date2 = Date() enum Permission: Equatable { case freeDuring(Range<Date>) case free case subscriberOnly } print(enumTag(Permission.freeDuring(date1 ..< date2))) print(enumTag(Permission.free)) print(enumTag(Permission.subscriberOnly)) private func enumTag<Case>(_ `case`: Case) -> UInt32? { let metadataPtr = unsafeBitCast( type(of: `case`), to: UnsafeRawPointer.self ) let kind = metadataPtr.load(as: Int.self) let isEnumOrOptional = kind == 0x201 || kind == 0x202 guard isEnumOrOptional else { return nil } let vwtPtr = (metadataPtr - MemoryLayout<UnsafeRawPointer>.size) .load(as: UnsafeRawPointer.self) let vwt = vwtPtr.load(as: EnumValueWitnessTable.self) return withUnsafePointer(to: `case`) { vwt.getEnumTag($0, metadataPtr) } } private struct EnumValueWitnessTable { let f1, f2, f3, f4, f5, f6, f7, f8: UnsafeRawPointer let f9, f10: Int let f11, f12: UInt32 let getEnumTag: @convention(c) (UnsafeRawPointer, UnsafeRawPointer) -> UInt32 let f13, f14: UnsafeRawPointer }
(edited)<stdin>:14:1: warning: result of call to 'enumTag' is unused enumTag(Permission.freeDuring(date1 ..< date2)) ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <stdin>:15:1: warning: result of call to 'enumTag' is unused enumTag(Permission.free) ^ ~~~~~~~~~~~~~~~~~ <stdin>:16:1: warning: result of call to 'enumTag' is unused enumTag(Permission.subscriberOnly) ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
import Foundation struct LoggedInState {} struct LoggedOutState {} let date1 = Date() let date2 = Date() enum Permission: Equatable { case freeDuring(Range<Date>) case free case subscriberOnly } print(enumTag(Permission.freeDuring(date1 ..< date2))) print(enumTag(Permission.free)) print(enumTag(Permission.subscriberOnly)) private func enumTag<Case>(_ `case`: Case) -> UInt32? { let metadataPtr = unsafeBitCast( type(of: `case`), to: UnsafeRawPointer.self ) let kind = metadataPtr.load(as: Int.self) let isEnumOrOptional = kind == 0x201 || kind == 0x202 guard isEnumOrOptional else { return nil } let vwtPtr = (metadataPtr - MemoryLayout<UnsafeRawPointer>.size) .load(as: UnsafeRawPointer.self) let vwt = vwtPtr.load(as: EnumValueWitnessTable.self) return withUnsafePointer(to: `case`) { vwt.getEnumTag($0, metadataPtr) } } private struct EnumValueWitnessTable { let f1, f2, f3, f4, f5, f6, f7, f8: UnsafeRawPointer let f9, f10: Int let f11, f12: UInt32 let getEnumTag: @convention(c) (UnsafeRawPointer, UnsafeRawPointer) -> UInt32 let f13, f14: UnsafeRawPointer }
Optional(0) Optional(1) Optional(2)
stderr:<stdin>:14:7: warning: expression implicitly coerced from 'UInt32?' to 'Any' print(enumTag(Permission.freeDuring(date1 ..< date2))) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <stdin>:14:7: note: provide a default value to avoid this warning print(enumTag(Permission.freeDuring(date1 ..< date2))) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ?? <#default value#> <stdin>:14:7: note: force-unwrap the value to avoid this warning print(enumTag(Permission.freeDuring(date1 ..< date2))) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! <stdin>:14:7: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(enumTag(Permission.freeDuring(date1 ..< date2))) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ as Any <stdin>:15:7: warning: expression implicitly coerced from 'UInt32?' to 'Any' print(enumTag(Permission.free)) ^~~~~~~~~~~~~~~~~~~~~~~~ <stdin>:15:7: note: provide a default value to avoid this warning print(enumTag(Permission.free)) ^~~~~~~~~~~~~~~~~~~~~~~~ ?? <#default value#> <stdin>:15:7: note: force-unwrap the value to avoid this warning print(enumTag(Permission.free)) ^~~~~~~~~~~~~~~~~~~~~~~~ ! <stdin>:15:7: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(enumTag(Permission.free)) ^~~~~~~~~~~~~~~~~~~~~~~~ as Any <stdin>:16:7: warning: expression implicitly coerced from 'UInt32?' to 'Any' print(enumTag(Permission.subscriberOnly)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <stdin>:16:7: note: provide a default value to avoid this warning print(enumTag(Permission.subscriberOnly)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ?? <#defau
import Foundation struct LoggedInState {} struct LoggedOutState {} let date1 = Date() let date2 = Date() enum Permission: Equatable { case freeDuring(Range<Date>) case free case subscriberOnly } print(enumTag(Permission.freeDuring(date1 ..< date2))!) print(enumTag(Permission.free)!) print(enumTag(Permission.subscriberOnly)!) private func enumTag<Case>(_ `case`: Case) -> UInt32? { let metadataPtr = unsafeBitCast( type(of: `case`), to: UnsafeRawPointer.self ) let kind = metadataPtr.load(as: Int.self) let isEnumOrOptional = kind == 0x201 || kind == 0x202 guard isEnumOrOptional else { return nil } let vwtPtr = (metadataPtr - MemoryLayout<UnsafeRawPointer>.size) .load(as: UnsafeRawPointer.self) let vwt = vwtPtr.load(as: EnumValueWitnessTable.self) return withUnsafePointer(to: `case`) { vwt.getEnumTag($0, metadataPtr) } } private struct EnumValueWitnessTable { let f1, f2, f3, f4, f5, f6, f7, f8: UnsafeRawPointer let f9, f10: Int let f11, f12: UInt32 let getEnumTag: @convention(c) (UnsafeRawPointer, UnsafeRawPointer) -> UInt32 let f13, f14: UnsafeRawPointer }
@propertyWrapper struct Wrapper { var wrappedValue: Int? init(wrappedValue: Int?) { self.wrappedValue = wrappedValue } } class Test { @Wrapper var foo: Int? init() { self.foo = foo } }
print("スウィフト".lowercased())
import Foundation let numberFormatter: NumberFormatter = { let f = NumberFormatter() f.numberStyle = .decimal f.usesGroupingSeparator = true return f }() print(numberFormatter.string(from: .init(value: 1000)))
(edited)<stdin>:1:22: error: cannot find type 'NumberFormatter' in scope let numberFormatter: NumberFormatter = { ^~~~~~~~~~~~~~~ <stdin>:8:37: error: cannot infer contextual base in reference to member 'init' print(numberFormatter.string(from: .init(value: 1000))) ~^~~~
import Foundation import CoreFoundation let numberFormatter: NumberFormatter = { let f = NumberFormatter() f.numberStyle = .decimal f.usesGroupingSeparator = true return f }() print(numberFormatter.string(from: .init(value: 1000)))
(edited)<stdin>:3:22: error: cannot find type 'NumberFormatter' in scope let numberFormatter: NumberFormatter = { ^~~~~~~~~~~~~~~ <stdin>:10:37: error: cannot infer contextual base in reference to member 'init' print(numberFormatter.string(from: .init(value: 1000))) ~^~~~
import Foundation import CoreFoundation let numberFormatter: NumberFormatter = { let f = NumberFormatter() f.numberStyle = .decimal f.usesGroupingSeparator = true return f }() print(numberFormatter.string(from: .init(value: 1000)))
Optional("1,000")
stderr:<stdin>:11:7: warning: expression implicitly coerced from 'String?' to 'Any' print(numberFormatter.string(from: .init(value: 1000))) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <stdin>:11:23: note: provide a default value to avoid this warning print(numberFormatter.string(from: .init(value: 1000))) ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ?? <#default value#> <stdin>:11:23: note: force-unwrap the value to avoid this warning print(numberFormatter.string(from: .init(value: 1000))) ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ! <stdin>:11:23: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(numberFormatter.string(from: .init(value: 1000))) ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ as Any
swift -
への標準入力として渡してます。 (edited)import Foundation import CoreFoundation let numberFormatter: NumberFormatter = { let f = NumberFormatter() f.numberStyle = .decimal f.usesGroupingSeparator = true return f }() print(numberFormatter.string(from: .init(value: 1000)))
(edited)<stdin>:3:22: error: cannot find type 'NumberFormatter' in scope let numberFormatter: NumberFormatter = { ^~~~~~~~~~~~~~~ <stdin>:10:37: error: cannot infer contextual base in reference to member 'init' print(numberFormatter.string(from: .init(value: 1000))) ~^~~~
protocol P0 {} extension P0 { func openExistential() -> some P0 { return self } } func use<T: P0>(_: T) {} func make() -> P0 { fatalError() } let p0 = make() _ = p0.openExistential()
<stdin>:13:5: error: member 'openExistential' cannot be used on value of protocol type 'P0'; use a generic constraint instead _ = p0.openExistential() ^~ ~~~~~~~~~~~~~~~
<stdin>:13:5: error: member 'openExistential' cannot be used on value of protocol type 'P0'; use a generic constraint instead _ = p0.openExistential() ^~ ~~~~~~~~~~~~~~~
Fatal error: file main/<stdin>, line 10 Current stack trace: 0 libswiftCore.so 0x00007fc7d0e80df0 swift_reportError + 50 1 libswiftCore.so 0x00007fc7d0ef4160 _swift_stdlib_reportFatalErrorInFile + 115 2 libswiftCore.so 0x00007fc7d0bd9eb5 <unavailable> + 1400501 3 libswiftCore.so 0x00007fc7d0bd9af7 <unavailable> + 1399543 4 libswiftCore.so 0x00007fc7d0bda0e2 <unavailable> + 1401058 5 libswiftCore.so 0x00007fc7d0bd8530 _assertionFailure(_:_:file:line:flags:) + 517 8 swift 0x00000000005b4501 <unavailable> + 1787137 9 swift 0x00000000005a1d04 <unavailable> + 1711364 10 swift 0x0000000000587e88 <unavailable> + 1605256 11 swift 0x000000000057b322 <unavailable> + 1553186 12 swift 0x00000000005780ef <unavailable> + 1540335 13 swift 0x0000000000501c2c <unavailable> + 1055788 14 libc.so.6 0x00007fc7d2f4f740 __libc_start_main + 240 15 swift 0x00000000005017a9 <unavailable> + 1054633 Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/inc
struct Hoge { var hoge, fuga: Int } print(Hoge(hoge: 1, fuga: 2))
Hoge(hoge: 1, fuga: 2)
import Foundation func f(q: URLRequest) {}
<stdin>:2:11: error: cannot find type 'URLRequest' in scope func f(q: URLRequest) {} ^~~~~~~~~~
import Foundation func f(q: URLRequest) {}
<stdin>:2:11: error: cannot find type 'URLRequest' in scope func f(q: URLRequest) {} ^~~~~~~~~~
<stdin>:2:11: error: use of undeclared type 'URLRequest' func f(q: URLRequest) {} ^~~~~~~~~~
<stdin>:2:11: error: use of undeclared type 'URLRequest' func f(q: URLRequest) {} ^~~~~~~~~~
import FoundationNetworking func f(q: URLRequest) {}
#if canImport(FoundationNetworking) import FoundationNetworking #endif
をいたるところに貼り付けます…import Foundation func foo() { struct Item<Content: Identifiable>: Equatable { let content: Content static func == (lhs: Item<Content>, rhs: Item<Content>) -> Bool { return lhs.content.id == rhs.content.id } } }
<stdin>:4:12: error: type 'Item<Content>' does not conform to protocol 'Equatable' struct Item<Content: Identifiable>: Equatable { ^ <stdin>:5:13: note: stored property type 'Content' does not conform to protocol 'Equatable', preventing synthesized conformance of 'Item<Content>' to 'Equatable' let content: Content ^ Swift.==:1:24: note: candidate would match if 'Item<Content>' conformed to 'RawRepresentable' @inlinable public func == <T>(lhs: T, rhs: T) -> Bool where T : RawRepresentable, T.RawValue : Equatable ^ Swift.FloatingPoint:2:24: note: candidate would match if 'Item<Content>' conformed to 'FloatingPoint' public static func == (lhs: Self, rhs: Self) -> Bool ^ Swift.BinaryInteger:2:24: note: candidate would match if 'Item<Content>' conformed to 'BinaryInteger' public static func == <Other>(lhs: Self, rhs: Other) -> Bool where Other : BinaryInteger ^ Swift._Pointer:2:24: note: candidate would match if 'Item<Content>' conformed to '_Pointer' public static func == (lhs: Self, rhs: Self) -> Bool ^ Swift.Strideable:3:35: note: candidate would match if 'Item<Content>' conformed to 'Strideable' @inlinable public static func == (x: Self, y: Self) -> Bool ^ Swift.StringProtocol:2:35: note: candidate would match if 'Item<Content>' conformed to 'StringProtocol' @inlinable public static func == <RHS>(lhs: Self, rhs: RHS) -> Bool where RHS : StringProtocol ^ Swift.SIMD:4:24: note: candidate would match if 'Item<Content>' conformed to 'SIMD' public static func == (lhs: Self, rhs: Self) -> Bool ^ Foundation.__BridgedNSError:2:24: note: candidate would match if 'Item<Content>' conformed to '__BridgedNSError' public static func == (lhs: Self, rhs: Self) -> Bool ^ Foundation._Bri
<stdin>:4:12: error: type 'Item<Content>' does not conform to protocol 'Equatable' struct Item<Content: Identifiable>: Equatable { ^ Swift.==:1:24: note: candidate would match if 'Item<Content>' conformed to 'RawRepresentable' @inlinable public func == <T>(lhs: T, rhs: T) -> Bool where T : RawRepresentable, T.RawValue : Equatable ^ Swift.FloatingPoint:2:24: note: candidate would match if 'Item<Content>' conformed to 'FloatingPoint' public static func == (lhs: Self, rhs: Self) -> Bool ^ Swift.BinaryInteger:2:24: note: candidate would match if 'Item<Content>' conformed to 'BinaryInteger' public static func == <Other>(lhs: Self, rhs: Other) -> Bool where Other : BinaryInteger ^ Swift._Pointer:2:24: note: candidate would match if 'Item<Content>' conformed to '_Pointer' public static func == (lhs: Self, rhs: Self) -> Bool ^ Swift.Strideable:3:35: note: candidate would match if 'Item<Content>' conformed to 'Strideable' @inlinable public static func == (x: Self, y: Self) -> Bool ^ Swift.StringProtocol:2:35: note: candidate would match if 'Item<Content>' conformed to 'StringProtocol' @inlinable public static func == <RHS>(lhs: Self, rhs: RHS) -> Bool where RHS : StringProtocol ^ Swift.SIMD:4:24: note: candidate would match if 'Item<Content>' conformed to 'SIMD' public static func == (lhs: Self, rhs: Self) -> Bool ^ Foundation.__BridgedNSError:2:24: note: candidate would match if 'Item<Content>' conformed to '__BridgedNSError' public static func == (lhs: Self, rhs: Self) -> Bool ^ Foundation._BridgedStoredNSError:2:24: note: candidate would match if 'Item<Content>' conformed to '_BridgedStoredNSError' public static func == (lhs: Self, rhs: Self) -> Bool ^ Swift.Equatable
@propertyWrapper struct Wrap { var wrappedValue: Int = 1 } struct S { @Wrap var val }
(edited)<stdin>:6:13: error: type annotation missing in pattern @Wrap var val ^
var
宣言の型アノテーション省略できる@Namespace
で初めて見たとき、なんじゃこりゃってなった。 @Namespace private var foo
(edited)func hoge() async {} Task { await hoge() }
do { defer { print(a) } // ←まだaが宣言されてないよ…? let a = 0 }
<stdin>:3:9: warning: initialization of immutable value 'a' was never used; consider replacing with assignment to '_' or removing it let a = 0 ~~~~^ _ <stdin>:2:19: error: cannot capture 'a' before it is declared defer { print(a) } // ←まだaが宣言されてないよ…? <stdin>:3:9: note: 'a' declared here let a = 0 ^
do { defer { print(a) } // ←まだaが宣言されてないよ…? let a = 0 }
<stdin>:3:9: warning: initialization of immutable value 'a' was never used; consider replacing with assignment to '_' or removing it let a = 0 ~~~~^ _ <stdin>:2:19: error: cannot capture 'a' before it is declared defer { print(a) } // ←まだaが宣言されてないよ…? <stdin>:3:9: note: 'a' declared here let a = 0 ^
do { defer { print(a) } // ←まだaが宣言されてないよ…? let a = 0 }
0
stderr:<stdin>:3:9: warning: initialization of immutable value 'a' was never used; consider replacing with assignment to '_' or removing it let a = 0 ~~~~^ _
do { defer { print(a) } // ←まだaが宣言されてないよ…? let a = 0 }
do { defer { print(a) } // ←まだaが宣言されてないよ…? let a = 0 }
func foo() { defer { print(a) } // ←まだaが宣言されてないよ…? let a: Int? = 42 guard var a = a else { return } a = 20 } foo()
Optional(42)
stderr:<stdin>:2:19: warning: expression implicitly coerced from 'Int?' to 'Any' defer { print(a) } // ←まだaが宣言されてないよ…? <stdin>:2:19: note: provide a default value to avoid this warning defer { print(a) } // ←まだaが宣言されてないよ…? <stdin>:2:19: note: force-unwrap the value to avoid this warning defer { print(a) } // ←まだaが宣言されてないよ…? <stdin>:2:19: note: explicitly cast to 'Any' with 'as Any' to silence this warning defer { print(a) } // ←まだaが宣言されてないよ…? <stdin>:4:15: warning: variable 'a' was written to, but never read guard var a = a else { return } ^
func foo() { defer { print(a as Any) } // ←まだaが宣言されてないよ…? let a: Int? = 42 guard var a = a else { return } a = 20 } foo()
Optional(42)
stderr:<stdin>:4:15: warning: variable 'a' was written to, but never read guard var a = a else { return } ^
func foo() { defer { print(a as Any) } // ←まだaが宣言されてないよ…? var a: Int? = 42 guard let b = a else { return } a = b + 1 } foo()
Optional(42)
func foo() { defer { print(a) } // ←まだaが宣言されてないよ…? var a: Int = 42 a += 1 } foo()
func foo() { defer { // まだaが宣言されてないよ…? a += 2 print(a) } var a: Int = 42 a += 1 } foo()
defer
での利用ができてしまっていること自体がバグなのかな?昔の挙動が正しかった?class C { var a: Int = 1 func f() { let _ = (0...2).map { _ -> Int in _ = a return 1 } let a = 2 } }
<stdin>:4:25: error: closure captures 'a' before it is declared let _ = (0...2).map { _ -> Int in ^ <stdin>:8:9: note: captured value declared here let a = 2 ^ <stdin>:5:11: note: captured here _ = a ^
a
もあるので使えるはず) (edited)class A { var i: Int init(_ i: Int) { self.i = i } } func f() -> A { defer { a.i = 10 } let a = A(3) return a } print(f())
Begin Error in Function: '$s4main1fAA1ACyF' Found outside of lifetime use?! Value: %6 = apply %5(%4, %0) : $@convention(method) (Int, @thick A.Type) -> @owned A // users: %12, %11, %8, %7 Consuming User: destroy_value %6 : $A // id: %11 Non Consuming User: %12 = begin_borrow %6 : $A // users: %15, %14 Block: bb0 End Error in Function: '$s4main1fAA1ACyF' Found ownership error?! triggering standard assertion failure routine UNREACHABLE executed at /home/buildnode/jenkins/workspace/oss-swift-5.4-package-linux-ubuntu-16_04/swift/lib/SIL/Verifier/LinearLifetimeCheckerPrivate.h:211! Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -Xc
func foo() { defer { // まだaが宣言されてないよ…? a += 2 print(a) } var a: Int = 42 a += 1 } foo()
<stdin>:4:9: error: use of local variable 'a' before its declaration a += 2 ^ <stdin>:7:9: note: 'a' declared here var a: Int = 42 ^ <stdin>:5:15: error: use of local variable 'a' before its declaration print(a) ^ <stdin>:7:9: note: 'a' declared here var a: Int = 42 ^
struct Test { @available(iOS 16, *) var a: Int { 42 } func test() { if #available(macOS 11, *) { print(a) } } } Test().test()
struct Test { @available(iOS 16, *) var a: Int { 42 } func test() { print(a) } } Test().test()
protocol P { associatedtype T } protocol Q: P { typealias T = Int } func f(q: Q) {}
<stdin>:6:13: warning: typealias overriding associated type 'T' from protocol 'P' is better expressed as same-type constraint on the protocol typealias T = Int ~~~~~~~~~~^~~~~~~ <stdin>:2:18: note: 'T' declared here associatedtype T ^ <stdin>:9:11: error: protocol 'Q' can only be used as a generic constraint because it has Self or associated type requirements func f(q: Q) {} ^
<stdin>:6:13: warning: typealias overriding associated type 'T' from protocol 'P' is better expressed as same-type constraint on the protocol typealias T = Int ~~~~~~~~~~^~~~~~~ <stdin>:2:18: note: 'T' declared here associatedtype T ^ <stdin>:9:11: error: protocol 'Q' can only be used as a generic constraint because it has Self or associated type requirements func f(q: Q) {} ^
<stdin>:6:13: warning: typealias overriding associated type 'T' from protocol 'P' is better expressed as same-type constraint on the protocol typealias T = Int ~~~~~~~~~~^~~~~~~ <stdin>:2:18: note: 'T' declared here associatedtype T ^ <stdin>:9:11: error: protocol 'Q' can only be used as a generic constraint because it has Self or associated type requirements func f(q: Q) {} ^
protocol P { associatedtype T } protocol Q: P where T = Int { } func f(q: Q) {}
<stdin>:5:23: error: use '==' for same-type requirements rather than '=' protocol Q: P where T = Int { ^ == <stdin>:8:11: error: protocol 'Q' can only be used as a generic constraint because it has Self or associated type requirements func f(q: Q) {} ^
protocol P { associatedtype T } protocol Q: P where T == Int { } func f(q: Q) {}
<stdin>:8:11: error: protocol 'Q' can only be used as a generic constraint because it has Self or associated type requirements func f(q: Q) {} ^
struct Foo { var x: Int func test() { let x = x + 1 print(x) } }
struct Foo { var x: Int func test() { let x = x + 1 print(x) } }
<stdin>:5:17: error: variable used within its own initial value let x = x + 1 ^
protocol P {} struct A { var p: some P = A() }
<stdin>:3:21: error: return type of property 'p' requires that 'A' conform to 'P' var p: some P = A() ^ <stdin>:3:12: note: opaque return type declared here var p: some P = A() ^~~~~~ <stdin>:3:9: error: property declares an opaque return type, but cannot infer the underlying type from its initializer expression var p: some P = A() ^
protocol P {} struct A: P { var p: some P = A() }
Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIODarwin.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOLinux.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-name main -lLib
extension String { func foo() {} } "".foo()
extension String { private func foo() {} } "".foo()
(edited)<stdin>:5:4: error: 'foo' is inaccessible due to 'private' protection level "".foo() ^~~ <stdin>:2:16: note: 'foo()' declared here private func foo() {} ^
final class ViewController { func viewDidLoad() { prepareViews() } } extension ViewController { private func prepareViews() { prepareAView() prepareBView() prepareCView() } /*extension*/private func prepareAView() {} /*extension*/private func prepareBView() {} /*extension*/private func prepareCView() {} }
final class ViewController { func viewDidLoad() { prepareViews() // ↓これはできてほしくない prepareAView() } } extension ViewController { private func prepareViews() { prepareAView() prepareBView() prepareCView() } /*extension*/private func prepareAView() {} /*extension*/private func prepareBView() {} /*extension*/private func prepareCView() {} }
print(Bundle.main.bundleURL)
<stdin>:1:7: error: cannot find 'Bundle' in scope print(Bundle.main.bundleURL) ^~~~~~
import Foundation print(Bundle.main.bundleURL)
file:///usr/bin/
import Foundation enum Key: String, Codable { case a, b } let data = [Key.a: "A", Key.b: "B"] let json = try String(data: JSONEncoder().encode(data), encoding: .utf8)! print(json)
["b","B","a","A"]
String
のときだけ 辞書になるprotocol P { func foo() } struct S: P { func foo() {} } func nopConsumeP(_ p: P) {} func useAny(_ x: Any) { if let p = x as? P { nopConsumeP(p) } else { print("キャスト失敗!") } } func useOptionalT(_ x: T?) { useAny(x as Any) } useOptionalT(T())
<stdin>:19:24: error: use of undeclared type 'T' func useOptionalT(_ x: T?) { ^ <stdin>:23:14: error: use of unresolved identifier 'T' useOptionalT(T()) ^
<stdin>:19:24: error: cannot find type 'T' in scope func useOptionalT(_ x: T?) { ^ <stdin>:23:14: error: cannot find 'T' in scope useOptionalT(T()) ^
<stdin>:19:24: error: cannot find type 'T' in scope func useOptionalT(_ x: T?) { ^ <stdin>:23:14: error: cannot find 'T' in scope useOptionalT(T()) ^
<stdin>:19:24: error: cannot find type 'T' in scope func useOptionalT(_ x: T?) { ^ <stdin>:23:14: error: cannot find 'T' in scope useOptionalT(T()) ^
protocol P { func foo() } struct S: P { func foo() {} } func nopConsumeP(_ p: P) {} func useAny(_ x: Any) { if let p = x as? P { nopConsumeP(p) } else { print("キャスト失敗!") } } func useOptionalS(_ x: S?) { useAny(x as Any) } useOptionalS(S())
platforms: [ .macOS(.v10_15) ],
ってかいた以外のことはしてない@available(macOS 12, *) public struct Crayon {} public enum Pen { case pencil @available(macOS 12, *) case crayon(Crayon) }
print("hello")
(edited)print("hello")
(edited)swift -version -
Swift version 5.5-dev (LLVM 5ac425fe8b983a2, Swift e6826e3cbcf5c16) Target: x86_64-unknown-linux-gnu
(edited)print("hello")
(edited)swift -
hello
-O
と-Onone
の比較とか。)@swift55
だけが新しいコードで動いてて、それ以外は以前のままです。@swift55
をしばらく使ってみて、問題なさそうなら他も更新していきます。func main() { let a: Int? = 42 guard let a = a else { return } print(a) } main()
<stdin>:3:15: error: definition conflicts with previous value guard let a = a else { return } ^ <stdin>:2:9: note: previous definition of 'a' is here let a: Int? = 42 ^ <stdin>:4:11: warning: expression implicitly coerced from 'Int?' to 'Any' print(a) ^ <stdin>:4:11: note: provide a default value to avoid this warning print(a) ^ ?? <#default value#> <stdin>:4:11: note: force-unwrap the value to avoid this warning print(a) ^ ! <stdin>:4:11: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(a) ^ as Any <stdin>:3:15: warning: value 'a' was defined but never used; consider replacing with boolean test guard let a = a else { return } ~~~~^~~~ != nil
let aOrNone
にしてたから助かるなーfunc main() { guard let _ = Int?.none else { preconditionFailure("preconditionFailure!") } print("hello") } main()
main/<stdin>:4: Fatal error: preconditionFailure! Current stack trace: 0 libswiftCore.so 0x00007f1c29b157b0 swift_reportError + 50 1 libswiftCore.so 0x00007f1c29b89d30 _swift_stdlib_reportFatalErrorInFile + 112 2 libswiftCore.so 0x00007f1c29873320 _assertionFailure(_:_:file:line:flags:) + 1329 5 swift-frontend 0x00000000005a07e5 <unavailable> + 1705957 6 swift-frontend 0x000000000056a1de <unavailable> + 1483230 7 swift-frontend 0x000000000053a902 <unavailable> + 1288450 8 swift-frontend 0x0000000000539f6c <unavailable> + 1285996 9 swift-frontend 0x000000000052e445 <unavailable> + 1238085 10 swift-frontend 0x00000000004b8d98 <unavailable> + 757144 11 libc.so.6 0x00007f1c2bbc4740 __libc_start_main + 240 12 swift-frontend 0x00000000004b8869 <unavailable> + 755817 Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/includ
func main() { guard let _ = Int?.none else { preconditionFailure("preconditionFailure!") } print("hello") } main()
Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -Ounchecked -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIODarwin.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOLinux.build/module.modulemap -Xcc -I -Xcc /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-name main -lLibraries 1. Swift version 5.4.2 (swift-5.4.2-RELEASE) 2.
precondition
は消えるけど preconditionFailure
は消えなかったはず。main/<stdin>:4: Fatal error: preconditionFailure!
という出力があります。-Ounchecked
で precondition
は消えるけど preconditionFailure
は消えない○×表見た気がするんだけどなぁ。どこだろう・・・。-Onone
と -O
でも変わったはずだからそういうもので、クラッシュする部分は残ってるとか?guard
なので-Ounchecked
builds, the optimizer may assume that this function is never called. precondition
と違って preconditionFailure
は分岐して使うことが前提となってるし、そうかも。print([1, "hoge"].description)
print(x) var x = 32
(edited)print(x) var x = 32
(edited)swift -O -
32
(edited)print(x) var x = 32
(edited)swift -Onone -
0
(edited)@swift55
をしばらく使ってみて、問題なさそうなら他も更新していきます。 @swift-x.x.x ```swift
という感じでメンションと同じ行にコードを書き始めると今まではいけてたのですが新しいものではエラーになったようです。元々が仕様じゃなかったという感じでしょうか?Swift version 5.5 (swift-5.5-RELEASE) Target: x86_64-unknown-linux-gnu
var count = 0 loop: do { print(count) count += 1 if count >= 10 { break loop } continue loop }
var count = 0 loop: do { print(count) count += 1 if count >= 10 { break loop } continue loop }
0 1 2 3 4 5 6 7 8 9
public protocol BaseP { func foo() } public protocol DerivedP: BaseP { func foo() } public struct Concrete: DerivedP { public func foo() {} }
(edited)sil_stage canonical import Builtin import Swift import SwiftShims public protocol BaseP { func foo() } public protocol DerivedP : BaseP { func foo() } public struct Concrete : DerivedP { public func foo() init() } // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int32, 0 // user: %3 %3 = struct $Int32 (%2 : $Builtin.Int32) // user: %4 return %3 : $Int32 // id: %4 } // end sil function 'main' // Concrete.foo() sil @$S4main8ConcreteV3fooyyF : $@convention(method) (Concrete) -> () { // %0 // user: %1 bb0(%0 : $Concrete): debug_value %0 : $Concrete, let, name "self", argno 1 // id: %1 %2 = tuple () // user: %3 return %2 : $() // id: %3 } // end sil function '$S4main8ConcreteV3fooyyF' // protocol witness for DerivedP.foo() in conformance Concrete sil shared [transparent] [serialized] [thunk] @$S4main8ConcreteVAA8DerivedPA2aDP3fooyyFTW : $@convention(witness_method: DerivedP) (@in_guaranteed Concrete) -> () { // %0 // user: %1 bb0(%0 : $*Concrete): %1 = load %0 : $*Concrete // user: %3 // function_ref Concrete.foo() %2 = function_ref @$S4main8ConcreteV3fooyyF : $@convention(method) (Concrete) -> () // user: %3 %3 = apply %2(%1) : $@convention(method) (Concrete) -> () %4 = tuple () // user: %5 return %4 : $() // id: %5 } // end sil function '$S4main8ConcreteVAA8DerivedPA2aDP3fooyyFTW' // protocol witness for BaseP.foo() in conformance Concrete sil shared [transparent] [serialized] [thunk] @$S4main8ConcreteVAA5BasePA2aDP3fooyyFTW : $@convention(witness_method: BaseP) (@
actor State { var value = 0 func inc() -> Int { defer { value += 1 } return value } } Task { let state = State() let stream = AsyncStream<Int> { let v = await state.inc() print("produce", v) return v } onCancel: { @Sendable in print("cancel") } var count = 0 for await aa in stream { count += 1 if count > 10 { break } print("for", aa) await Task.sleep(1 * 1000 * 1000 * 1000) } }
actor State { var value = 0 func inc() -> Int { defer { value += 1 } return value } } Task { let state = State() let stream = AsyncStream<Int> { let v = await state.inc() print("produce", v) return v } onCancel: { @Sendable in print("cancel") } var count = 0 for await aa in stream { count += 1 if count > 10 { break } print("for", aa) await Task.sleep(1 * 1000 * 1000 * 1000) } }
produce 0 for 0
Swift version 5.2.5 (swift-5.2.5-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.5-dev (LLVM 87f91d38709ee59, Swift 5e0d32b7a898616) Target: x86_64-unknown-linux-gnu
Swift version 5.1.5 (swift-5.1.5-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.0.3 (swift-5.0.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.2.4 (swift-4.2.4-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.4.3 (swift-5.4.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.1.3 (swift-4.1.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.3.3 (swift-5.3.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.6-dev (LLVM 063fb68c1307e0b, Swift 14eefd1162036b8) Target: x86_64-unknown-linux-gnu
import Foundation print(try! String(contentsOf: URL(fileURLWithPath: "/proc/3/environ")))
(edited)import Foundation print(try! String(contentsOf: URL(fileURLWithPath: "/proc/3/environ")))
(edited)PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binDENO_TLS_CA_STORE=system
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binDENO_TLS_CA_STORE=system
import Foundation print(try! String(contentsOf: URL(fileURLWithPath: "/proc/3/cmdline")))
import Foundation print(try! String(contentsOf: URL(fileURLWithPath: "/proc/3/cmdline")))
denorun--allow-env=PATH--allow-net--allow-run=/usr/bin/env--quiet-
exec env -i
で環境変数を消して、sh
プロセスをdeno
プロセスへ置き換える形にしてる。 exec env -i PATH=${PATH} DENO_TLS_CA_STORE=system deno run ...
(edited)kill
するとか)もあるだろうけど、Herokuのコンテナを再起動すれば直る様なものは対策しないと思う。<name>+...@gmail.com
形式のエリアスを使って、Herokuのアカウントをボット毎に作ってきました。 (edited)protocol P { var value: Int? { get } } struct S: P { let value: Int = 42 }
protocol P { var value: Int? { get } } struct S: P { let value: Int = 42 }
<stdin>:5:8: error: type 'S' does not conform to protocol 'P' struct S: P { ^ <stdin>:6:9: note: candidate has non-matching type 'Int' let value: Int = 42 ^ <stdin>:2:9: note: protocol requires property 'value' with type 'Int?'; do you want to add a stub? var value: Int? { get } ^
protocol P { var value: Int? { get } } struct S: P { let value: Int = 42 }
<stdin>:5:8: error: type 'S' does not conform to protocol 'P' struct S: P { ^ <stdin>:6:9: note: candidate has non-matching type 'Int' let value: Int = 42 ^ <stdin>:2:9: note: protocol requires property 'value' with type 'Int?'; do you want to add a stub? var value: Int? { get } ^
protocol P { var value: Int? { get } } struct S: P { let value: Int = 42 }
<stdin>:5:8: error: type 'S' does not conform to protocol 'P' struct S: P { ^ <stdin>:6:9: note: candidate has non-matching type 'Int' let value: Int = 42 ^ <stdin>:2:9: note: protocol requires property 'value' with type 'Int?'; do you want to add a stub? var value: Int? { get } ^
protocol P { var value: Int? { get } } struct S: P { let value: Int = 42 }
<stdin>:5:8: error: type 'S' does not conform to protocol 'P' struct S: P { ^ <stdin>:6:9: note: candidate has non-matching type 'Int' let value: Int = 42 ^ <stdin>:2:9: note: protocol requires property 'value' with type 'Int?'; do you want to add a stub? var value: Int? { get } ^
protocol P { var value: Int? { get } } struct S: P { let value: Int = 42 }
<stdin>:5:8: error: type 'S' does not conform to protocol 'P' struct S: P { ^ <stdin>:6:9: note: candidate has non-matching type 'Int' let value: Int = 42 ^ <stdin>:2:9: note: protocol requires property 'value' with type 'Int?'; do you want to add a stub? var value: Int? { get } ^
class C { func foo() -> Int? { nil } } class SC: C { override func foo() -> Int { 42 } }
class C { func foo() -> Int? { nil } } class SC: C { override func foo() -> Int { 42 } }
protocol P { func foo() -> Int? } struct S: P { func foo() -> Int { 42 } }
protocol P { func foo() -> Int? } struct S: P { func foo() -> Int { 42 } }
<stdin>:5:8: error: type 'S' does not conform to protocol 'P' struct S: P { ^ <stdin>:6:10: note: candidate has non-matching type '() -> Int' func foo() -> Int { 42 } ^ <stdin>:2:10: note: protocol requires function 'foo()' with type '() -> Int?'; do you want to add a stub? func foo() -> Int? ^
{ get }
なので readonly だし、 func
の戻り値でもダメみたいですね。class Animal {} class Cat: Animal {} protocol P { func animal() -> Animal } struct S { func animal() -> Cat { Cat() } }
class Animal {} class Cat: Animal {} protocol P { func animal() -> Animal } struct S { func animal() -> Cat { Cat() } }
Foo | Nil
と Either<Foo, Nil>
を混ぜて扱うこと自体に無理がある・・・。 Codable
と JSON の Foo??
とかも。色んなところで歪みが出るのは避けられなくて、できるだけ普段目に触れないところで出すようにしてるけど、普段目に見えないからこそ不意をつかれた感じになる。Optional
に代入する度に .some
を書くべきなのか)とかを考えると仕方ないよなぁ。仮に全部 Foo | Nil
に寄せると IteratorProtocol
の next
が( Element
が Optional
のときに)表現できないとかそれはそれで問題があって、とはいえ Foo | Nil
と Either<Foo, Nil>
を適切に使い分けるのもハードルが高いし、どれを取っても一長一短。なので、 Swift は理論的なきれいさよりも実用上の使いやすさをとって、その分生じる歪みをできるだけ目立たないところで消化するという選択なんだろうなぁ。import Foundation @objc protocol P { func foo() -> NSObject? } class S: NSObject, P { func foo() -> NSObject { self } }
(edited)import Foundation @objc protocol P { func foo() -> NSObject? } class S: NSObject, P { func foo() -> NSObject { self } }
(edited)<stdin>:2:2: error: Objective-C interoperability is disabled @objc protocol P { ~^~~~~ <stdin>:6:7: error: type 'S' does not conform to protocol 'P' class S: NSObject, P { ^ <stdin>:7:10: note: candidate has non-matching type '() -> NSObject' func foo() -> NSObject { self } ^ <stdin>:3:10: note: protocol requires function 'foo()' with type '() -> NSObject?'; do you want to add a stub? func foo() -> NSObject? ^
(edited)func trans(_ f: (Int) -> Int?) { _ = f(0) } func main() { func f(a: Int?) -> Int { a ?? 0 } // (Int?) -> Int is (Int) -> Int? trans(f) }
(edited)protocol P { func f(_ v: Int) -> Int? } class C: P { func f(_ v: Int?) -> Int? { 1 } func f(_ v: Int) -> Int { 2 } }
こういうの同じレベルになりませんか?@_implements
はあるか。@resultBuilder enum MyBuilder { static func buildBlock<C>(_ c: C) -> C { c } static func buildBlock<C>(_ c: C) -> Int { 1 } } func f(@MyBuilder content: () -> Int) { print(content()) } f { "" }
@resultBuilder enum MyBuilder { static func buildBlock<C>(_ c: C) -> C { c } static func buildBlock<C>(_ c: C) -> Int { 1 } } func f(@MyBuilder content: () -> Int) { print(content()) } f { "" }
1
@resultBuilder enum MyBuilder { static func buildBlock<C>(_ c: C) -> C { c } @_disfavoredOverload static func buildBlock<C>(_ c: C) -> Int { 1 } } func f(@MyBuilder content: () -> Int) { print(content()) } f { "" }
@resultBuilder enum MyBuilder { static func buildBlock<C>(_ c: C) -> C { c } @_disfavoredOverload static func buildBlock<C>(_ c: C) -> Int { 1 } } func f(@MyBuilder content: () -> Int) { print(content()) } f { "" }
<stdin>:17:5: error: cannot convert value of type 'String' to closure result type 'Int' "" ^~
_disfavoredOverload
をつけることで可能性がまるごと消えてしまったimport UIKit
import UIKit
<stdin>:1:8: error: no such module 'UIKit' import UIKit ^
@propertyWrapper struct Wrap { var wrappedValue: Int var projectedValue: Int = 0 } actor A { nonisolated var a: Int = 0 @Wrap nonisolated var i: Int = 0 nonisolated var u: Wrap = .init(wrappedValue: 0) nonisolated var e: Int { $i } nonisolated var o: Wrap { _i } }
(edited)@propertyWrapper struct Wrap { var wrappedValue: Int var projectedValue: Int = 0 } actor A { nonisolated var a: Int = 0 @Wrap nonisolated var i: Int = 0 nonisolated var u: Wrap = .init(wrappedValue: 0) nonisolated var e: Int { $i } nonisolated var o: Wrap { _i } }
(edited)<stdin>:6:3: error: nonisolated' can not be applied to stored properties nonisolated var a: Int = 0 ^~~~~~~~~~~~ <stdin>:8:3: error: nonisolated' can not be applied to stored properties nonisolated var u: Wrap = .init(wrappedValue: 0) ^~~~~~~~~~~~ <stdin>:9:28: error: actor-isolated property '$i' can not be referenced from a non-isolated context nonisolated var e: Int { $i } ^ <stdin>:7:25: note: property declared here @Wrap nonisolated var i: Int = 0 ^ <stdin>:10:29: error: actor-isolated property '_i' can not be referenced from a non-isolated context nonisolated var o: Wrap { _i } ^ <stdin>:7:25: note: property declared here @Wrap nonisolated var i: Int = 0 ^
(edited)@propertyWrapper struct Wrap { var wrappedValue: Int var projectedValue: Int = 0 } actor A { @Wrap nonisolated var i: Int = 0 }
@propertyWrapper struct Wrap { var wrappedValue: Int var projectedValue: Int = 0 } actor A { @Wrap nonisolated var i: Int = 0 }
print(a) let a = 1 print(a)
swift -O -
1 1
print(a) let a = 1 print(a)
swift -Onone -
0 1
_ = 1 as Sendable
protocol P {} extension Int: P {} func f() -> [some P] { [1, 2] } print(f())
(edited)protocol P {} extension Int: P {} func f() -> [some P] { [1, 2] } print(f())
(edited)<stdin>:3:13: error: 'opaque' types cannot be nested inside other types; structural 'opaque' types are an experimental feature func f() -> [some P] { [1, 2] } ^
(edited)import XCTest let c1 = { XCTAssertNoThrow(1) } let c2 = { XCTAssertNoThrow(try Result<Int, Error>.success(1).get()) } print(type(of: c1)) print(type(of: c2))
import XCTest let c1 = { XCTAssertNoThrow(1) } let c2 = { XCTAssertNoThrow(try Result<Int, Error>.success(1).get()) } print(type(of: c1)) print(type(of: c2))
() -> () () throws -> ()
import XCTest let c1 = { XCTAssertNoThrow(1) } let c2 = { XCTAssertNoThrow(try Result<Int, Error>.success(1).get()) } print(type(of: c1)) print(type(of: c2))
() -> () () throws -> ()
import XCTest let c1 = { XCTAssertNoThrow(1) } let c2 = { XCTAssertNoThrow(try Result<Int, Error>.success(1).get()) } print(type(of: c1)) print(type(of: c2))
import XCTest let c1 = { XCTAssertNoThrow(1) } let c2 = { XCTAssertNoThrow(try Result<Int, Error>.success(1).get()) } print(type(of: c1)) print(type(of: c2))
() -> () () throws -> ()
import XCTest let c3: () -> () = { XCTAssertNoThrow(try Result<Int, Error>.success(1).get()) } func c4() { XCTAssertNoThrow(try Result<Int, Error>.success(1).get()) } print(type(of: c3)) print(type(of: c4))
import XCTest let c3: () -> () = { XCTAssertNoThrow(try Result<Int, Error>.success(1).get()) } func c4() { XCTAssertNoThrow(try Result<Int, Error>.success(1).get()) } print(type(of: c3)) print(type(of: c4))
<stdin>:3:20: error: invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> ()' let c3: () -> () = { ^
func f() { print(nanika) } f() let nanika: String = { print("nanika is initialized!") return "nanika" }()
func f() { print(nanika) } f() let nanika: String = { print("nanika is initialized!") return "nanika" }()
nanika is initialized!
func f() { let v = nanika if v.isEmpty { print("nanika is empty") } else { print(v) } } f() let nanika: String = { print("nanika is initialized!") return "nanika" }()
func f() { let v = nanika if v.isEmpty { print("nanika is empty") } else { print(v) } } f() let nanika: String = { print("nanika is initialized!") return "nanika" }()
nanika is empty nanika is initialized!
func f() { nanika.withCString { ptr in print(ptr.pointee) } } f() let nanika: String = { return "nanika" }()
(edited)func f() { nanika.withCString { ptr in print(ptr.pointee) } } f() let nanika: String = { return "nanika" }()
(edited)Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6-dev (LLVM bfd3cb18089d333, Swift 367b4c1355d9269) 2. Compiling with the current language version 3. While running user code "<stdin>" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5f5aee3] /usr/bin/swift-frontend[0x5f58a8e] /usr/bin/swift-frontend[0x5f5b276] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7fcd67aec980] /usr/lib/swift/linux/libswiftCore.so($ss13_StringObjectV18getSharedUTF8StartSPys5UInt8VGyF+0xd)[0x7fcd5ed2f22d]
print(nanika) let nanika: String = { return "nanika" }()
print(nanika) let nanika: String = { return "nanika" }()
let nanika: String = { return "nanika" }() print(nanika)
let nanika: String = { return "nanika" }() print(nanika)
nanika
func main() { print(nanika) let nanika: String = { return "nanika" }() }
-parse-as-library
付けてれば大丈夫ですねprint(1 / 0)
print(1 / 0)
<stdin>:1:9: error: division by zero print(1 / 0) ^
print(1.0 / 0.0)
let t: (some Numeric, some Numeric) = (0, 0) print(t)
(edited)let t: (some Numeric, some Numeric) = (0, 0) print(t)
(edited)<stdin>:1:8: error: '(some Numeric, some Numeric)' contains multiple 'opaque' types, but only one 'opaque' type is supported let t: (some Numeric, some Numeric) = (0, 0) ^
(edited)protocol P {} extension Int: P {} let t: (Int, some P) = (0, 0)
(edited)protocol P {} extension Int: P {} let t: (Int, some P) = (0, 0)
(edited)actor SendableExperiment { private var int: Int = 0 private var user2: User2 = .init() private var user3: User3 = .init() private var user4: User4 = .init() private var user5: User5 = .init() func increment() -> Int { int += 1 return int } func incrementAge2() -> User2 { user2.age += 1 return user2 } func incrementAge3() -> User3 { user3.age += 1 return user3 } func incrementAge4() -> User4 { user4.age += 1 return user4 } func incrementAge5() -> User5 { // user5.age += 1 return user5 } } struct User2 { let name: String = "Foo" var age: Int = 42 } public struct User3 { public let name: String = "Foo" public var age: Int = 42 } final class User4 { let name: String = "Foo" var age: Int = 42 } final class User5 { let name: String = "Foo" let age: Int = 42 }
actor SendableExperiment { private var int: Int = 0 private var user2: User2 = .init() private var user3: User3 = .init() private var user4: User4 = .init() private var user5: User5 = .init() func increment() -> Int { int += 1 return int } func incrementAge2() -> User2 { user2.age += 1 return user2 } func incrementAge3() -> User3 { user3.age += 1 return user3 } func incrementAge4() -> User4 { user4.age += 1 return user4 } func incrementAge5() -> User5 { // user5.age += 1 return user5 } } struct User2 { let name: String = "Foo" var age: Int = 42 } public struct User3 { public let name: String = "Foo" public var age: Int = 42 } final class User4 { let name: String = "Foo" var age: Int = 42 } final class User5 { let name: String = "Foo" let age: Int = 42 }
@MainActor protocol P { } struct S: P {} Task { await MainActor.run { let p: P = S() let optionalP: P! = nil let s: S = S() Task { print(String(describing: p)) print(String(describing: optionalP)) print(String(describing: s)) } } }
(edited)@MainActor protocol P { } struct S: P {} Task { await MainActor.run { let p: P = S() let optionalP: P! = nil let s: S = S() Task { print(String(describing: p)) print(String(describing: optionalP)) print(String(describing: s)) } } }
(edited)<stdin>:11:32: warning: cannot use let 'p' with a non-sendable type 'P' from concurrently-executed code print(String(describing: p)) ^ <stdin>:1:21: note: protocol 'P' does not conform to the 'Sendable' protocol @MainActor protocol P { } ^ <stdin>:12:32: warning: cannot use let 'optionalP' with a non-sendable type 'P?' from concurrently-executed code print(String(describing: optionalP)) ^ <stdin>:1:21: note: protocol 'P' does not conform to the 'Sendable' protocol @MainActor protocol P { } ^
(edited)@MainActor protocol P { } struct S: P {} Task { await MainActor.run { let p: P = S() let optionalP: P! = nil let s: S = S() Task { print(String(describing: p)) print(String(describing: optionalP)) print(String(describing: s)) } } }
(edited)<stdin>:11:32: warning: cannot use let 'p' with a non-sendable type 'P' from concurrently-executed code print(String(describing: p)) ^ <stdin>:12:32: warning: cannot use let 'optionalP' with a non-sendable type 'P?' from concurrently-executed code print(String(describing: optionalP)) ^
(edited)Swift version 5.4.3 (swift-5.4.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.5-dev (LLVM c315411fac10439, Swift 424bc4056fc81c2) Target: x86_64-unknown-linux-gnu
Swift version 5.1.5 (swift-5.1.5-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.1.3 (swift-4.1.3-RELEASE) Target: x86_64-unknown-linux-gnu
var const: Int { 42 } let const2: Int = 42 actor A { init() { _ = const _ = const2 } }
var const: Int { 42 } let const2: Int = 42 actor A { init() { _ = const _ = const2 } }
<stdin>:6:9: warning: reference to var 'const' is not concurrency-safe because it involves shared mutable state _ = const ^ <stdin>:1:5: note: var declared here var const: Int { 42 } ^
func const() -> Int { 42 } let const2: Int = 42 actor A { init() { _ = const() _ = const2 } }
(edited)func const() -> Int { 42 } let const2: Int = 42 actor A { init() { _ = const() _ = const2 } }
(edited)var mutableG = 0 func const() -> Int { mutableG = 1 return 42 } let const2: Int = 42 actor A { init() { _ = const() _ = const2 } }
var mutableG = 0 func const() -> Int { mutableG = 1 return 42 } let const2: Int = 42 actor A { init() { _ = const() _ = const2 } }
<stdin>:3:3: warning: reference to var 'mutableG' is not concurrency-safe because it involves shared mutable state mutableG = 1 ^ <stdin>:1:5: note: var declared here var mutableG = 0 ^
const()
がactor contextを持っているかのような警告だvar mutableG = 0 func const() -> Int { mutableG = 1 return 42 }
var mutableG = 0 func const() -> Int { mutableG = 1 return 42 }
<stdin>:3:3: warning: reference to var 'mutableG' is not concurrency-safe because it involves shared mutable state mutableG = 1 ^ <stdin>:1:5: note: var declared here var mutableG = 0 ^
import Foundation let json = """ { "foo": "{\"key\": \"value\"}" } """.data(using: .utf8)! struct Body: Codable { var foo: String } let decoder = JSONDecoder() let decoded = try decoder.decode(Body.self, from: json) print(decoded)
(edited)import Foundation let json = """ { "foo": "{\"key\": \"value\"}" } """.data(using: .utf8)! struct Body: Codable { var foo: String } let decoder = JSONDecoder() let decoded = try decoder.decode(Body.self, from: json) print(decoded)
(edited)Swift/ErrorType.swift:200: Fatal error: Error raised at top level: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Foundation.JSONError.unexpectedCharacter(ascii: 107, characterIndex: 16)))) Current stack trace: 0 libswiftCore.so 0x00007f8a2e843cd0 swift_reportError + 50 1 libswiftCore.so 0x00007f8a2e8bc2a0 _swift_stdlib_reportFatalErrorInFile + 109 2 libswiftCore.so 0x00007f8a2e5c95a2 <unavailable> + 1414562 3 libswiftCore.so 0x00007f8a2e5c92cb <unavailable> + 1413835 4 libswiftCore.so 0x00007f8a2e5c7fb0 _assertionFailure(_:_:file:line:flags:) + 447 5 libswiftCore.so 0x00007f8a2e628d10 swift_errorInMain + 731 7 swift-frontend 0x00000000006e228a <unavailable> + 3023498 8 swift-frontend 0x00000000005ba271 <unavailable> + 1811057 9 swift-frontend 0x000000000056ddc3 <unavailable> + 1498563 10 swift-frontend 0x000000000056d5f7 <unavailable> + 1496567 11 swift-frontend 0x000000000056135e <unavailable> + 1446750 12 swift-frontend 0x00000000004b0646 <unavailable> + 722502 13 libc.so.6 0x00007f8a321f6b10 __libc_start_main + 231 14 swift-frontend 0x00000000004b027a <unavailable> + 721530 Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.5-dev (LLVM c315411fac10439, Swift 424bc4056fc81c2) 2. 3. While running user code "<stdin>" Stack dump wit
(edited)import Foundation let json = """ { "foo": "{\\"key\\": \\"value\\"}" } """.data(using: .utf8)! struct Body: Codable { var foo: String } let decoder = JSONDecoder() let decoded = try decoder.decode(Body.self, from: json) print(decoded)
import Foundation let json = """ { "foo": "{\\"key\\": \\"value\\"}" } """.data(using: .utf8)! struct Body: Codable { var foo: String } let decoder = JSONDecoder() let decoded = try decoder.decode(Body.self, from: json) print(decoded)
Body(foo: "{\"key\": \"value\"}")
import Foundation let json = #"{ "foo": "{\"key\": \"value\"}" }"#.data(using: .utf8)! struct Body: Codable { var foo: String } let decoded = try JSONDecoder().decode(Body.self, from: json) print(decoded)
import Foundation let json = #""" { "foo": "{\"key\": \"value\"}" } """#.data(using: .utf8)! struct Body: Codable { var foo: String } let decoder = JSONDecoder() let decoded = try decoder.decode(Body.self, from: json) print(decoded)
import Foundation let json = #""" { "foo": "{\"key\": \"value\"}" } """#.data(using: .utf8)! struct Body: Codable { var foo: String } let decoder = JSONDecoder() let decoded = try decoder.decode(Body.self, from: json) print(decoded)
Body(foo: "{\"key\": \"value\"}")
import Differentiation @differentiable func test(x: Float) -> Float { x*x }
import Differentiation @differentiable func test(x: Float) -> Float { x*x }
<stdin>:3:16: warning: '@differentiable' has been renamed to '@differentiable(reverse)' and will be removed in the next release @differentiable ^ (reverse) <stdin>:1:8: error: no such module 'Differentiation' import Differentiation ^
func twoOpaqueTypes() -> (some Numeric, some Numeric) { return (1, 2) }
(edited)func twoOpaqueTypes() -> (some Numeric, some Numeric) { return (1, 2) }
(edited)<stdin>:1:26: error: '(some Numeric, some Numeric)' contains multiple 'opaque' types, but only one 'opaque' type is supported func twoOpaqueTypes() -> (some Numeric, some Numeric) { return (1, 2) } ^
(edited)struct Links { var `self`: String init(`self`: String) { self.`self` = `self` } } var links = Links(self: "foo/bar") print(links.`self`)
(edited)struct Links { var `self`: String init(`self`: String) { self.`self` = `self` } } var links = Links(self: "foo/bar") print(links.`self`)
(edited)<stdin>:5:14: error: value of type 'String' has no member 'self' self.`self` = `self` ~~~~ ^~~~~~
(edited)let dict: [_: String] = [0: "zero", 1: "one", 2: "two"]
let dict: [_: String] = [0: "zero", 1: "one", 2: "two"]
@MainActor class ViewController { func viewDidAppear() {} } class XViewController: ViewController { override func viewDidAppear() { } } @MainActor protocol StateProtocol { } class State: StateProtocol { func f() async { let vc = ViewController() let xvc = XViewController() Task { vc.viewDidAppear() xvc.viewDidAppear() } } }
(edited)@MainActor class ViewController { func viewDidAppear() {} } class XViewController: ViewController { override func viewDidAppear() { } } @MainActor protocol StateProtocol { } class State: StateProtocol { func f() async { let vc = ViewController() let xvc = XViewController() Task { vc.viewDidAppear() xvc.viewDidAppear() } } }
(edited)<stdin>:21:7: warning: cannot use let 'xvc' with a non-sendable type 'XViewController' from concurrently-executed code xvc.viewDidAppear() ^
(edited)ViewController
から派生して来たものだけが保護されてるんじゃなかったでしたっけ?@MainActor class ViewController { func viewDidAppear() {} } class XViewController: ViewController { override func viewDidAppear() { } func viewDidAppear2() {} } @MainActor protocol StateProtocol { } class State: StateProtocol { func f() async { let vc = ViewController() let xvc = XViewController() Task { vc.viewDidAppear() xvc.viewDidAppear() xvc.viewDidAppear2() } vc.viewDidAppear() xvc.viewDidAppear() xvc.viewDidAppear2() } }
@MainActor class ViewController { func viewDidAppear() {} } class XViewController: ViewController { override func viewDidAppear() { } func viewDidAppear2() {} } @MainActor protocol StateProtocol { } class State: StateProtocol { func f() async { let vc = ViewController() let xvc = XViewController() Task { vc.viewDidAppear() xvc.viewDidAppear() xvc.viewDidAppear2() } vc.viewDidAppear() xvc.viewDidAppear() xvc.viewDidAppear2() } }
<stdin>:22:7: warning: cannot use let 'xvc' with a non-sendable type 'XViewController' from concurrently-executed code xvc.viewDidAppear() ^ <stdin>:23:7: warning: cannot use let 'xvc' with a non-sendable type 'XViewController' from concurrently-executed code xvc.viewDidAppear2() ^
ViewController
から派生して来たものだけが保護されてるんじゃなかったでしたっけ? viewDidAppear
だけですかねviewDidAppear2
もMainActorとして認識されてそうと思って↑の例を書きましたが、よく考えたら XVC
は何のglobalActorにも保護されてないからただ普通に呼んでるだけでした・・・import XCTest class T: XCTestCase { func testA() async throws {} }
import XCTest class T: XCTestCase { func testA() async throws {} }
error: Unexpected argument '-' Usage: swift test <options> See 'test -help' for more information.
import XCTest class T: XCTestCase { func testA() async throws {} static let allTests = [("testA", asyncTest(testA))] } XCTMain([testCase(T.allTests)])
(edited)import XCTest class T: XCTestCase { func testA() async throws {} static let allTests = [("testA", asyncTest(testA))] } XCTMain([testCase(T.allTests)])
(edited)Test Suite 'All tests' started at 2021-12-15 14:28:43.336 Test Suite 'bin.xctest' started at 2021-12-15 14:28:43.338 Test Suite 'T' started at 2021-12-15 14:28:43.338 Test Case 'T.testA' started at 2021-12-15 14:28:43.338 Test Case 'T.testA' passed (0.002 seconds) Test Suite 'T' passed at 2021-12-15 14:28:43.340 Executed 1 test, with 0 failures (0 unexpected) in 0.002 (0.002) seconds Test Suite 'bin.xctest' passed at 2021-12-15 14:28:43.340 Executed 1 test, with 0 failures (0 unexpected) in 0.002 (0.002) seconds Test Suite 'All tests' passed at 2021-12-15 14:28:43.340 Executed 1 test, with 0 failures (0 unexpected) in 0.002 (0.002) seconds
(edited)func f2() async -> Int { 42 } class C {} struct S { let c = C() var value = 0 func f() async { let _ = await f2() print(value) } }
(edited)func f2() async -> Int { 42 } class C {} struct S { let c = C() var value = 0 func f() async { let _ = await f2() print(value) } }
(edited)f
のスコープ内では保護されてるのかなawait
はまたげるんじゃないですか?@Sendable
クロージャがキャプチャできない。import Foundation func f2() async -> Int { 42 } class Nanika { var value = 0 func f() async { let _ = await f2() value += 1 print(value) } } let nanika = Nanika() for _ in 0..<10 { Task.detached { await nanika.f() } } sleep(1)
(edited)import Foundation func f2() async -> Int { 42 } class Nanika { var value = 0 func f() async { let _ = await f2() value += 1 print(value) } } let nanika = Nanika() for _ in 0..<10 { Task.detached { await nanika.f() } } sleep(1)
(edited)1 2 3 4 5 6 7 8 9 10
(edited)import Foundation func f2() async -> Int { 42 } class Nanika { var value = 0 func f() async { // let _ = await f2() value += 1 print(value) } } let nanika = Nanika() for _ in 0..<10 { Task.detached { await nanika.f() } } sleep(1)
(edited)import Foundation func f2() async -> Int { 42 } class Nanika { var value = 0 func f() async { // let _ = await f2() value += 1 print(value) } } let nanika = Nanika() for _ in 0..<10 { Task.detached { await nanika.f() } } sleep(1)
(edited)2 1 4 5 6 7 8 9 3 10
(edited)await
以降の処理がグローバルなコンテキストで律速してる?Nanika
に対して並列に f
を呼び出すと壊れるけど、そもそも呼び出しの時点で何も安全性が保証されてないのでそこを保護してもしょうがないのかstruct MyError: Error {} func throwError() async throws -> Int { throw MyError() } func main() async { async let v = try throwError() _ = try! await v }
(edited)struct MyError: Error {} func throwError() async throws -> Int { throw MyError() } func main() async { async let v = try throwError() _ = try! await v }
(edited)struct MyError: Error {} func throwError() async throws -> Int { throw MyError() } func main() async { async let v = try throwError() _ = try! await v }
(edited)try throwError()
の tryは無意味だけどワーニングが出ないimport Foundation print("Swift, Error".components(separatedBy: .init(charactersIn: ","))) print("Swift, Error".split(separator: ","))
(edited)import Foundation print("Swift, Error".components(separatedBy: .init(charactersIn: ","))) print("Swift, Error".split(separator: ","))
(edited)["Swift", " Error"] ["Swift", " Error"]
(edited)import Foundation @MainActor struct Button { var action: () -> () init(_ action: @escaping () -> ()) { self.action = action } func work() { let action = action DispatchQueue.global().async { action() } } } @MainActor struct MyView { var body: some Any { Button { f() } } func f() { print("Thread.isMainThread", Thread.isMainThread) print(Thread.current) } } Task { await MainActor.run { let view = MyView() let button = view.body as! Button button.work() } } RunLoop.main.run(until: Date().addingTimeInterval(0.3)) print("end")
(edited)import Foundation @MainActor struct Button { var action: () -> () init(_ action: @escaping () -> ()) { self.action = action } func work() { let action = action DispatchQueue.global().async { action() } } } @MainActor struct MyView { var body: some Any { Button { f() } } func f() { print("Thread.isMainThread", Thread.isMainThread) print(Thread.current) } } Task { await MainActor.run { let view = MyView() let button = view.body as! Button button.work() } } RunLoop.main.run(until: Date().addingTimeInterval(0.3)) print("end")
(edited)Thread.isMainThread false <Thread: 0x00007fb86c002140> end
stderr:<stdin>:11:13: warning: cannot use let 'action' with a non-sendable type '() -> ()' from concurrently-executed code action() ^ <stdin>:11:13: note: a function type must be marked '@Sendable' to conform to 'Sendable' action() ^
(edited)import Foundation @MainActor struct Button { var action: () -> () init(_ action: @escaping () -> ()) { self.action = action } func work() { let action = action DispatchQueue.global().async { action() } } } @MainActor struct MyView { var body: some Any { Button { f() } } func f() { print("Thread.isMainThread", Thread.isMainThread) print(Thread.current) } } Task { await MainActor.run { let view = MyView() let button = view.body as! Button button.work() } } RunLoop.main.run(until: Date().addingTimeInterval(0.3)) print("end")
(edited)Thread.isMainThread false <Thread: 0x00007fec20002130> end
stderr:<stdin>:11:13: warning: cannot use let 'action' with a non-sendable type '() -> ()' from concurrently-executed code action() ^
(edited)@MainActor
な f
がメインスレッド以外から呼ばれてるけど、一応Sendableの警告は出てるのでセーフか@dynamicMemberLookup struct Box<Value> { var value: Value subscript<T>(dynamicMember keyPath: WritableKeyPath<Value, T>) -> T { get { value[keyPath: keyPath] } set { value[keyPath: keyPath] = newValue } } } struct Foo { var count: Int = 0 } let boxed = Box(value: Foo()) print(boxed.count) let boxedBoxed = Box(value: boxed) print(boxedBoxed.count) print(boxedBoxed[dynamicMember: \.[dynamicMember: \Foo.count]])
(edited)@dynamicMemberLookup struct Box<Value> { var value: Value subscript<T>(dynamicMember keyPath: WritableKeyPath<Value, T>) -> T { get { value[keyPath: keyPath] } set { value[keyPath: keyPath] = newValue } } } struct Foo { var count: Int = 0 } let boxed = Box(value: Foo()) print(boxed.count) let boxedBoxed = Box(value: boxed) print(boxedBoxed.count) print(boxedBoxed[dynamicMember: \.[dynamicMember: \Foo.count]])
(edited)0 0 0
stderr:<stdin>:16:17: warning: cannot form key path that captures non-sendable type 'WritableKeyPath<Foo, Int>' print(boxedBoxed.count) ^ <stdin>:17:35: warning: cannot form key path that captures non-sendable type '(dynamicMember: WritableKeyPath<Foo, Int>)' print(boxedBoxed[dynamicMember: \.[dynamicMember: \Foo.count]]) ^
(edited)struct Box { subscript<T>(bar bar: T) -> T { bar } } let _ = \Box[bar: 1] let _ = \Box[bar: \Int.description]
(edited)struct Box { subscript<T>(bar bar: T) -> T { bar } } let _ = \Box[bar: 1] let _ = \Box[bar: \Int.description]
(edited)<stdin>:8:13: warning: cannot form key path that captures non-sendable type '(bar: KeyPath<Int, String>)' let _ = \Box[bar: \Int.description] ^
(edited)import Foundation let pi = 3.14159265359 print(String(format: "%f", pi))
(edited)import Foundation let pi = 3.14159265359 print(String(format: "%f", pi))
(edited)3.141593
(edited)@_predatesConcurrency import Foundation func f<T: Sendable>(_: T) { } f(Date())
@_predatesConcurrency import Foundation func f<T: Sendable>(_: T) { } f(Date())
Swift version 5.6-dev (LLVM 64a4d678f114158, Swift 8ae983c3480462b) Target: x86_64-unknown-linux-gnu
import Foundation @propertyWrapper struct W<T>: Sendable where T: Sendable { var wrappedValue: T } struct S { @W var ok: Int @W var ng: Date } extension Date: @unchecked Sendable {}
(edited)import Foundation @propertyWrapper struct W<T>: Sendable where T: Sendable { var wrappedValue: T } struct S { @W var ok: Int @W var ng: Date } extension Date: @unchecked Sendable {}
(edited)swift-frontend: /home/buildnode/jenkins/workspace/oss-swift-5.5-package-linux-ubuntu-18_04/swift/lib/AST/ASTMangler.cpp:2217: void swift::Mangle::ASTMangler::appendProtocolName(const swift::ProtocolDecl *, bool): Assertion `AllowMarkerProtocols || !protocol->isMarkerProtocol()' failed. Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.5.2-dev (LLVM c315411fac10439, Swift ef1fbfd974df3ad) 2. 3. While running user code "<stdin>" 4. While evaluating request IRGenRequest(IR Generation for module main) 5. While emitting IR for source file <stdin> 6. While emitting field type metadata 'S' (at <stdin>:8:1) Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5c5ffb3] /usr/bin/swift-frontend[0x5c5dd0e] /usr/bin/swift-frontend[0x5c6033c] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f5109d5a980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7f51085fcfb7] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7f51085fe921] /lib/x86_64-linux-gnu/libc.so.6(+0x3048a)[0x7f51085ee48a] /lib/x86_64-linux-gnu/libc.so.6(+0x30502)[0x7f51085ee502] /usr/bin/swift-frontend[0x181fed5] /usr/bin/swift-frontend[0x182c0f6] /usr/bin/swift-frontend[0x182903d] /usr/bin/swift-frontend[0x1827cf2] /usr/bin/swift-frontend[0x1826bde] /usr/bin/swift-frontend[0x1821b21] /usr/bin/swift-frontend[0xb239cd] /usr/bin/swift-frontend[0xb23bdf] /usr/bin/swift-frontend[0xacd38d] /usr/bin/swift-frontend[0xad1545] /usr/bin/swift-frontend[0xad4807] /usr/bin/swift-frontend[0xad4770] /usr/bin/swift-frontend[0x9ba13c] /usr/bin/swift-frontend[0xad436d] /usr/bin/swift-frontend[0xad416b] /usr
(edited)import Foundation @propertyWrapper struct W<T>: Sendable where T: Sendable { var wrappedValue: T } struct S { @W var ok: Int @W var ng: Date } extension Date: @unchecked Sendable {}
(edited)swift-frontend: /home/buildnode/jenkins/workspace/oss-swift-5.6-package-linux-ubuntu-18_04/swift/lib/AST/ASTMangler.cpp:2254: void swift::Mangle::ASTMangler::appendProtocolName(const swift::ProtocolDecl *, bool): Assertion `AllowMarkerProtocols || !protocol->isMarkerProtocol()' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6-dev (LLVM 64a4d678f114158, Swift 8ae983c3480462b) 2. Compiling with the current language version 3. While running user code "<stdin>" 4. While evaluating request IRGenRequest(IR Generation for module main) 5. While emitting IR for source file <stdin> 6. While emitting field type metadata 'S' (at <stdin>:8:1) Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5fa3093] /usr/bin/swift-frontend[0x5fa0c3e] /usr/bin/swift-frontend[0x5fa3426] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f2b4bf89980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7f2b4a217fb7] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7f2b4a219921] /lib/x86_64-linux-gnu/libc.so.6(+0x3048a)[0x7f2b4a20948a] /lib/x86_64-linux-gnu/libc.so.6(+0x30502)[0x7f2b4a209502] /usr/bin/swift-frontend[0x18b1185] /usr/bin/swift-frontend[0x18be316] /usr/bin/swift-frontend[0x18bb174] /usr/bin/swift-frontend[0x18b9db9] /usr/bin/swift-frontend[0x18b851e] /usr/bin/swift-frontend[0x18b2f55] /usr/bin/swift-frontend[0xb2e7dd] /usr/bin/swift-frontend[0xb2ea51] /usr/bin/swift-frontend[0xad4fdf] /usr/bin/swift-frontend[0xad9045] /usr/bin/swift-frontend[0xadc317] /usr/bin/swift-frontend[0xadc280] /usr/bin/swift-frontend[0x9bf88c] /usr/bin/swift-frontend[0xadbe7d] /usr/bin/swift-frontend[0xadbc7b] /usr/bin/swift-frontend[0xad9205] /usr/bin/swift-frontend[0xad7f29] /usr/bin/swift-front
(edited)import Foundation @propertyWrapper struct W<T>: Sendable where T: Sendable { var wrappedValue: T } struct S { @W var ok: Int @W var ng: Date } extension Date: @unchecked Sendable {}
(edited)swift-frontend: /home/buildnode/jenkins/workspace/oss-swift-package-linux-ubuntu-18_04/swift/lib/AST/ASTMangler.cpp:2287: void swift::Mangle::ASTMangler::appendProtocolName(const swift::ProtocolDecl *, bool): Assertion `AllowMarkerProtocols || !protocol->isMarkerProtocol()' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6-dev (LLVM 7b20e61dd04138a, Swift 9438cf6b2e83c5f) 2. Compiling with the current language version 3. While running user code "<stdin>" 4. While evaluating request IRGenRequest(IR Generation for module main) 5. While emitting IR for source file <stdin> 6. While emitting field type metadata 'S' (at <stdin>:8:1) Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x60543e3] /usr/bin/swift-frontend[0x6051f8e] /usr/bin/swift-frontend[0x6054776] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f7a34a14980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7f7a32ca0fb7] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7f7a32ca2921] /lib/x86_64-linux-gnu/libc.so.6(+0x3048a)[0x7f7a32c9248a] /lib/x86_64-linux-gnu/libc.so.6(+0x30502)[0x7f7a32c92502] /usr/bin/swift-frontend[0x1951be5] /usr/bin/swift-frontend[0x195ef76] /usr/bin/swift-frontend[0x195bce2] /usr/bin/swift-frontend[0x195a909] /usr/bin/swift-frontend[0x195902e] /usr/bin/swift-frontend[0x19539b7] /usr/bin/swift-frontend[0x9cf0ad] /usr/bin/swift-frontend[0x9cf321] /usr/bin/swift-frontend[0x97563f] /usr/bin/swift-frontend[0x9796f1] /usr/bin/swift-frontend[0x97ca3c] /usr/bin/swift-frontend[0x97c990] /usr/bin/swift-frontend[0x85e4bc] /usr/bin/swift-frontend[0x97c58d] /usr/bin/swift-frontend[0x97c38b] /usr/bin/swift-frontend[0x9798f5] /usr/bin/swift-frontend[0x9785b9] /usr/bin/swift-frontend[
Sendable
つけてるかどうかな気がするんですよねprotocol Animal: Sendable { associatedtype ID: Sendable } protocol P { func f<A: Animal>(type: A.Type, id: A.ID) async } actor Foo: P { func f<A: Animal>(type: A.Type, id: A.ID) async {} } actor Bar { func f<A: Animal>(type: A.Type, id: A.ID) async {} }
(edited)protocol Animal: Sendable { associatedtype ID: Sendable } protocol P { func f<A: Animal>(type: A.Type, id: A.ID) async } actor Foo: P { func f<A: Animal>(type: A.Type, id: A.ID) async {} } actor Bar { func f<A: Animal>(type: A.Type, id: A.ID) async {} }
(edited)protocol Animal: Sendable { associatedtype ID: Sendable } protocol P { func f<A: Animal>(type: A.Type, id: A.ID) async } actor Foo: P { func f<A: Animal>(type: A.Type, id: A.ID) async {} } actor Bar { func f<A: Animal>(type: A.Type, id: A.ID) async {} }
(edited)<stdin>:10:10: warning: cannot pass argument of non-sendable type 'A.ID' across actors func f<A: Animal>(type: A.Type, id: A.ID) async {} ^
// may cause "Cannot convert value of type 'Int' to expected argument type 'Builtin.FPIEEE64'" import Foundation let (N, M, K) = {() -> (Int, Int, Int) in let v = readLine()!.split(separator:" ").map{Int($0)!} return (v[0], v[1], v[2]) }() guard N - M >= K else { print(1.0) exit(0) } let b: [Double] = stride(from: N, through: N - K + 2, by: -1) .map({ i -> Double in Double(i)}) .map({ e -> Double in Double(e - 1 - M) / e }) let hazure = b.reduce(1.0) { (partialResult: inout Double, v: Double) -> Double in partialResult * v } let atari: Double = Double(M) / Double(N - K + 1) print(hazure * atari)
// may cause "Cannot convert value of type 'Int' to expected argument type 'Builtin.FPIEEE64'" import Foundation let (N, M, K) = {() -> (Int, Int, Int) in let v = readLine()!.split(separator:" ").map{Int($0)!} return (v[0], v[1], v[2]) }() guard N - M >= K else { print(1.0) exit(0) } let b: [Double] = stride(from: N, through: N - K + 2, by: -1) .map({ i -> Double in Double(i)}) .map({ e -> Double in Double(e - 1 - M) / e }) let hazure = b.reduce(1.0) { (partialResult: inout Double, v: Double) -> Double in partialResult * v } let atari: Double = Double(M) / Double(N - K + 1) print(hazure * atari)
<stdin>:15:10: error: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions .map({ e -> Double in Double(e - 1 - M) / e }) ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <stdin>:16:28: error: cannot convert value of type '(inout Double, Double) -> Double' to expected argument type '(Double, Double) throws -> Double' let hazure = b.reduce(1.0) { (partialResult: inout Double, v: Double) -> Double in partialResult * v } ^
import Foundation struct S { @TaskLocal static var foo: Date? } extension Date: @unchecked Sendable {} print(S.foo ?? "nil")
(edited)import Foundation struct S { @TaskLocal static var foo: Date? } extension Date: @unchecked Sendable {} print(S.foo ?? "nil")
(edited)swift-frontend: /home/buildnode/jenkins/workspace/oss-swift-5.6-package-linux-ubuntu-18_04/swift/lib/AST/ASTMangler.cpp:2254: void swift::Mangle::ASTMangler::appendProtocolName(const swift::ProtocolDecl *, bool): Assertion `AllowMarkerProtocols || !protocol->isMarkerProtocol()' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6-dev (LLVM 64a4d678f114158, Swift 8ae983c3480462b) 2. Compiling with the current language version 3. While running user code "<stdin>" 4. While evaluating request IRGenRequest(IR Generation for module main) 5. While emitting IR SIL function "@$s4main1SV4_foo33_1A61A3E7348A44FC8FF8726B26BEB4EDLL_WZ". for declaration 0xb2c3c68 (in module 'main') Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5fa3093] /usr/bin/swift-frontend[0x5fa0c3e] /usr/bin/swift-frontend[0x5fa3426] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f378e08d980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7f378c31bfb7] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7f378c31d921] /lib/x86_64-linux-gnu/libc.so.6(+0x3048a)[0x7f378c30d48a] /lib/x86_64-linux-gnu/libc.so.6(+0x30502)[0x7f378c30d502] /usr/bin/swift-frontend[0x18b1185] /usr/bin/swift-frontend[0x18be316] /usr/bin/swift-frontend[0x18bb174] /usr/bin/swift-frontend[0x18b9db9] /usr/bin/swift-frontend[0x18b851e] /usr/bin/swift-frontend[0x18b2f55] /usr/bin/swift-frontend[0xb2e7dd] /usr/bin/swift-frontend[0xb2ea51] /usr/bin/swift-frontend[0xad4fdf] /usr/bin/swift-frontend[0x9b17e5] /usr/bin/swift-frontend[0x9b4ae4] /usr/bin/swift-frontend[0xb3bbf0] /usr/bin/swift-frontend[0xb3320b] /usr/bin/swift-frontend[0xb3034c] /usr/bin/swift-frontend[0xa2d3bb] /usr/bin/swift-frontend[0x95ad10] /usr/bin/swift-fro
(edited)import Foundation struct S { @TaskLocal static var foo: Date? } extension Date: @unchecked Sendable {} print(S.foo ?? "nil")
(edited)nil
(edited)struct Links: Codable { let `self`: String init(self aSelf: String) { self.`self` = aSelf } }
(edited)struct Links: Codable { let `self`: String init(self aSelf: String) { self.`self` = aSelf } }
(edited)<unknown>:0: warning: 'self' refers to the method 'Links.CodingKeys.self', which may be unexpected <unknown>:0: note: use 'Links.CodingKeys.self' to silence this warning <unknown>:0: warning: 'self' refers to the method 'Links.self', which may be unexpected <unknown>:0: note: use 'Links.self' to silence this warning <unknown>:0: warning: 'self' refers to the method 'Links.self', which may be unexpected <unknown>:0: note: use 'Links.self' to silence this warning
(edited)struct Links: Codable { let `self`: String init(self aSelf: String) { self.`self` = aSelf } }
(edited)struct Links: Codable { let `self`: String }
struct Links: Codable { let `self`: String }
struct Links: Codable { let `self`: String }
<unknown>:0: warning: 'self' refers to the method 'Links.CodingKeys.self', which may be unexpected <unknown>:0: note: use 'Links.CodingKeys.self' to silence this warning <unknown>:0: warning: 'self' refers to the method 'Links.self', which may be unexpected <unknown>:0: note: use 'Links.self' to silence this warning <unknown>:0: warning: 'self' refers to the method 'Links.self', which may be unexpected <unknown>:0: note: use 'Links.self' to silence this warning
import Foundation @propertyWrapper struct Wrapper { var wrappedValue: Int? var projectedValue: String? init(wrappedValue: Int?) { self.wrappedValue = wrappedValue } init(projectedValue: String?) { self.projectedValue = projectedValue } } func foo(@Wrapper value: Int?) { print(value) } foo(value: 100) foo($value: "string")
import Foundation @propertyWrapper struct Wrapper { var wrappedValue: Int? var projectedValue: String? init(wrappedValue: Int?) { self.wrappedValue = wrappedValue } init(projectedValue: String?) { self.projectedValue = projectedValue } } func foo(@Wrapper value: Int?) { print(value) } foo(value: 100) foo($value: "string")
Optional(100) nil
stderr:<stdin>:18:9: warning: expression implicitly coerced from 'Int?' to 'Any' print(value) ^~~~~ <stdin>:18:9: note: provide a default value to avoid this warning print(value) ^~~~~ ?? <#default value#> <stdin>:18:9: note: force-unwrap the value to avoid this warning print(value) ^~~~~ ! <stdin>:18:9: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(value) ^~~~~ as Any
import Foundation @propertyWrapper struct Wrapper { var wrappedValue: Int? var projectedValue: String? init(wrappedValue: Int?) { self.wrappedValue = wrappedValue } init(projectedValue: String?) { self.projectedValue = projectedValue } } func foo(@Wrapper value: Int?) { print(value) } foo(value: 100) foo($value: "string")
<stdin>:21:1: error: type of expression is ambiguous without more context foo(value: 100) ^~~~~~~~~~~~~~~ <stdin>:18:9: warning: expression implicitly coerced from 'Int?' to 'Any' print(value) ^~~~~ <stdin>:18:9: note: provide a default value to avoid this warning print(value) ^~~~~ ?? <#default value#> <stdin>:18:9: note: force-unwrap the value to avoid this warning print(value) ^~~~~ ! <stdin>:18:9: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(value) ^~~~~ as Any
Swift version 5.5.3 (swift-5.5.3-RELEASE) Target: x86_64-unknown-linux-gnu
import Foundation struct S { @TaskLocal static var foo: Date? } extension Date: @unchecked Sendable {} print(S.foo ?? "nil")
import Foundation struct S { @TaskLocal static var foo: Date? } extension Date: @unchecked Sendable {} print(S.foo ?? "nil")
swift-frontend: /home/buildnode/jenkins/workspace/oss-swift-5.6-package-linux-ubuntu-18_04/swift/lib/AST/ASTMangler.cpp:2256: void swift::Mangle::ASTMangler::appendProtocolName(const swift::ProtocolDecl *, bool): Assertion `AllowMarkerProtocols || !protocol->isMarkerProtocol()' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6-dev (LLVM 62b900d3d0d5be9, Swift ce64fe8867792d4) 2. Compiling with the current language version 3. While running user code "<stdin>" 4. While evaluating request IRGenRequest(IR Generation for module main) 5. While emitting IR SIL function "@$s4main1SV4_foo33_1A61A3E7348A44FC8FF8726B26BEB4EDLL_WZ". for declaration 0xb52a178 (in module 'main') Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5fa5913] /usr/bin/swift-frontend[0x5fa34be] /usr/bin/swift-frontend[0x5fa5ca6] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f04a53ea980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7f04a3675fb7] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7f04a3677921] /lib/x86_64-linux-gnu/libc.so.6(+0x3048a)[0x7f04a366748a] /lib/x86_64-linux-gnu/libc.so.6(+0x30502)[0x7f04a3667502] /usr/bin/swift-frontend[0x18b2295] /usr/bin/swift-frontend[0x18bf416] /usr/bin/swift-frontend[0x18bc204] /usr/bin/swift-frontend[0x18bae49] /usr/bin/swift-frontend[0x18b95ae] /usr/bin/swift-frontend[0x18b4065] /usr/bin/swift-frontend[0xb2e76d] /usr/bin/swift-frontend[0xb2e9e1] /usr/bin/swift-frontend[0xad4e6f] /usr/bin/swift-frontend[0x9b1875] /usr/bin/swift-frontend[0x9b4b74] /usr/bin/swift-frontend[0xb3bc80] /usr/bin/swift-frontend[0xb3329b] /usr/bin/swift-frontend[0xb303dc] /usr/bin/swift-frontend[0xa2d3db] /usr/bin/swift-frontend[0x95ae10] /usr/bin/swift-fro
import Foundation enum Foo: Codable { case aaa(_ foo: Int, _ bar: String) }
(edited)import Foundation enum Foo: Codable { case aaa(_ foo: Int, _ bar: String) }
(edited)import Foundation enum Foo: Codable { case aaa(_ foo: Int, _ bar: String) }
(edited)<unknown>:0: error: type 'Foo' has no member 'aaa(foo:bar:)'
@usableFromInline struct S { @usableFromInline var v: [Int] @inlinable init() { self.v = [] } }
(edited)@usableFromInline struct S { @usableFromInline var v: [Int] @inlinable init() { self.v = [] } }
(edited)<stdin>:8:12: error: 'self' used before 'self.init' call or assignment to 'self' self.v = [] ^ <stdin>:9:3: error: 'self.init' isn't called on all paths before returning from initializer } ^
@usableFromInline struct S { @usableFromInline var v: [Int] @inlinable init() { self.v = [] } }
(edited)<stdin>:8:12: error: 'self' used before 'self.init' call or assignment to 'self' self.v = [] ^ <stdin>:9:3: error: 'self.init' isn't called on all paths before returning from initializer } ^
class C {} @propertyWrapper struct S<T: C> { var wrappedValue: T? } protocol P {} struct Impl { @S var value: (C & P)? }
class C {} @propertyWrapper struct S<T: C> { var wrappedValue: T? } protocol P {} struct Impl { @S var value: (C & P)? }
@MainActor(unsafe) class View { init() {} var foo = 0 } @MainActor final class MyView: View { override init() { super.init() foo = 2 } }
(edited)@MainActor(unsafe) class View { init() {} var foo = 0 } @MainActor final class MyView: View { override init() { super.init() foo = 2 } }
(edited)@MainActor struct View { } func nonIsolated() { _ = View() }
(edited)@MainActor struct View { } func nonIsolated() { _ = View() }
(edited)<stdin>:5:7: error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context _ = View() ^ <stdin>:1:19: note: calls to initializer 'init()' from outside of its actor context are implicitly asynchronous @MainActor struct View { ^ <stdin>:4:6: note: add '@MainActor' to make global function 'nonIsolated()' part of global actor 'MainActor' func nonIsolated() { ^ @MainActor
(edited)@MainActor struct View { init() {} } func nonIsolated() { _ = View() }
@MainActor struct View { init() {} } func nonIsolated() { _ = View() }
<stdin>:6:7: error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context _ = View() ^ <stdin>:2:3: note: calls to initializer 'init()' from outside of its actor context are implicitly asynchronous init() {} ^ <stdin>:5:6: note: add '@MainActor' to make global function 'nonIsolated()' part of global actor 'MainActor' func nonIsolated() { ^ @MainActor
@MainActor(unsafe) class View { init() {} var foo = 0 } @MainActor final class MyView: View { override init() { super.init() foo = 2 } }
(edited)@MainActor @objc class View { init() {} } func nonIsolated() { _ = View() }
(edited)@MainActor @objc class View { init() {} } func nonIsolated() { _ = View() }
(edited)<stdin>:1:13: error: Objective-C interoperability is disabled @MainActor @objc class View { ~^~~~~ <stdin>:6:7: error: call to main actor-isolated initializer 'init()' in a synchronous nonisolated context _ = View() ^ <stdin>:2:3: note: calls to initializer 'init()' from outside of its actor context are implicitly asynchronous init() {} ^ <stdin>:5:6: note: add '@MainActor' to make global function 'nonIsolated()' part of global actor 'MainActor' func nonIsolated() { ^ @MainActor
(edited)@MainActor(unsafe) struct View { init() {} } func nonIsoalted() { _ = View() }
@MainActor(unsafe) struct View { init() {} } func nonIsoalted() { _ = View() }
class MyView: UIView { init() { super.init(frame: .zero) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
(edited)import Foundation let dateS = "2022-03-08T15:00:00.000Z" let f = ISO8601DateFormatter() var c = Calendar(identifier: .gregorian) c.timeZone = .init(secondsFromGMT: 9 * 3600)! let todayDay = c.component(.day, from: f.date(from: dateS)!) print(todayDay)
(edited)import Foundation let dateS = "2022-03-08T15:00:00.000Z" let f = ISO8601DateFormatter() var c = Calendar(identifier: .gregorian) c.timeZone = .init(secondsFromGMT: 9 * 3600)! let todayDay = c.component(.day, from: f.date(from: dateS)!) print(todayDay)
(edited)main/<stdin>:9: Fatal error: Unexpectedly found nil while unwrapping an Optional value Current stack trace: 0 libswiftCore.so 0x00007f40da08a920 _swift_stdlib_reportFatalErrorInFile + 112 1 libswiftCore.so 0x00007f40d9d822f1 <unavailable> + 1417969 2 libswiftCore.so 0x00007f40d9d82016 <unavailable> + 1417238 3 libswiftCore.so 0x00007f40d9d81e0a <unavailable> + 1416714 4 libswiftCore.so 0x00007f40d9d81840 _assertionFailure(_:_:file:line:flags:) + 315 6 swift-frontend 0x000000000068ff2a <unavailable> + 2686762 7 swift-frontend 0x0000000000547e4c <unavailable> + 1343052 8 swift-frontend 0x0000000000509396 <unavailable> + 1086358 9 swift-frontend 0x0000000000508a90 <unavailable> + 1084048 10 swift-frontend 0x00000000004fd2a4 <unavailable> + 1036964 11 swift-frontend 0x00000000004b3814 <unavailable> + 735252 12 libc.so.6 0x00007f40d86c3ba0 __libc_start_main + 231 13 swift-frontend 0x00000000004b326a <unavailable> + 733802 Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6-dev (LLVM 016ddf3ba9bf6cf, Swift a43b04fe3d5feea) 2. Compiling with the current language version 3. While running user code "<stdin>" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5fa5993] /usr/bin/swift-frontend[0x5fa353e] /usr/bin/swift-frontend[0x5fa5d26] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f40da455980] /usr/lib/swift/linux/libswiftCore.so(+0x15a2f5)[0x7f40d9d822f5] /usr/lib/swift/l
(edited)import Foundation let dateS = "2022-03-08T15:00:00.000Z" let f = ISO8601DateFormatter() var c = Calendar(identifier: .gregorian) // c.timeZone = .init(secondsFromGMT: 9 * 3600)! let todayDay = c.component(.day, from: f.date(from: dateS)!) print(todayDay)
import Foundation let dateS = "2022-03-08T15:00:00.000Z" let f = ISO8601DateFormatter() var c = Calendar(identifier: .gregorian) // c.timeZone = .init(secondsFromGMT: 9 * 3600)! let todayDay = c.component(.day, from: f.date(from: dateS)!) print(todayDay)
main/<stdin>:9: Fatal error: Unexpectedly found nil while unwrapping an Optional value Current stack trace: 0 libswiftCore.so 0x00007f29a022e920 _swift_stdlib_reportFatalErrorInFile + 112 1 libswiftCore.so 0x00007f299ff262f1 <unavailable> + 1417969 2 libswiftCore.so 0x00007f299ff26016 <unavailable> + 1417238 3 libswiftCore.so 0x00007f299ff25e0a <unavailable> + 1416714 4 libswiftCore.so 0x00007f299ff25840 _assertionFailure(_:_:file:line:flags:) + 315 6 swift-frontend 0x000000000068ff2a <unavailable> + 2686762 7 swift-frontend 0x0000000000547e4c <unavailable> + 1343052 8 swift-frontend 0x0000000000509396 <unavailable> + 1086358 9 swift-frontend 0x0000000000508a90 <unavailable> + 1084048 10 swift-frontend 0x00000000004fd2a4 <unavailable> + 1036964 11 swift-frontend 0x00000000004b3814 <unavailable> + 735252 12 libc.so.6 0x00007f299e867ba0 __libc_start_main + 231 13 swift-frontend 0x00000000004b326a <unavailable> + 733802 Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6-dev (LLVM 016ddf3ba9bf6cf, Swift a43b04fe3d5feea) 2. Compiling with the current language version 3. While running user code "<stdin>" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5fa5993] /usr/bin/swift-frontend[0x5fa353e] /usr/bin/swift-frontend[0x5fa5d26] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f29a05f9980] /usr/lib/swift/linux/libswiftCore.so(+0x15a2f5)[0x7f299ff262f5] /usr/lib/swift/l
!
でのクラッシュってこんなにうるさかったっけ (edited)let todayDay: Int? = nil print(todayDay!)
let todayDay: Int? = nil print(todayDay!)
main/<stdin>:2: Fatal error: Unexpectedly found nil while unwrapping an Optional value Current stack trace: 0 libswiftCore.so 0x00007fd0572de920 _swift_stdlib_reportFatalErrorInFile + 112 1 libswiftCore.so 0x00007fd056fd62f1 <unavailable> + 1417969 2 libswiftCore.so 0x00007fd056fd6016 <unavailable> + 1417238 3 libswiftCore.so 0x00007fd056fd5e0a <unavailable> + 1416714 4 libswiftCore.so 0x00007fd056fd5840 _assertionFailure(_:_:file:line:flags:) + 315 6 swift-frontend 0x000000000068ff2a <unavailable> + 2686762 7 swift-frontend 0x0000000000547e4c <unavailable> + 1343052 8 swift-frontend 0x0000000000509396 <unavailable> + 1086358 9 swift-frontend 0x0000000000508a90 <unavailable> + 1084048 10 swift-frontend 0x00000000004fd2a4 <unavailable> + 1036964 11 swift-frontend 0x00000000004b3814 <unavailable> + 735252 12 libc.so.6 0x00007fd055917ba0 __libc_start_main + 231 13 swift-frontend 0x00000000004b326a <unavailable> + 733802 Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6-dev (LLVM 016ddf3ba9bf6cf, Swift a43b04fe3d5feea) 2. Compiling with the current language version 3. While running user code "<stdin>" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5fa5993] /usr/bin/swift-frontend[0x5fa353e] /usr/bin/swift-frontend[0x5fa5d26] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7fd0576a9980] /usr/lib/swift/linux/libswiftCore.so(+0x15a2f5)[0x7fd056fd62f5] /usr/lib/swift/l
View
)が、親のnon-isolated initializer(Base.init(tag: ())
)を持つことBase.init(tag: ())
がActor IsolatedでないことView
を継承した型( MyView
)でinit(tag: ())
を定義すると、 Base.init(tag: ())
のActor情報を引き継ぐことView
)が、親のnon-isolated initializer(Base.init(tag: ())
)を持つことBase.init(tag: ())
がActor IsolatedでないことView
を継承した型( MyView
)でinit(tag: ())
を定義すると、 Base.init(tag: ())
のActor情報を引き継ぐことfunc foo() -> Optional<some Equatable> { return .some(100) }
func foo() -> Optional<some Equatable> { return .some(100) }
enum MyOptional<Wrapped> { case some(Wrapped) case none } func foo() -> MyOptional<some Equatable> { return .some(100) }
enum MyOptional<Wrapped> { case some(Wrapped) case none } func foo() -> MyOptional<some Equatable> { return .some(100) }
Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6-dev (LLVM 016ddf3ba9bf6cf, Swift a43b04fe3d5feea) 2. Compiling with the current language version 3. While evaluating request ASTLoweringRequest(Lowering AST to SIL for module main) Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5fa5993] /usr/bin/swift-frontend[0x5fa353e] /usr/bin/swift-frontend[0x5fa5d26] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7fcebcb85980] /usr/bin/swift-frontend[0x4b5ef0] /usr/bin/swift-frontend[0x5f8372c] /usr/bin/swift-frontend[0x1e48e60] /usr/bin/swift-frontend[0x1e480c6] /usr/bin/swift-frontend[0x18b7f21] /usr/bin/swift-frontend[0x18af8b8] /usr/bin/swift-frontend[0x18b8c5c] /usr/bin/swift-frontend[0x18b376a] /usr/bin/swift-frontend[0x18b9460] /usr/bin/swift-frontend[0x18b40d7] /usr/bin/swift-frontend[0x18bcc94] /usr/bin/swift-frontend[0x18b7105] /usr/bin/swift-frontend[0x18af8c8] /usr/bin/swift-frontend[0x18b8c5c] /usr/bin/swift-frontend[0x18b376a] /usr/bin/swift-frontend[0x18b9460] /usr/bin/swift-frontend[0x18b40d7] /usr/bin/swift-frontend[0x18bcc94] /usr/bin/swift-frontend[0x18b7105] /usr/bin/swift-frontend[0x18af8c8] /usr/bin/swift-frontend[0x18b8c5c] /usr/bin/swift-frontend[0x18b376a] /usr/bin/swift-frontend[0x18b9460] /usr/bin/swift-frontend[0x18b40d7] /usr/bin/swift-frontend[0x18bcc94] /usr/bin/swift-frontend[0x18b7105] /usr/bin/swift-frontend[0x18af8c8] /usr/bin/swift-frontend[0x18b8c5c] /usr/bin/swift-frontend[0x18b376a] /usr/bin/swift-frontend[0x18b9460] /usr/bin/swift-frontend[0x18b40d7] /usr/bin/swift-frontend[0x18bcc94] /usr/bin/swift-frontend[0x18b7105] /usr/bin/swift-frontend[0x18af8c8] /usr/bin/swift-frontend[0x18b8c5c] /usr/bin/swift-frontend[0x18b376a]
import Foundation func proc(count: Int, idx: Int) { var st = Set<Int>() for i in 0..<count { st.insert(i) } let mid = count >> 1 let start = Date() st.remove(mid) let elapsed = Date().timeIntervalSince(start) print(idx, elapsed) } for d in 1...7 { let c = (pow(10, d) as NSDecimalNumber).intValue proc(count: c, idx: d) }
import Foundation func proc(count: Int, idx: Int) { var st = Set<Int>() for i in 0..<count { st.insert(i) } let mid = count >> 1 let start = Date() st.remove(mid) let elapsed = Date().timeIntervalSince(start) print(idx, elapsed) } for d in 1...7 { let c = (pow(10, d) as NSDecimalNumber).intValue proc(count: c, idx: d) }
1 4.0531158447265625e-06 2 9.5367431640625e-07 3 0.0 4 9.5367431640625e-07 5 2.0265579223632812e-06 6 1.0728836059570312e-06 7 2.0265579223632812e-06
swift-5.7
ボットを用意する時期。 順当に行くと 4.2.4のインスタンスを再利用だけど、メジャーバージョン違いは残した方が良い気も (edited)print("Hello")
print("Hello")
<unknown>:0: error: unknown argument: '--swift-version'
OVERVIEW: Swift compiler USAGE: swift [options] <inputs> OPTIONS: -assert-config <value> Specify the assert_configuration replacement. Possible values are Debug, Release, Unchecked, DisableReplacement. -continue-building-after-errors Continue building, even after errors are encountered -debug-info-format=<value> Specify the debug info format type to either 'dwarf' or 'codeview' -debug-info-store-invocation Emit the compiler invocation in the debug info. -debug-prefix-map <value> Remap source paths in debug info -D <value> Marks a conditional compilation flag as true -enforce-exclusivity=<enforcement> Enforce law of exclusivity -framework <value> Specifies a framework which should be linked against -Fsystem <value> Add directory to system framework search path -F <value> Add directory to framework search path -gdwarf-types Emit full DWARF type info. -gline-tables-only Emit minimal debug info for backtraces only -gnone Don't emit debug info -g Emit debug info. This is the preferred setting for debugging with LLDB. -help Display available options -index-store-path <path> Store indexing data to <path> -I <value> Add directory to the import search path -j <n> Number of commands to execute in parallel -L <value> Add directory to library link search path -l<value> Specifies a library which should be linked against -module-cache-path <value> Specifies the Clang module cache path -module-link-name <value> Library to link against when using this module -module-name <value> Name of the module to build -nostdimport Don't search the standard
print(1)
(edited)print(1)
(edited)<unknown>:0: error: unknown argument: '--swift-version'
(edited)print(2)
#if swift(5.0) print(5) #else print(4) #endif
#if swift(5.0) print(5) #else print(4) #endif
<stdin>:1:11: error: unexpected platform condition argument: expected a unary comparison '>=' or '<'; for example, '>=2.2' or '<2.2' #if swift(5.0) ^
print(42)
print(42)
<unknown>:0: error: invalid value '6' in '-swift-version 6' <unknown>:0: note: valid arguments to '-swift-version' are '4', '4.2', '5'
print(42)
class Foo { func bar(v: Int) { print("bar: \(v)") } } protocol FooProtocol: Foo {} extension Foo: FooProtocol {} func f() { let foo = Foo() FooProtocol.bar(foo)(v: 1) }
(edited)class Foo { func bar(v: Int) { print("bar: \(v)") } } protocol FooProtocol: Foo {} extension Foo: FooProtocol {} func f() { let foo = Foo() FooProtocol.bar(foo)(v: 1) }
(edited)not existential UNREACHABLE executed at /home/build-user/swift/lib/SILGen/SILGenConvert.cpp:992! Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7-dev (LLVM aac709978dda363, Swift 8c308d0ff137dde) 2. Compiling with the current language version 3. While evaluating request ASTLoweringRequest(Lowering AST to SIL for module main) 4. While silgen emitFunction SIL function "@$s4main1fyyF". for 'f()' (at <stdin>:8:1) Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x62f7253] /usr/bin/swift-frontend[0x62f4dfe] /usr/bin/swift-frontend[0x62f75e6] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f89645e5980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7f8962858e87] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7f896285a7f1] /usr/bin/swift-frontend[0x622c8f6] /usr/bin/swift-frontend[0xc7ac93] /usr/bin/swift-frontend[0xca27db] /usr/bin/swift-frontend[0xcb2a17] /usr/bin/swift-frontend[0xca6321] /usr/bin/swift-frontend[0xc98839] /usr/bin/swift-frontend[0xd55d00] /usr/bin/swift-frontend[0xd3a9d6] /usr/bin/swift-frontend[0xd3a6ed] /usr/bin/swift-frontend[0xca3d14] /usr/bin/swift-frontend[0xc98839] /usr/bin/swift-frontend[0xd55d00] /usr/bin/swift-frontend[0xd3a9d6] /usr/bin/swift-frontend[0xd3a6ed] /usr/bin/swift-frontend[0xca3d14] /usr/bin/swift-frontend[0xc98c7e] /usr/bin/swift-frontend[0xd08eb3] /usr/bin/swift-frontend[0xd0872d] /usr/bin/swift-frontend[0xcbc3ac] /usr/bin/swift-frontend[0xc4e952] /usr/bin/swift-frontend[0xc50cc0] /usr/bin/swift-frontend[0xc4ca87] /usr/bin/swift-frontend[0xc53a24] /usr/bin/swift-frontend[0xd08142] /usr/bin/swift-frontend[0xc57de6] /usr/bin/swift-frontend[0xc54f54] /usr/bin/swift-frontend[0x5c7b4e] /usr/bin/sw
class Foo { func bar(v: Int) { print("bar: \(v)") } } protocol FooProtocol: Foo {} extension Foo: FooProtocol {} func f() { let foo = Foo() FooProtocol.bar(foo)(v: 1) }
(edited)not existential UNREACHABLE executed at /home/buildnode/jenkins/workspace/oss-swift-5.5-package-linux-ubuntu-18_04/swift/lib/SILGen/SILGenConvert.cpp:984! Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.5.3 (swift-5.5.3-RELEASE) 2. 3. While evaluating request ASTLoweringRequest(Lowering AST to SIL for module main) 4. While silgen emitFunction SIL function "@$s4main1fyyF". for 'f()' (at <stdin>:8:1) Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5c5feb3] /usr/bin/swift-frontend[0x5c5dc0e] /usr/bin/swift-frontend[0x5c6023c] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f05c44b9980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7f05c2d5be87] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7f05c2d5d7f1] /usr/bin/swift-frontend[0x5ba1536] /usr/bin/swift-frontend[0xce721e] /usr/bin/swift-frontend[0xd0793b] /usr/bin/swift-frontend[0xd17277] /usr/bin/swift-frontend[0xd0a9d0] /usr/bin/swift-frontend[0xcfe2c9] /usr/bin/swift-frontend[0xdbba62] /usr/bin/swift-frontend[0xd9fda9] /usr/bin/swift-frontend[0xd08e14] /usr/bin/swift-frontend[0xcfe2c9] /usr/bin/swift-frontend[0xdbba62] /usr/bin/swift-frontend[0xd9fda9] /usr/bin/swift-frontend[0xd08e14] /usr/bin/swift-frontend[0xcfe749] /usr/bin/swift-frontend[0xd71be4] /usr/bin/swift-frontend[0xd71a0d] /usr/bin/swift-frontend[0xd20fe5] /usr/bin/swift-frontend[0xcbd30e] /usr/bin/swift-frontend[0xcbf594] /usr/bin/swift-frontend[0xcbb842] /usr/bin/swift-frontend[0xcc20d1] /usr/bin/swift-frontend[0xd71452] /usr/bin/swift-frontend[0xcc62b1] /usr/bin/swift-frontend[0xcc3234] /usr/bin/swift-fronte
class EventLoopFuture<T> { func get() async throws -> T { fatalError() } } protocol Database { func transaction<T>(_ closure: @escaping (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> } extension Database { func transaction<T>(_ closure: @Sendable @escaping (Database) async throws -> T) async throws -> T { try await self.transaction { db -> EventLoopFuture<T> in fatalError() }.get() } }
(edited)class EventLoopFuture<T> { func get() async throws -> T { fatalError() } } protocol Database { func transaction<T>(_ closure: @escaping (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> } extension Database { func transaction<T>(_ closure: @Sendable @escaping (Database) async throws -> T) async throws -> T { try await self.transaction { db -> EventLoopFuture<T> in fatalError() }.get() } }
(edited)class EventLoopFuture<T> { func get() async throws -> T { fatalError() } } struct Database { func transaction<T>(_ closure: @escaping (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> { closure(self) } } extension Database { func transaction<T>(_ closure: @Sendable @escaping (Database) async throws -> T) async throws -> T { try await self.transaction { db -> EventLoopFuture<T> in fatalError() }.get() } }
(edited)class EventLoopFuture<T> { func get() async throws -> T { fatalError() } } struct Database { func transaction<T>(_ closure: @escaping (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> { closure(self) } } extension Database { func transaction<T>(_ closure: @Sendable @escaping (Database) async throws -> T) async throws -> T { try await self.transaction { db -> EventLoopFuture<T> in fatalError() }.get() } }
(edited)<stdin>:12:19: error: ambiguous use of 'transaction' try await self.transaction { db -> EventLoopFuture<T> in ^ <stdin>:5:10: note: found this candidate func transaction<T>(_ closure: @escaping (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> { ^ <stdin>:11:10: note: found this candidate func transaction<T>(_ closure: @Sendable @escaping (Database) async throws -> T) async throws -> T { ^
(edited)protocol P<A> { associatedtype A } protocol Q {} struct S<A>: P {} struct K: Q {} func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { (S<K>(), S<K>()) } func usePair<T: Q>(_ pair: (S<T>, S<T>)) {} func main() { let pair = makePair() usePair(pair) }
protocol P<A> { associatedtype A } protocol Q {} struct S<A>: P {} struct K: Q {} func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { (S<K>(), S<K>()) } func usePair<T: Q>(_ pair: (S<T>, S<T>)) {} func main() { let pair = makePair() usePair(pair) }
<stdin>:1:11: error: protocols do not allow generic parameters; use associated types instead protocol P<A> { ^ <stdin>:9:20: error: expected type for function result func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^ <stdin>:9:19: error: consecutive statements on a line must be separated by ';' func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^ ; <stdin>:9:23: error: consecutive statements on a line must be separated by ';' func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^ ; <stdin>:9:23: error: expected expression func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^ <stdin>:9:50: error: top-level statement cannot begin with a closure expression func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^ <stdin>:9:6: error: expected '{' in body of function declaration func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^ <stdin>:9:20: error: '<' is not a prefix unary operator func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^ <stdin>:9:21: error: cannot find 'T0' in scope func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^~ <stdin>:9:50: error: closure expression is unused func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^ <stdin>:9:50: note: did you mean to use a 'do' statement? func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { ^ do <stdin>:16:9: warning: constant 'pair' inferred to have type '()', which may be unexpected let pair = makePair() ^ <stdin>:16:9: note: add an explicit type annotation to silence this warning let pair = makePair() ^ : () <stdin>:17:5: error: generic parameter 'T' could not be inferred usePair(pa
protocol P<A> { associatedtype A } protocol Q {} struct S<A>: P {} struct K: Q {} func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { (S<K>(), S<K>()) } func usePair<T: Q>(_ pair: (S<T>, S<T>)) {} func main() { let pair = makePair() usePair(pair) }
protocol P<A> { associatedtype A } protocol Q {} struct S<A>: P {} struct K: Q {} func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { (S<K>(), S<K>()) } func usePair<T: Q>(_ pair: (S<T>, S<T>)) {} func main() { let pair = makePair() usePair(pair) }
<stdin>:1:11: error: protocols do not allow generic parameters; use associated types instead protocol P<A> { ^ swift-frontend: /home/build-user/swift/lib/Sema/CSSimplify.cpp:3221: ConstraintSystem::TypeMatchResult swift::constraints::ConstraintSystem::matchDeepEqualityTypes(swift::Type, swift::Type, swift::constraints::ConstraintLocatorBuilder): Assertion `opaque1->getCanonicalInterfaceType(arch1->getInterfaceType())->isEqual( opaque2->getCanonicalInterfaceType(arch2->getInterfaceType()))' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -enable-experimental-named-opaque-types -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7-dev (LLVM aac709978dda363, Swift 8c308d0ff137dde) 2. Compiling with the current language version 3. While evaluating request TypeCheckSourceFileRequest(source_file "<stdin>") 4. While evaluating request TypeCheckFunctionBodyRequest(main.(file).main()@<stdin>:15:6) 5. While type-checking statement at [<stdin>:15:13 - line:18:1] RangeText="{ let pair = makePair() usePair(pair) " 6. While type-checking expression at [<stdin>:17:5 - line:17:17] RangeText="usePair(pair" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x62f7253] /usr/bin/swift-frontend[0x62f4dfe] /usr/bin/swift-frontend[0x62f75e6] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f70ed252980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7f70eb4c5e87] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7f70eb4c77f1] /lib/x86_64-linux-gnu/libc.so.6(+0x303fa)[0x7f70eb4b73fa] /lib/x86_64-linux-gnu/libc.so.6(+0x30472)[0x7f70eb4b7472] /usr/bin/swift-frontend[0x13579fe] /usr/bin/swift-frontend[0x137e7d5] /usr/bin/swift-frontend[0x1363e37] /usr/bin/swift-frontend[0x1351451] /usr/bin
protocol P<A> { associatedtype A } protocol Q {} struct S<A>: P {} struct K: Q {} func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { (S<K>(), S<K>()) } func usePair<T: Q>(_ pair: (S<T>, S<T>)) {} func main() { let pair = makePair() usePair(pair) }
protocol P<A> { associatedtype A } protocol Q {} struct S<A>: P {} struct K: Q {} func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { (S<K>(), S<K>()) } func usePair<T: Q>(_ pair: (S<T>, S<T>)) {} func main() { let pair = makePair() usePair(pair) }
<unknown>:0: error: unknown argument: '-enable-parameterized-existential-types'
protocol P<A> { associatedtype A } protocol Q {} struct S<A>: P {} struct K: Q {} func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { (S<K>(), S<K>()) } func usePair<T: Q>(_ pair: (S<T>, S<T>)) {} func main() { let pair = makePair() usePair(pair) }
protocol P<A> { associatedtype A } protocol Q {} struct S<A>: P {} struct K: Q {} func makePair() -> <T0: Q, T1: Q> (S<T0>, S<T1>) { (S<K>(), S<K>()) } func usePair<T: Q>(_ pair: (S<T>, S<T>)) {} func main() { let pair = makePair() usePair(pair) }
swift-frontend: /home/build-user/swift/lib/Sema/CSSimplify.cpp:3221: ConstraintSystem::TypeMatchResult swift::constraints::ConstraintSystem::matchDeepEqualityTypes(swift::Type, swift::Type, swift::constraints::ConstraintLocatorBuilder): Assertion `opaque1->getCanonicalInterfaceType(arch1->getInterfaceType())->isEqual( opaque2->getCanonicalInterfaceType(arch2->getInterfaceType()))' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -enable-experimental-named-opaque-types -enable-parameterized-protocol-types -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7-dev (LLVM aac709978dda363, Swift 8c308d0ff137dde) 2. Compiling with the current language version 3. While evaluating request TypeCheckSourceFileRequest(source_file "<stdin>") 4. While evaluating request TypeCheckFunctionBodyRequest(main.(file).main()@<stdin>:15:6) 5. While type-checking statement at [<stdin>:15:13 - line:18:1] RangeText="{ let pair = makePair() usePair(pair) " 6. While type-checking expression at [<stdin>:17:5 - line:17:17] RangeText="usePair(pair" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x62f7253] /usr/bin/swift-frontend[0x62f4dfe] /usr/bin/swift-frontend[0x62f75e6] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7fdc4ba8b980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7fdc49cfee87] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7fdc49d007f1] /lib/x86_64-linux-gnu/libc.so.6(+0x303fa)[0x7fdc49cf03fa] /lib/x86_64-linux-gnu/libc.so.6(+0x30472)[0x7fdc49cf0472] /usr/bin/swift-frontend[0x13579fe] /usr/bin/swift-frontend[0x137e7d5] /usr/bin/swift-frontend[0x1363e37] /usr/bin/swift-frontend[0x1351451] /usr/bin/swift-frontend[0x1357c11] /usr/bin/swift-frontend[0x13573c8] /usr/bin/swift-fronten
public protocol P<A> { associatedtype A } struct S1<A>: P {} struct S2<A>: P {} public func makeP() -> <T: P, U: P where T.A == U.A> (T, U) { return (S1<Int>(), S2<Int>()) } public func useSame<T>(_ a: T, _ b: T) {} func main() { let pair = makeP() useSame(type(of: pair.0).A.self, type(of: pair.1).A.self) }
public protocol P<A> { associatedtype A } struct S1<A>: P {} struct S2<A>: P {} public func makeP() -> <T: P, U: P where T.A == U.A> (T, U) { return (S1<Int>(), S2<Int>()) } public func useSame<T>(_ a: T, _ b: T) {} func main() { let pair = makeP() useSame(type(of: pair.0).A.self, type(of: pair.1).A.self) }
public protocol P<A> { associatedtype A } struct S1<A>: P {} struct S2<A>: P {} public func makeP() -> <T: P, U: P> (T, U) { return (S1<Int>(), S2<Int>()) } public func useSame<T>(_ a: T, _ b: T) {} func main() { let pair = makeP() useSame(type(of: pair.0).A.self, type(of: pair.1).A.self) }
public protocol P<A> { associatedtype A } struct S1<A>: P {} struct S2<A>: P {} public func makeP() -> <T: P, U: P> (T, U) { return (S1<Int>(), S2<Int>()) } public func useSame<T>(_ a: T, _ b: T) {} func main() { let pair = makeP() useSame(type(of: pair.0).A.self, type(of: pair.1).A.self) }
swift-frontend: /home/build-user/swift/lib/Sema/CSSimplify.cpp:3221: ConstraintSystem::TypeMatchResult swift::constraints::ConstraintSystem::matchDeepEqualityTypes(swift::Type, swift::Type, swift::constraints::ConstraintLocatorBuilder): Assertion `opaque1->getCanonicalInterfaceType(arch1->getInterfaceType())->isEqual( opaque2->getCanonicalInterfaceType(arch2->getInterfaceType()))' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -enable-experimental-named-opaque-types -enable-parameterized-protocol-types -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7-dev (LLVM aac709978dda363, Swift 8c308d0ff137dde) 2. Compiling with the current language version 3. While evaluating request TypeCheckSourceFileRequest(source_file "<stdin>") 4. While evaluating request TypeCheckFunctionBodyRequest(main.(file).main()@<stdin>:14:6) 5. While type-checking statement at [<stdin>:14:13 - line:17:1] RangeText="{ let pair = makeP() useSame(type(of: pair.0).A.self, type(of: pair.1).A.self) " 6. While type-checking expression at [<stdin>:16:5 - line:16:61] RangeText="useSame(type(of: pair.0).A.self, type(of: pair.1).A.self" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x62f7253] /usr/bin/swift-frontend[0x62f4dfe] /usr/bin/swift-frontend[0x62f75e6] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f3c6f6d7980] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xc7)[0x7f3c6d94ae87] /lib/x86_64-linux-gnu/libc.so.6(abort+0x141)[0x7f3c6d94c7f1] /lib/x86_64-linux-gnu/libc.so.6(+0x303fa)[0x7f3c6d93c3fa] /lib/x86_64-linux-gnu/libc.so.6(+0x30472)[0x7f3c6d93c472] /usr/bin/swift-frontend[0x13579fe] /usr/bin/swift-frontend[0x137e7d5] /usr/bin/swift-frontend[0x1363e37] /usr/bin/swift-frontend[0x1351451] /usr/bi
Swift version 5.8-dev (LLVM 2974a4eff23971f, Swift 0bf6fc311e973a8) Target: x86_64-unknown-linux-gnu
Swift version 5.6.1 (swift-5.6.1-RELEASE) Target: x86_64-unknown-linux-gnu
swift-nightly
ではなくswift-main
とボットに名乗らせた方が分かりやすいかな? (edited)protocol P<A> { associatedtype A } struct S<A>: P {} func f<T>() -> any P<T> { S() }
protocol P<A> { associatedtype A } struct S<A>: P {} func f<T>() -> any P<T> { S() }
protocol P { func foo() -> Int } struct S: P { func foo() -> Int { 42 } } func useP(_ p: some P) { print(p.foo()) } let p: any P = S() useP(p)
(edited)protocol P { func foo() -> Int } struct S: P { func foo() -> Int { 42 } } func useP(_ p: some P) { print(p.foo()) } let p: any P = S() useP(p)
(edited)42
(edited)protocol P { func foo() -> Int } struct S: P { func foo() -> Int { 42 } } func useP<T: P>(_ p: T) -> T { p } let p: any P = S() let q: any P = useP(p) print(q.foo())
(edited)protocol P { func foo() -> Int } struct S: P { func foo() -> Int { 42 } } func useP<T: P>(_ p: T) -> T { p } let p: any P = S() let q: any P = useP(p) print(q.foo())
(edited)42
(edited)protocol P { func foo() -> Int } struct S: P { func foo() -> Int { 42 } } func useP<T: P>(_ p: T) -> T? { p } let p: any P = S() let q: (any P)? = useP(p) print(q?.foo() as Any)
(edited)protocol P { func foo() -> Int } struct S: P { func foo() -> Int { 42 } } func useP<T: P>(_ p: T) -> T? { p } let p: any P = S() let q: (any P)? = useP(p) print(q?.foo() as Any)
(edited)Optional(42)
(edited)protocol P { func foo() -> Int } struct S: P { func foo() -> Int { 42 } } func useP<T: P>(_ p: T) -> (T, T) { (p, p) } let p: any P = S() let q = useP(p) print(type(of: q)) print(q)
protocol P { func foo() -> Int } struct S: P { func foo() -> Int { 42 } } func useP<T: P>(_ p: T) -> (T, T) { (p, p) } let p: any P = S() let q = useP(p) print(type(of: q)) print(q)
(P, P) (main.S(), main.S())
protocol View { } struct FooView: View { } struct BarView: View { } struct TupleView<T>: View { let content: T init(_ content: T) { self.content = content } } func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> TupleView<(C0, C1)> where C0 : View, C1 : View { TupleView((c0, c1)) } let view0 = FooView() let view1 = BarView() print(buildBlock(view0, view1))
(edited)protocol View { } struct FooView: View { } struct BarView: View { } struct TupleView<T>: View { let content: T init(_ content: T) { self.content = content } } func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> TupleView<(C0, C1)> where C0 : View, C1 : View { TupleView((c0, c1)) } let view0 = FooView() let view1 = BarView() print(buildBlock(view0, view1))
(edited)TupleView<(FooView, BarView)>(content: (main.FooView(), main.BarView()))
(edited)protocol View { } struct FooView: View { } struct BarView: View { } struct TupleView<T>: View { let content: T init(_ content: T) { self.content = content } } func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> TupleView<(C0, C1)> where C0 : View, C1 : View { TupleView((c0, c1)) } let view0: any View = FooView() let view1: any View = BarView() print(buildBlock(view0, view1))
protocol View { } struct FooView: View { } struct BarView: View { } struct TupleView<T>: View { let content: T init(_ content: T) { self.content = content } } func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> TupleView<(C0, C1)> where C0 : View, C1 : View { TupleView((c0, c1)) } let view0: any View = FooView() let view1: any View = BarView() print(buildBlock(view0, view1))
<stdin>:23:7: error: type 'any View' cannot conform to 'View' print(buildBlock(view0, view1)) ^ <stdin>:23:7: note: only concrete types such as structs, enums and classes can conform to protocols print(buildBlock(view0, view1)) ^ <stdin>:17:6: note: required by global function 'buildBlock' where 'C0' = 'any View' func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> TupleView<(C0, C1)> where C0 : View, C1 : View { ^ <stdin>:23:7: error: type 'any View' cannot conform to 'View' print(buildBlock(view0, view1)) ^ <stdin>:23:7: note: only concrete types such as structs, enums and classes can conform to protocols print(buildBlock(view0, view1)) ^ <stdin>:17:6: note: required by global function 'buildBlock' where 'C1' = 'any View' func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> TupleView<(C0, C1)> where C0 : View, C1 : View { ^
protocol View { } struct FooView: View { } struct BarView: View { } func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) where C0 : View, C1 : View { } let view0: any View = FooView() let view1: any View = BarView() buildBlock(view0, view1)
protocol View { } struct FooView: View { } struct BarView: View { } func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) where C0 : View, C1 : View { } let view0: any View = FooView() let view1: any View = BarView() buildBlock(view0, view1)
protocol View { } struct FooView: View { } struct BarView: View { } struct TupleView<T>: View { let content: T init(_ content: T) { self.content = content } } func buildBlock<C0>(_ c0: C0) -> TupleView<(C0)> where C0 : View { TupleView(c0) } let view0: any View = FooView() print(buildBlock(view0))
protocol View { } struct FooView: View { } struct BarView: View { } struct TupleView<T>: View { let content: T init(_ content: T) { self.content = content } } func buildBlock<C0>(_ c0: C0) -> TupleView<(C0)> where C0 : View { TupleView(c0) } let view0: any View = FooView() print(buildBlock(view0))
<stdin>:22:7: error: type 'any View' cannot conform to 'View' print(buildBlock(view0)) ^ <stdin>:22:7: note: only concrete types such as structs, enums and classes can conform to protocols print(buildBlock(view0)) ^ <stdin>:17:6: note: required by global function 'buildBlock' where 'C0' = 'any View' func buildBlock<C0>(_ c0: C0) -> TupleView<(C0)> where C0 : View { ^
@differentiable func f(_ x: Float) -> Float { x * x } let dfdx = derivative(of: f) print(dfdx(3))
@differentiable func f(_ x: Float) -> Float { x * x } let dfdx = derivative(of: f) print(dfdx(3))
<stdin>:1:16: warning: '@differentiable' has been renamed to '@differentiable(reverse)' and will be removed in the next release @differentiable ^ (reverse) <stdin>:1:2: error: @differentiable attribute used without importing module '_Differentiation' @differentiable ~^~~~~~~~~~~~~~ <stdin>:5:12: error: cannot find 'derivative' in scope let dfdx = derivative(of: f) ^~~~~~~~~~
import _Differentiation @differentiable(reverse) func f(_ x: Float) -> Float { x * x } let dfdx = derivative(of: f) print(dfdx(3))
import _Differentiation @differentiable(reverse) func f(_ x: Float) -> Float { x * x } let dfdx = derivative(of: f) print(dfdx(3))
_Differentiation/DifferentiationUtilities.swift:40: Fatal error: JVP does not exist. Use '-Xfrontend -enable-experimental-forward-mode-differentiation' to enable differential-first differentiation APIs. Current stack trace: 0 libswiftCore.so 0x00007f6de6bc2920 _swift_stdlib_reportFatalErrorInFile + 112 1 libswiftCore.so 0x00007f6de68baa6c <unavailable> + 1419884 2 libswiftCore.so 0x00007f6de68ba893 <unavailable> + 1419411 3 libswiftCore.so 0x00007f6de68b93a0 _assertionFailure(_:_:file:line:flags:) + 411 4 libswift_Differentiation.so 0x00007f6de2df9ec4 <unavailable> + 163524 7 libswift_Differentiation.so 0x00007f6de2df82a0 valueWithDifferential<A, B>(at:of:) + 106 8 libswift_Differentiation.so 0x00007f6de2df8720 differential<A, B>(at:of:) + 93 9 libswift_Differentiation.so 0x00007f6de2df8a90 derivative<A, B>(at:of:) + 89 10 libswift_Differentiation.so 0x00007f6de2df96b8 <unavailable> + 161464 13 swift-frontend 0x00000000005ccbea <unavailable> + 1887210 14 swift-frontend 0x00000000004d3954 <unavailable> + 866644 15 swift-frontend 0x00000000004993b9 <unavailable> + 627641 16 swift-frontend 0x000000000049893d <unavailable> + 624957 17 swift-frontend 0x000000000048d508 <unavailable> + 578824 18 swift-frontend 0x00000000004463af <unavailable> + 287663 19 libc.so.6 0x00007f6de51fbba0 __libc_start_main + 231 20 swift-frontend 0x0000000000445dda <unavailable> + 286170 Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6.1 (swift-5.6.1-RELEASE) 2. Compiling with the current
import _Differentiation @differentiable(reverse) func f(_ x: Float) -> Float { x * x } let dfdx = derivative(of: f) print(dfdx(3))
import _Differentiation @differentiable(reverse) func f(_ x: Float) -> Float { x * x } let dfdx = derivative(of: f) print(dfdx(3))
6.0
import _Differentiation @differentiable(_forward) func f(_ x: Float) -> Float { x * x } let dfdx = derivative(of: f) print(dfdx(3))
import _Differentiation @differentiable(_forward) func f(_ x: Float) -> Float { x * x } let dfdx = derivative(of: f) print(dfdx(3))
<stdin>:3:17: error: unsupported differentiability kind '_forward'; only 'reverse' is supported @differentiable(_forward) ^~~~~~~~ reverse
swift-5.7-DEVELOPMENT-SNAPSHOT-*
を使った公式Dockerイメージが提供されないので、公式Dokcerイメージに依存しない形で作りました。 @swift-5.7.3 -version (edited)swift-5.7-DEVELOPMENT-SNAPSHOT-*
を使った公式Dockerイメージが提供されないので、公式Dokcerイメージに依存しない形で作りました。 @swift-5.7.3 -version (edited)Swift version 5.7-dev (LLVM 9fde71b269b42b8, Swift ddc46e1f5bd885d) Target: x86_64-unknown-linux-gnu
import Foundation @MainActor func run(action: @escaping @Sendable () -> Void) async { print("1") print(Thread.isMainThread) action() } Task { await run { print("action") print(Thread.isMainThread) } print("2") print(Thread.isMainThread) } RunLoop.main.run(until: Date().addingTimeInterval(0.3))
(edited)import Foundation @MainActor func run(action: @escaping @Sendable () -> Void) async { print("1") print(Thread.isMainThread) action() } Task { await run { print("action") print(Thread.isMainThread) } print("2") print(Thread.isMainThread) } RunLoop.main.run(until: Date().addingTimeInterval(0.3))
(edited)1 true action true 2 true
(edited)import Foundation @MainActor func run(action: @escaping @Sendable () -> Void) async { print("1") print(Thread.isMainThread) action() } Task { await run { print("action") print(Thread.isMainThread) } print("2") print(Thread.isMainThread) } RunLoop.main.run(until: Date().addingTimeInterval(0.3))
import Foundation @MainActor func run(action: @escaping @Sendable () -> Void) async { print("1") print(Thread.isMainThread) action() } Task { await run { print("action") print(Thread.isMainThread) } print("2") print(Thread.isMainThread) } RunLoop.main.run(until: Date().addingTimeInterval(0.3))
1 true action true 2 false
import Foundation @MainActor func run(action: @escaping @Sendable () -> Void) async { print("1") print(Thread.isMainThread) action() } Task { @MainActor in // 追加 await run { print("action") print(Thread.isMainThread) } print("2") print(Thread.isMainThread) } RunLoop.main.run(until: Date().addingTimeInterval(0.3))
import Foundation @MainActor func run(action: @escaping @Sendable () -> Void) async { print("1") print(Thread.isMainThread) action() } Task { @MainActor in // 追加 await run { print("action") print(Thread.isMainThread) } print("2") print(Thread.isMainThread) } RunLoop.main.run(until: Date().addingTimeInterval(0.3))
1 true action true 2 true
import Foundation protocol P: Sendable { func f() } final class C: P { @MainActor func f() { print(Thread.isMainThread) } } let c = C() let p: P = C() Task { print(Thread.isMainThread) await c.f() p.f() } RunLoop.main.run(until: Date().addingTimeInterval(0.3))
(edited)import Foundation protocol P: Sendable { func f() } final class C: P { @MainActor func f() { print(Thread.isMainThread) } } let c = C() let p: P = C() Task { print(Thread.isMainThread) await c.f() p.f() } RunLoop.main.run(until: Date().addingTimeInterval(0.3))
(edited)false true false
(edited)struct Foo {} protocol Bar { associatedtype Foos: Sequence where Foos.Element == Foo var foos: Foos { get } } struct Baz: Bar { var foos: [Foo] { [Foo()] } } let bar: any Bar = Baz() var iterator = (bar.foos as any Sequence).makeIterator() as any IteratorProtocol while let foo = iterator.next() { print(foo) }
(edited)struct Foo {} protocol Bar { associatedtype Foos: Sequence where Foos.Element == Foo var foos: Foos { get } } struct Baz: Bar { var foos: [Foo] { [Foo()] } } let bar: any Bar = Baz() var iterator = (bar.foos as any Sequence).makeIterator() as any IteratorProtocol while let foo = iterator.next() { print(foo) }
(edited)Foo()
(edited)struct Foo {} protocol Bar { associatedtype Foos: Sequence where Foos.Element == Foo var foos: Foos { get } } struct Baz: Bar { var foos: [Foo] { [Foo()] } } let bar: any Bar = Baz() for foo in bar.foos as any Sequence { print(foo) }
struct Foo {} protocol Bar { associatedtype Foos: Sequence where Foos.Element == Foo var foos: Foos { get } } struct Baz: Bar { var foos: [Foo] { [Foo()] } } let bar: any Bar = Baz() for foo in bar.foos as any Sequence { print(foo) }
Foo()
*.tar.gz
やDockerfile
に変化がなくても更新されてしまう様なので、無駄なボットの更新を避けるためDockerイメージへ依存しない今の仕組みのままでいきます。 (edited)extension Substring { /// Converts all `\"` to `"`. func unescapingDoubleQuotes() -> Substring { self.lazy.split(separator: "\\").reduce(into: "") { (result, part) in if result.isEmpty || part.first == "\"" { result += part } else { result += "\\" + part } } } }
extension Substring { /// Converts all `\"` to `"`. func unescapingDoubleQuotes() -> Substring { self.lazy.split(separator: "\\").reduce(into: "") { (result, part) in if result.isEmpty || part.first == "\"" { result += part } else { result += "\\" + part } } } }
<stdin>:4:14: error: ambiguous use of 'split(separator:maxSplits:omittingEmptySubsequences:)' self.lazy.split(separator: "\\").reduce(into: "") { (result, part) in ^ Swift.Sequence:2:40: note: found this candidate @inlinable public __consuming func split(separator: Self.Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [ArraySlice<Self.Element>] ^ Swift.Collection:2:40: note: found this candidate @inlinable public __consuming func split(separator: Self.Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [Self.SubSequence] ^
extension Substring { /// Converts all `\"` to `"`. func unescapingDoubleQuotes() -> Substring { self.lazy.split(separator: "\\").reduce(into: "") { (result, part) in if result.isEmpty || part.first == "\"" { result += part } else { result += "\\" + part } } } }
public protocol DependencyKey { associatedtype Value } public struct GenericDependencyKey<T>: DependencyKey { public typealias Value = T public init() {} } extension DependencyKey where Self == GenericDependencyKey<Value> { static var `default`: Self { GenericDependencyKey<Value>() } }
public protocol DependencyKey { associatedtype Value } public struct GenericDependencyKey<T>: DependencyKey { public typealias Value = T public init() {} } extension DependencyKey where Self == GenericDependencyKey<Value> { static var `default`: Self { GenericDependencyKey<Value>() } }
<stdin>:12:34: error: failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project static var `default`: Self { GenericDependencyKey<Value>() } ^
public protocol DependencyKey { associatedtype Value } public struct GenericDependencyKey<T>: DependencyKey { public typealias Value = T public init() {} } extension DependencyKey where Self == GenericDependencyKey<Value> { static var `default`: Self { GenericDependencyKey<Value>() } }
<stdin>:11:36: error: same-type constraint 'Self' == 'GenericDependencyKey<Self.Value>' is recursive extension DependencyKey where Self == GenericDependencyKey<Value> { ^
public protocol DependencyKey { associatedtype Value } public struct GenericDependencyKey<T>: DependencyKey { public typealias Value = T public init() {} } extension DependencyKey where Self == GenericDependencyKey<Value> { static var `default`: Self { GenericDependencyKey<Value>() } }
<stdin>:12:34: error: failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project static var `default`: Self { GenericDependencyKey<Value>() } ^
public protocol DependencyKey { associatedtype Value } public struct GenericDependencyKey<T>: DependencyKey { public typealias Value = T public init() {} } extension DependencyKey where Self == GenericDependencyKey<Value> { public static var `default`: GenericDependencyKey<Value> { .init() } }
(edited)public protocol DependencyKey { associatedtype Value } public struct GenericDependencyKey<T>: DependencyKey { public typealias Value = T public init() {} } extension DependencyKey where Self == GenericDependencyKey<Value> { public static var `default`: GenericDependencyKey<Value> { .init() } }
(edited)swift-frontend: /home/build-user/swift/include/swift/AST/ExprNodes.def:103: virtual std::pair<bool, Expr *> (anonymous namespace)::Verifier::walkToExprPre(swift::Expr *): Assertion `(HadError || !M.is<SourceFile*>() || M.get<SourceFile*>()->ASTStage < SourceFile::TypeChecked) && "UnresolvedMember" "in wrong phase"' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7-dev (LLVM fc0ab39bda0c879, Swift c6bb52ea2e91c0e) 2. Compiling with the current language version 3. While walking into decl extension of DependencyKey (at <stdin>:11:1) 4. While walking into body of getter for default (at <stdin>:12:23) Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x610e423] /usr/bin/swift-frontend[0x610c16e] /usr/bin/swift-frontend[0x610e7af] /lib/x86_64-linux-gnu/libpthread.so.0(+0x14420)[0x7f699e736420] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xcb)[0x7f699db8200b] /lib/x86_64-linux-gnu/libc.so.6(abort+0x12b)[0x7f699db61859] /lib/x86_64-linux-gnu/libc.so.6(+0x22729)[0x7f699db61729] /lib/x86_64-linux-gnu/libc.so.6(+0x33fd6)[0x7f699db72fd6] /usr/bin/swift-frontend[0x1a752b8] /usr/bin/swift-frontend[0x1a87d40] /usr/bin/swift-frontend[0x1a8a23f] /usr/bin/swift-frontend[0x1a89cb0] /usr/bin/swift-frontend[0x1a8cb36] /usr/bin/swift-frontend[0x1a8768e] /usr/bin/swift-frontend[0x1a8ba2c] /usr/bin/swift-frontend[0x1a8768e] /usr/bin/swift-frontend[0x1a8adb1] /usr/bin/swift-frontend[0x1a8afe2] /usr/bin/swift-frontend[0x1a8c133] /usr/bin/swift-frontend[0x1a8768e] /usr/bin/swift-frontend[0x1a8be45] /usr/bin/swift-frontend[0x1a8768e] /usr/bin/swift-frontend[0x1a87623] /usr/bin/swift-frontend[0x1c6e6a9] /usr/bin/swift-frontend[0x1a74a5d] /usr/bin/swift-fronten
(edited)public protocol DependencyKey { associatedtype Value } public struct GenericDependencyKey<T>: DependencyKey { public typealias Value = T public init() {} } extension DependencyKey where Self == GenericDependencyKey<Value> { public static var `default`: GenericDependencyKey<Value> { .init() } }
(edited)<stdin>:11:36: error: same-type constraint 'Self' == 'GenericDependencyKey<Self.Value>' is recursive extension DependencyKey where Self == GenericDependencyKey<Value> { ^
let regex = /-(.*?)\+/ print(type(of: regex))
(edited)let regex = /-(.*?)\+/ print(type(of: regex))
(edited)Regex<(Substring, Substring)>
(edited)import Foundation import CoreData @objc(Test) class Test: NSManagedObject { } extension Test { @NSManaged public var text: String } class Model: ObservableObject { @MainActor @Published var list: [Test] = [] init() { let container = NSPersistentContainer(name: "") NotificationCenter.default.addObserver( forName: NSManagedObjectContext.didChangeObjectsNotification, object: container.persistentStoreCoordinator, queue: nil ) { notification in if let updatedList = notification.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject> { for updated in updatedList { Task { if let i = await self.list.firstIndex(where: { $0.objectID == updated.objectID }) { await MainActor.run(body: { self.list[i].text = "Changed" }) } } } } } } }
import Foundation import CoreData @objc(Test) class Test: NSManagedObject { } extension Test { @NSManaged public var text: String } class Model: ObservableObject { @MainActor @Published var list: [Test] = [] init() { let container = NSPersistentContainer(name: "") NotificationCenter.default.addObserver( forName: NSManagedObjectContext.didChangeObjectsNotification, object: container.persistentStoreCoordinator, queue: nil ) { notification in if let updatedList = notification.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject> { for updated in updatedList { Task { if let i = await self.list.firstIndex(where: { $0.objectID == updated.objectID }) { await MainActor.run(body: { self.list[i].text = "Changed" }) } } } } } } }
<stdin>:2:8: error: no such module 'CoreData' import CoreData ^
import Foundation import CoreData @objc(Test) class Test: NSManagedObject { } extension Test { @NSManaged public var text: String } class Model: ObservableObject { @MainActor @Published var list: [Test] = [] init() { let container = NSPersistentContainer(name: "") NotificationCenter.default.addObserver( forName: NSManagedObjectContext.didChangeObjectsNotification, object: container.persistentStoreCoordinator, queue: nil ) { notification in if let updatedList = notification.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject> { for updated in updatedList { Task { if let i = await self.list.firstIndex(where: { $0.objectID == updated.objectID }) { await MainActor.run(body: { self.list[i].text = "Changed" }) } } } } } } }
<stdin>:2:8: error: no such module 'CoreData' import CoreData ^
import Foundation struct Test { var text: String } class Model: ObservableObject { @MainActor @Published var list: [Test] = [] init() { Task { let updatedList = [ Test(text: "Text1"), Test(text: "Text2") ] for updated in updatedList { if let i = await self.list.firstIndex(where: { $0.text == updated.text }) { await MainActor.run(body: { self.list[i].text = "Changed" }) } } } } }
import Foundation struct Test { var text: String } class Model: ObservableObject { @MainActor @Published var list: [Test] = [] init() { Task { let updatedList = [ Test(text: "Text1"), Test(text: "Text2") ] for updated in updatedList { if let i = await self.list.firstIndex(where: { $0.text == updated.text }) { await MainActor.run(body: { self.list[i].text = "Changed" }) } } } } }
<stdin>:8:17: error: unknown attribute 'Published' @MainActor @Published var list: [Test] = [] ^ <stdin>:7:14: error: cannot find type 'ObservableObject' in scope class Model: ObservableObject { ^~~~~~~~~~~~~~~~ <stdin>:19:30: error: actor-isolated property 'list' cannot be passed 'inout' to 'async' function call self.list[i].text = "Changed" ^ <stdin>:8:31: note: property declared here @MainActor @Published var list: [Test] = [] ^
import Foundation struct Test { var text: String } class Model: ObservableObject { @MainActor @Published var list: [Test] = [] init() { Task { let updatedList = [ Test(text: "Text1"), Test(text: "Text2") ] for updated in updatedList { if let i = await self.list.firstIndex(where: { $0.text == updated.text }) { await MainActor.run(body: { self.list[i].text = "Changed" }) } } } } }
<stdin>:8:17: error: unknown attribute 'Published' @MainActor @Published var list: [Test] = [] ^ <stdin>:7:14: error: cannot find type 'ObservableObject' in scope class Model: ObservableObject { ^~~~~~~~~~~~~~~~ <stdin>:19:30: error: actor-isolated property 'list' cannot be passed 'inout' to 'async' function call self.list[i].text = "Changed" ^ <stdin>:8:31: note: property declared here @MainActor @Published var list: [Test] = [] ^
import Foundation struct Test { var id: Int var text: String } class Model { @MainActor var list: [Test] = [ Test(id: 1, text: ""), Test(id: 2, text: "") ] init() { Task { let updatedList = [ Test(id: 1, text: "Text1"), Test(id: 2, text: "Text2") ] for updated in updatedList { if let i = await self.list.firstIndex(where: { $0.id == updated.id }) { await MainActor.run(body: { self.list[i].text = updated.text }) } } } } }
import Foundation struct Test { var id: Int var text: String } class Model { @MainActor var list: [Test] = [ Test(id: 1, text: ""), Test(id: 2, text: "") ] init() { Task { let updatedList = [ Test(id: 1, text: "Text1"), Test(id: 2, text: "Text2") ] for updated in updatedList { if let i = await self.list.firstIndex(where: { $0.id == updated.id }) { await MainActor.run(body: { self.list[i].text = updated.text }) } } } } }
<stdin>:23:30: error: actor-isolated property 'list' cannot be passed 'inout' to 'async' function call self.list[i].text = updated.text ^ <stdin>:9:20: note: property declared here @MainActor var list: [Test] = [ ^
import Foundation struct Test { var id: Int var text: String } class Model { @MainActor var list: [Test] = [ Test(id: 1, text: ""), Test(id: 2, text: "") ] init() { Task { let updatedList = [ Test(id: 1, text: "Text1"), Test(id: 2, text: "Text2") ] for updated in updatedList { if let i = await self.list.firstIndex(where: { $0.id == updated.id }) { await MainActor.run(body: { self.list[i].text = updated.text }) } } } } }
<stdin>:23:30: error: actor-isolated property 'list' cannot be passed 'inout' to 'async' function call self.list[i].text = updated.text ^ <stdin>:9:20: note: property declared here @MainActor var list: [Test] = [ ^
import Foundation struct Test { var id: Int var text: String } class Model { @MainActor var list: [Test] = [ Test(id: 1, text: ""), Test(id: 2, text: "") ] init() { Task { let updatedList = [ Test(id: 1, text: "Text1"), Test(id: 2, text: "Text2") ] for updated in updatedList { if let i = await self.list.firstIndex(where: { $0.id == updated.id }) { await MainActor.run(body: { self.updateText(i: i, value: updated.text) }) } } } } @MainActor private func updateText(i: Int, value: String) { self.list[i].text = value } }
import Foundation struct Test { var id: Int var text: String } class Model { @MainActor var list: [Test] = [ Test(id: 1, text: ""), Test(id: 2, text: "") ] init() { Task { let updatedList = [ Test(id: 1, text: "Text1"), Test(id: 2, text: "Text2") ] for updated in updatedList { if let i = await self.list.firstIndex(where: { $0.id == updated.id }) { await MainActor.run(body: { self.updateText(i: i, value: updated.text) }) } } } } @MainActor private func updateText(i: Int, value: String) { self.list[i].text = value } }
import Foundation struct Test { var id: Int var text: String } class Model: @unchecked Sendable { @MainActor var list: [Test] = [ Test(id: 1, text: ""), Test(id: 2, text: "") ] func f() { Task { [self] in await MainActor.run { @MainActor in self.list[0].text = "updated" } } } }
import Foundation struct Test { var id: Int var text: String } class Model: @unchecked Sendable { @MainActor var list: [Test] = [ Test(id: 1, text: ""), Test(id: 2, text: "") ] func f() { Task { [self] in await MainActor.run { @MainActor in self.list[0].text = "updated" } } } }
<stdin>:17:22: error: actor-isolated property 'list' cannot be passed 'inout' to 'async' function call self.list[0].text = "updated" ^ <stdin>:9:20: note: property declared here @MainActor var list: [Test] = [ ^
import Foundation struct Test { var id: Int var text: String } class Model: @unchecked Sendable { @MainActor var list: [Test] = [ Test(id: 1, text: ""), Test(id: 2, text: "") ] func f() { Task { [self] in await MainActor.run { @MainActor [self] () in self.list[0].text = "updated" } } } }
(edited)import Foundation struct Test { var id: Int var text: String } class Model: @unchecked Sendable { @MainActor var list: [Test] = [ Test(id: 1, text: ""), Test(id: 2, text: "") ] func f() { Task { [self] in await MainActor.run { @MainActor [self] () in self.list[0].text = "updated" } } } }
(edited)<stdin>:17:22: error: actor-isolated property 'list' cannot be passed 'inout' to 'async' function call self.list[0].text = "updated" ^ <stdin>:9:20: note: property declared here @MainActor var list: [Test] = [ ^
(edited)import Foundation let workCount = 1000 class Counter { let lock = NSLock() var count = 0 func increment() { self.lock.lock() defer { self.lock.unlock() } self.count += 1 } } let counter = Counter() for _ in 0..<workCount { Task { counter.increment() } } Thread.sleep(forTimeInterval: 2) print("counter.count", counter.count)
(edited)import Foundation let workCount = 1000 class Counter { let lock = NSLock() var count = 0 func increment() { self.lock.lock() defer { self.lock.unlock() } self.count += 1 } } let counter = Counter() for _ in 0..<workCount { Task { counter.increment() } } Thread.sleep(forTimeInterval: 2) print("counter.count", counter.count)
(edited)counter.count 1000
(edited)import Foundation let workCount = 1000 class Counter { let lock = NSLock() var count = 0 func increment() { self.lock.lock() defer { self.lock.unlock() } self.count += 1 } } let counter = Counter() for _ in 0..<workCount { Task { counter.increment() } } Thread.sleep(forTimeInterval: 2) print("counter.count", counter.count)
(edited)import Foundation let workCount = 1000 class Counter { let lock = NSLock() var count = 0 func increment() { self.lock.lock() defer { self.lock.unlock() } self.count += 1 } } let counter = Counter() for _ in 0..<workCount { Task { counter.increment() } } Thread.sleep(forTimeInterval: 2) print("counter.count", counter.count)
(edited)counter.count 1000
(edited)import Foundation import FoundationNetworking enum RequestData { @TaskLocal static var requestId: UUID! @TaskLocal static var startDate: Date! } struct Response: Encodable { let user: User let subscription: StripeSubscription } struct User: Encodable { var id: Int } func fetchUser() async throws -> User{ let requestId = RequestData.requestId! defer { print(requestId, "databaseQuery", "isCancelled", Task.isCancelled )} print(requestId, "Making database query") try await Task.sleep(nanoseconds: 500_000_000) print(requestId, "Finished database query") return User(id: 42) } struct StripeSubscription: Encodable { var id: Int} func fetchSubscription() async throws -> StripeSubscription { let requestId = RequestData.requestId! defer { print(requestId, "networkRequest", "isCancelled", Task.isCancelled )} print(requestId, "Making network request") try await Task.sleep(nanoseconds: 500_000_000) print(requestId, "Finished network request") return .init(id: 1729) } func response(for request: URLRequest) async throws -> Data { let requestId = RequestData.requestId! let start = RequestData.startDate! defer { print(requestId, "Request finished in", Date().timeIntervalSince(start)) } Task { print(RequestData.requestId!, "Track analytics") } async let user = fetchUser() async let subscription = fetchSubscription() let jsonData = try await JSONEncoder().encode( Response( user: user, subscription: subscription ) ) return jsonData } RequestData.$requestId.withValue(UUID()) { RequestData.$startDate.withValue(Date()) { let task = Task { _ = try await response(for: .init(url: .init(string: "https://www.pointfree.co")!)) } Thread.sleep(forTimeInterval: 0.1) } } Thread.sleep(forTimeInterval: 5)
(edited)import Foundation import FoundationNetworking enum RequestData { @TaskLocal static var requestId: UUID! @TaskLocal static var startDate: Date! } struct Response: Encodable { let user: User let subscription: StripeSubscription } struct User: Encodable { var id: Int } func fetchUser() async throws -> User{ let requestId = RequestData.requestId! defer { print(requestId, "databaseQuery", "isCancelled", Task.isCancelled )} print(requestId, "Making database query") try await Task.sleep(nanoseconds: 500_000_000) print(requestId, "Finished database query") return User(id: 42) } struct StripeSubscription: Encodable { var id: Int} func fetchSubscription() async throws -> StripeSubscription { let requestId = RequestData.requestId! defer { print(requestId, "networkRequest", "isCancelled", Task.isCancelled )} print(requestId, "Making network request") try await Task.sleep(nanoseconds: 500_000_000) print(requestId, "Finished network request") return .init(id: 1729) } func response(for request: URLRequest) async throws -> Data { let requestId = RequestData.requestId! let start = RequestData.startDate! defer { print(requestId, "Request finished in", Date().timeIntervalSince(start)) } Task { print(RequestData.requestId!, "Track analytics") } async let user = fetchUser() async let subscription = fetchSubscription() let jsonData = try await JSONEncoder().encode( Response( user: user, subscription: subscription ) ) return jsonData } RequestData.$requestId.withValue(UUID()) { RequestData.$startDate.withValue(Date()) { let task = Task { _ = try await response(for: .init(url: .init(string: "https://www.pointfree.co")!)) } Thread.sleep(forTimeInterval: 0.1) } } Thread.sleep(forTimeInterval: 5)
(edited)61E1B2B1-A445-4E76-A697-99C55BDBA919 Making database query 61E1B2B1-A445-4E76-A697-99C55BDBA919 Track analytics 61E1B2B1-A445-4E76-A697-99C55BDBA919 Making network request 61E1B2B1-A445-4E76-A697-99C55BDBA919 Finished network request 61E1B2B1-A445-4E76-A697-99C55BDBA919 networkRequest isCancelled false 61E1B2B1-A445-4E76-A697-99C55BDBA919 Finished database query 61E1B2B1-A445-4E76-A697-99C55BDBA919 databaseQuery isCancelled false 61E1B2B1-A445-4E76-A697-99C55BDBA919 Request finished in 0.5015460252761841
stderr:<stdin>:58:9: warning: initialization of immutable value 'task' was never used; consider replacing with assignment to '_' or removing it let task = Task { ~~~~^~~~ _
(edited)@preconcurrency import Foundation import FoundationNetworking enum RequestData { @TaskLocal static var requestId: UUID! @TaskLocal static var startDate: Date! } struct Response: Encodable { let user: User let subscription: StripeSubscription } struct User: Encodable { var id: Int } func fetchUser() async throws -> User{ let requestId = RequestData.requestId! defer { print(requestId, "databaseQuery", "isCancelled", Task.isCancelled )} print(requestId, "Making database query") try await Task.sleep(nanoseconds: 500_000_000) print(requestId, "Finished database query") return User(id: 42) } struct StripeSubscription: Encodable { var id: Int} func fetchSubscription() async throws -> StripeSubscription { let requestId = RequestData.requestId! defer { print(requestId, "networkRequest", "isCancelled", Task.isCancelled )} print(requestId, "Making network request") try await Task.sleep(nanoseconds: 500_000_000) print(requestId, "Finished network request") return .init(id: 1729) } func response(for request: URLRequest) async throws -> Data { let requestId = RequestData.requestId! let start = RequestData.startDate! defer { print(requestId, "Request finished in", Date().timeIntervalSince(start)) } Task { print(RequestData.requestId!, "Track analytics") } async let user = fetchUser() async let subscription = fetchSubscription() let jsonData = try await JSONEncoder().encode( Response( user: user, subscription: subscription ) ) return jsonData } RequestData.$requestId.withValue(UUID()) { RequestData.$startDate.withValue(Date()) { let task = Task { _ = try await response(for: .init(url: .init(string: "https://www.pointfree.co")!)) } Thread.sleep(forTimeInterval: 0.1) } } Thread.sleep(forTimeInterval: 5)
(edited)@preconcurrency import Foundation import FoundationNetworking enum RequestData { @TaskLocal static var requestId: UUID! @TaskLocal static var startDate: Date! } struct Response: Encodable { let user: User let subscription: StripeSubscription } struct User: Encodable { var id: Int } func fetchUser() async throws -> User{ let requestId = RequestData.requestId! defer { print(requestId, "databaseQuery", "isCancelled", Task.isCancelled )} print(requestId, "Making database query") try await Task.sleep(nanoseconds: 500_000_000) print(requestId, "Finished database query") return User(id: 42) } struct StripeSubscription: Encodable { var id: Int} func fetchSubscription() async throws -> StripeSubscription { let requestId = RequestData.requestId! defer { print(requestId, "networkRequest", "isCancelled", Task.isCancelled )} print(requestId, "Making network request") try await Task.sleep(nanoseconds: 500_000_000) print(requestId, "Finished network request") return .init(id: 1729) } func response(for request: URLRequest) async throws -> Data { let requestId = RequestData.requestId! let start = RequestData.startDate! defer { print(requestId, "Request finished in", Date().timeIntervalSince(start)) } Task { print(RequestData.requestId!, "Track analytics") } async let user = fetchUser() async let subscription = fetchSubscription() let jsonData = try await JSONEncoder().encode( Response( user: user, subscription: subscription ) ) return jsonData } RequestData.$requestId.withValue(UUID()) { RequestData.$startDate.withValue(Date()) { let task = Task { _ = try await response(for: .init(url: .init(string: "https://www.pointfree.co")!)) } Thread.sleep(forTimeInterval: 0.1) } } Thread.sleep(forTimeInterval: 5)
(edited)2C9A9B92-608A-4F07-A935-BB5C5A212108 Making database query 2C9A9B92-608A-4F07-A935-BB5C5A212108 Track analytics 2C9A9B92-608A-4F07-A935-BB5C5A212108 Making network request 2C9A9B92-608A-4F07-A935-BB5C5A212108 Finished network request 2C9A9B92-608A-4F07-A935-BB5C5A212108 Finished database query 2C9A9B92-608A-4F07-A935-BB5C5A212108 databaseQuery isCancelled false 2C9A9B92-608A-4F07-A935-BB5C5A212108 networkRequest isCancelled false 2C9A9B92-608A-4F07-A935-BB5C5A212108 Request finished in 0.5029729604721069
stderr:<stdin>:58:9: warning: initialization of immutable value 'task' was never used; consider replacing with assignment to '_' or removing it let task = Task { ~~~~^~~~ _
(edited)actor A { func foo() {} func bar() { Task { foo() } Task { [weak self] in self?.foo() } } }
actor A { func foo() {} func bar() { Task { foo() } Task { [weak self] in self?.foo() } } }
<stdin>:5:31: error: expression is 'async' but is not marked with 'await' Task { [weak self] in self?.foo() } ^~~~~~~~~~~ await <stdin>:5:31: note: calls to instance method 'foo()' from outside of its actor context are implicitly asynchronous Task { [weak self] in self?.foo() } ^
@MainActor class C { func foo() {} func bar() { Task { foo() } Task { [weak self] in self?.foo() } } }
@MainActor class C { func foo() {} func bar() { Task { foo() } Task { [weak self] in self?.foo() } } }
let pattern = #"Hello, (?<world>.*)"# let regexRuntime = try Regex(pattern) let matches = "Hello, Swift".matches(of: regexRuntime) if let m = matches[0].as((Substring, world: Substring).self) { print(m.world) }
let pattern = #"Hello, (?<world>.*)"# let regexRuntime = try Regex(pattern) let matches = "Hello, Swift".matches(of: regexRuntime) if let m = matches[0].as((Substring, world: Substring).self) { print(m.world) }
<stdin>:2:24: error: cannot find 'Regex' in scope let regexRuntime = try Regex(pattern) ^~~~~ <stdin>:3:30: error: value of type 'String' has no member 'matches' let matches = "Hello, Swift".matches(of: regexRuntime) ~~~~~~~~~~~~~~ ^~~~~~~
import _StringProcessing let pattern = #"Hello, (?<world>.*)"# let regexRuntime = try Regex(pattern) let matches = "Hello, Swift".matches(of: regexRuntime) if let m = matches[0].as((Substring, world: Substring).self) { print(m.world) }
import _StringProcessing let pattern = #"Hello, (?<world>.*)"# let regexRuntime = try Regex(pattern) let matches = "Hello, Swift".matches(of: regexRuntime) if let m = matches[0].as((Substring, world: Substring).self) { print(m.world) }
<stdin>:6:23: error: value of type 'Regex<AnyRegexOutput>.Match' has no dynamic member 'as' using key path from root type 'AnyRegexOutput' if let m = matches[0].as((Substring, world: Substring).self) { ~~~~~~~~~~ ^~
protocol P {} struct S: P {} let foo: some P = S()
protocol P {} struct S: P {} let foo: some P = S()
protocol P { func foo() async } struct S: P { func foo() async { print("async version") } func foo() { print("sync version") } } func takeP<X: P>(_ x: X) async { await x.foo() } @main struct Entry { static func main() async { await takeP(S()) } }
(edited)protocol P { func foo() async } struct S: P { func foo() async { print("async version") } func foo() { print("sync version") } } func takeP<X: P>(_ x: X) async { await x.foo() } @main struct Entry { static func main() async { await takeP(S()) } }
(edited)sync version
(edited)@rethrows internal protocol _ErrorMechanism { associatedtype Output func get() throws -> Output } extension _ErrorMechanism { internal func _rethrowGet() rethrows -> Output { return try get() } } extension Result: _ErrorMechanism { } @rethrows protocol P { func foo() throws } struct S1: P { func foo() {} } struct E: Error {} func foo<T: P>(_: T.Type) rethrows { _ = try Result<Int, Error>.failure(E())._rethrowGet() } print("start program") foo(S1.self) print("end program")
(edited)@rethrows internal protocol _ErrorMechanism { associatedtype Output func get() throws -> Output } extension _ErrorMechanism { internal func _rethrowGet() rethrows -> Output { return try get() } } extension Result: _ErrorMechanism { } @rethrows protocol P { func foo() throws } struct S1: P { func foo() {} } struct E: Error {} func foo<T: P>(_: T.Type) rethrows { _ = try Result<Int, Error>.failure(E())._rethrowGet() } print("start program") foo(S1.self) print("end program")
(edited)Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7-dev (LLVM d5f117e38620783, Swift 260a80fcce5a2ab) 2. Compiling with the current language version 3. While running user code "<stdin>"
(edited)@rethrows internal protocol _ErrorMechanism { associatedtype Output func get() throws -> Output } extension _ErrorMechanism { internal func _rethrowGet() rethrows -> Output { return try get() } } extension Result: _ErrorMechanism { } @rethrows protocol P { func foo() throws } struct S1: P { func foo() {} } struct E: Error {} func foo<T: P>(_: T.Type) rethrows { _ = try Result<Int, Error>.failure(E())._rethrowGet() } print("start program") foo(S1.self) print("end program")
(edited)Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6.2 (swift-5.6.2-RELEASE) 2. Compiling with the current language version 3. While running user code "<stdin>" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5187de3] /usr/bin/swift-frontend[0x5185b7e] /usr/bin/swift-frontend[0x5188176] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7f1e8c7a9980] [0x7f1e8cbdb240] [0x7acf840]
(edited)@MainActor class Foo { @discardableResult func bar() -> Int { 1 } } Task { await Foo().bar() return }
(edited)@MainActor class Foo { @discardableResult func bar() -> Int { 1 } } Task { await Foo().bar() return }
(edited)<stdin>:3:1: warning: non-breaking space (U+00A0) used instead of regular space @discardableResult <stdin>:3:4: warning: non-breaking space (U+00A0) used instead of regular space @discardableResult <stdin>:4:1: warning: non-breaking space (U+00A0) used instead of regular space func bar() -> Int { 1 } <stdin>:4:4: warning: non-breaking space (U+00A0) used instead of regular space func bar() -> Int { 1 } <stdin>:8:1: warning: non-breaking space (U+00A0) used instead of regular space await Foo().bar() <stdin>:8:4: warning: non-breaking space (U+00A0) used instead of regular space await Foo().bar() <stdin>:9:1: warning: non-breaking space (U+00A0) used instead of regular space return <stdin>:9:4: warning: non-breaking space (U+00A0) used instead of regular space return <stdin>:8:19: warning: result of call to function returning 'Int' is unused await Foo().bar()
(edited)actor Foo { @discardableResult func bar() -> Int { 1 } } Task { await Foo().bar() return }
actor Foo { @discardableResult func bar() -> Int { 1 } } Task { await Foo().bar() return }
<stdin>:2:1: warning: non-breaking space (U+00A0) used instead of regular space @discardableResult <stdin>:2:4: warning: non-breaking space (U+00A0) used instead of regular space @discardableResult <stdin>:3:1: warning: non-breaking space (U+00A0) used instead of regular space func bar() -> Int { 1 } <stdin>:3:4: warning: non-breaking space (U+00A0) used instead of regular space func bar() -> Int { 1 } <stdin>:7:1: warning: non-breaking space (U+00A0) used instead of regular space await Foo().bar() <stdin>:7:4: warning: non-breaking space (U+00A0) used instead of regular space await Foo().bar() <stdin>:8:1: warning: non-breaking space (U+00A0) used instead of regular space return <stdin>:8:4: warning: non-breaking space (U+00A0) used instead of regular space return
class A { init(name: String) { self.name = name } var name: String deinit { print("deinit \(name)") } } func main() { let a = A(name: "a") defer { print("defer") } let b = A(name: "b") use(a) use(b) } func use<T>(_ x: T) { } main()
class A { init(name: String) { self.name = name } var name: String deinit { print("deinit \(name)") } } func main() { let a = A(name: "a") defer { print("defer") } let b = A(name: "b") use(a) use(b) } func use<T>(_ x: T) { } main()
deinit b defer deinit a
struct S<T> { struct I {} func f() where T == I {} }
struct S<T> { struct I {} func f() where T == I {} }
<stdin>:3:20: error: same-type constraint 'T' == 'S<T>.I' is recursive func f() where T == I {} ^
struct S<T> { struct I {} func f() where T == I {} }
<stdin>:3:12: error: cannot build rewrite system for generic signature; concrete nesting limit exceeded func f() where T == I {} ^ <stdin>:3:12: note: failed rewrite rule is τ_0_0.[concrete: S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<τ_0_0>.I>.I>.I>.I>.I>.I>.I>.I>.I>.I>.I>.I>.I>.I>.I] => τ_0_0 func f() where T == I {} ^
curl -X POST "https://swiftfiddle.com/runner/5.5.2/run" \ -H "Content-Type:application/json" \ --data '{"code": "import Foundation\nprint(\"Hello World\")”}'
今のところ全バージョンのSwiftがあります。 (edited)import Foundation @propertyWrapper struct Wrapper<Value> { var wrappedValue: Value var projectedValue: Self { get { self } set { self = newValue } } init(wrappedValue: Value) { self.wrappedValue = wrappedValue } init(projectedValue: Self) { self = projectedValue } } struct Foo { init(@Wrapper val: Int) {} } func call() { @Wrapper var val = 10 Foo($val: _val) } call()
(edited)import Foundation @propertyWrapper struct Wrapper<Value> { var wrappedValue: Value var projectedValue: Self { get { self } set { self = newValue } } init(wrappedValue: Value) { self.wrappedValue = wrappedValue } init(projectedValue: Self) { self = projectedValue } } struct Foo { init(@Wrapper val: Int) {} } func call() { @Wrapper var val = 10 Foo($val: _val) } call()
(edited)<stdin>:24:5: warning: result of 'Foo' initializer is unused Foo($val: _val) ^ ~~~~~~~~~~~~ Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.6.2 (swift-5.6.2-RELEASE) 2. Compiling with the current language version 3. While evaluating request TypeCheckSourceFileRequest(source_file "<stdin>") 4. While evaluating request TypeCheckFunctionBodyRequest(main.(file).call()@<stdin>:22:6) 5. While computing captures for 'call()' (at <stdin>:22:1) Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x5187de3] /usr/bin/swift-frontend[0x5185b7e] /usr/bin/swift-frontend[0x5188176] /lib/x86_64-linux-gnu/libpthread.so.0(+0x12980)[0x7fab3d796980] /usr/bin/swift-frontend[0x13188ba] /usr/bin/swift-frontend[0x13194dc] /usr/bin/swift-frontend[0x1541a35] /usr/bin/swift-frontend[0x15418ff] /usr/bin/swift-frontend[0x1541b3d] /usr/bin/swift-frontend[0x15434b2] /usr/bin/swift-frontend[0x1541224] /usr/bin/swift-frontend[0x13181eb] /usr/bin/swift-frontend[0x12498c8] /usr/bin/swift-frontend[0x1606f12] /usr/bin/swift-frontend[0x1606d9f] /usr/bin/swift-frontend[0x158e8de] /usr/bin/swift-frontend[0x158e8ba] /usr/bin/swift-frontend[0x12770d9] /usr/bin/swift-frontend[0x1278b21] /usr/bin/swift-frontend[0x12789bb] /usr/bin/swift-frontend[0x1276f6a] /usr/bin/swift-frontend[0x1276f44] /usr/bin/swift-frontend[0x649619] /usr/bin/swift-frontend[0x48df47] /usr/bin/swift-frontend[0x4463af] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0x7fab3ba04c87] /usr/bin/swift-frontend[0x445dda]
(edited)import Foundation @propertyWrapper struct Wrapper<Value> { var wrappedValue: Value var projectedValue: Self { get { self } set { self = newValue } } init(wrappedValue: Value) { self.wrappedValue = wrappedValue } init(projectedValue: Self) { self = projectedValue } } struct Foo { init(@Wrapper val: Int) {} } func call() { @Wrapper var val = 10 Foo($val: _val) } call()
(edited)swift-frontend: /home/build-user/llvm-project/llvm/include/llvm/ADT/ArrayRef.h:256: const T &llvm::ArrayRef<swift::AppliedPropertyWrapper>::operator[](size_t) const [T = swift::AppliedPropertyWrapper]: Assertion `Index < Length && "Invalid index!"' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.8-dev (LLVM f6b60d5b8f4b443, Swift ecccce61139bbc4) 2. Compiling with the current language version 3. While evaluating request TypeCheckSourceFileRequest(source_file "<stdin>") 4. While evaluating request TypeCheckFunctionBodyRequest(main.(file).call()@<stdin>:22:6) 5. While type-checking statement at [<stdin>:22:13 - line:25:1] RangeText="{ @Wrapper var val = 10 Foo($val: _val) " 6. While type-checking expression at [<stdin>:24:5 - line:24:19] RangeText="Foo($val: _val" 7. While type-checking-target starting at <stdin>:24:5 Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x66fdb63] /usr/bin/swift-frontend[0x66fb89e] /usr/bin/swift-frontend[0x66fdeef] /lib/x86_64-linux-gnu/libpthread.so.0(+0x14420)[0x7fc65d4b3420] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xcb)[0x7fc65c92500b] /lib/x86_64-linux-gnu/libc.so.6(abort+0x12b)[0x7fc65c904859] /lib/x86_64-linux-gnu/libc.so.6(+0x22729)[0x7fc65c904729] /lib/x86_64-linux-gnu/libc.so.6(+0x33fd6)[0x7fc65c915fd6] /usr/bin/swift-frontend[0x17279a0] /usr/bin/swift-frontend[0x172f367] /usr/bin/swift-frontend[0x172fe15] /usr/bin/swift-frontend[0x1734eb7] /usr/bin/swift-frontend[0x171a733] /usr/bin/swift-frontend[0x1bef4e6] /usr/bin/swift-frontend[0x17125a1] /usr/bin/swift-frontend[0x1711ee2] /usr/bin/swift-frontend[0x15e0e0a] /usr/bin/swift-frontend[0x15e0c4d] /usr/bin/swift-frontend[0x15e0b2d]
(edited)@propertyWrapper struct Wrapper { var wrappedValue: Int { 10 } } func call() { @Wrapper var int print(int) } call()
(edited)@propertyWrapper struct Wrapper { var wrappedValue: Int { 10 } } func call() { @Wrapper var int print(int) } call()
(edited)<stdin>:8:3: error: found an unexpected second identifier in variable declaration; is there an accidental break? print(int) ^ <stdin>:8:3: note: join the identifiers together print(int) ~~^~~~~ intprint <stdin>:8:3: note: join the identifiers together with camel-case print(int) ~~^~~~~ intPrint <stdin>:8:8: error: consecutive statements on a line must be separated by ';' print(int) ^ ; <stdin>:8:9: warning: expression of type 'Int' is unused print(int) ^~~
(edited)@propertyWrapper struct Wrapper { var wrappedValue: Int { 10 } } func call() { @Wrapper var int print(int) } call()
(edited)10
extension String? {}
extension String? {}
<stdin>:1:1: error: constrained extension must be declared on the unspecialized generic type 'Optional' with constraints specified by a 'where' clause extension String? {} ^ ~~~~~~~
private extension Equatable { func isEquals(_ other: any Equatable) -> Bool { guard let other = other as? Self else { return false } return self == other } } public func == (lhs: any Equatable, rhs: any Equatable) -> Bool { lhs.isEquals(rhs) } let i: any Equatable = 1 let d: any Equatable = 1.0 let i2: any Equatable = 1 print(i == d) print(i == i2)
private extension Equatable { func isEquals(_ other: any Equatable) -> Bool { guard let other = other as? Self else { return false } return self == other } } public func == (lhs: any Equatable, rhs: any Equatable) -> Bool { lhs.isEquals(rhs) } let i: any Equatable = 1 let d: any Equatable = 1.0 let i2: any Equatable = 1 print(i == d) print(i == i2)
Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7.1 (swift-5.7.1-RELEASE) 2. Compiling with the current language version 3. While running user code "<stdin>" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend(+0x551a083)[0x5643df6e6083] /usr/bin/swift-frontend(+0x5517fae)[0x5643df6e3fae] /usr/bin/swift-frontend(+0x551a40a)[0x5643df6e640a] /lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7ffa50f4d520] /usr/lib/swift/linux/libswiftCore.so(+0x42192f)[0x7ffa518e192f] /usr/lib/swift/linux/libswiftCore.so(+0x3fad00)[0x7ffa518bad00]
private extension Equatable { func isEquals(_ other: any Equatable) -> Bool { guard let other = other as? Self else { return false } return self == other } } public func == (lhs: any Equatable, rhs: any Equatable) -> Bool { lhs.isEquals(rhs) } let i: any Equatable = 1 let d: any Equatable = 1.0 let i2: any Equatable = 1 print(i == d) print(i == i2)
Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.8-dev (LLVM 1299cdab04e4506, Swift 56665d5ce9f6420) 2. Compiling with the current language version 3. While running user code "<stdin>" Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x6954fe3] /usr/bin/swift-frontend[0x6952d1e] /usr/bin/swift-frontend[0x695536f] /lib/x86_64-linux-gnu/libpthread.so.0(+0x14420)[0x7f363d0e5420] /usr/lib/swift/linux/libswiftCore.so(+0x3f2c49)[0x7f363ce8dc49] /usr/lib/swift/linux/libswiftCore.so(+0x3d0ba0)[0x7f363ce6bba0]
private extension Equatable { func isEquals(_ other: any Equatable) -> Bool { guard let other = other as? Self else { return false } return self == other } } public func == (lhs: any Equatable, rhs: any Equatable) -> Bool { lhs.isEquals(rhs) } let i: any Equatable = 1 let d: any Equatable = 1.0 let i2: any Equatable = 1 print(i == d) // print(i == i2)
(edited)private extension Equatable { func isEquals(_ other: any Equatable) -> Bool { guard let other = other as? Self else { return false } return self == other } } public func == (lhs: any Equatable, rhs: any Equatable) -> Bool { lhs.isEquals(rhs) } let i: any Equatable = 1 let d: any Equatable = 1.0 let i2: any Equatable = 1 print(i == d) // print(i == i2)
(edited)false
(edited)private extension Equatable { func isEquals(_ other: any Equatable) -> Bool { guard let other = other as? Self else { return false } return self == other } } public func == (lhs: any Equatable, rhs: any Equatable) -> Bool { lhs.isEquals(rhs) } let i: any Equatable = 1 let d: any Equatable = 1.0 let i2: any Equatable = 1 print(i == d) // print(i == i2)
(edited)false
(edited)private extension Equatable { func isEquals(_ other: any Equatable) -> Bool { guard let other = other as? Self else { return false } let op: (Self, Self) -> Bool = (==) return op(self, other) } } public func == (lhs: any Equatable, rhs: any Equatable) -> Bool { lhs.isEquals(rhs) } let i: any Equatable = 1 let d: any Equatable = 1.0 let i2: any Equatable = 1 print(i == d) print(i == i2)
(edited)private extension Equatable { func isEquals(_ other: any Equatable) -> Bool { guard let other = other as? Self else { return false } let op: (Self, Self) -> Bool = (==) return op(self, other) } } public func == (lhs: any Equatable, rhs: any Equatable) -> Bool { lhs.isEquals(rhs) } let i: any Equatable = 1 let d: any Equatable = 1.0 let i2: any Equatable = 1 print(i == d) print(i == i2)
(edited)false true
(edited)protocol P {} struct S: P {} func f1() -> some P { S() } func f2() -> () -> some P { { S() } }
protocol P {} struct S: P {} func f1() -> some P { S() } func f2() -> () -> some P { { S() } }
<stdin>:8:5: error: cannot convert value of type 'S' to closure result type 'some P' { S() } ^~~
protocol P {} struct S: P {} struct Builder<T> { var build: () -> T func callAsFunction() -> T { build() } } func f2_5() -> Builder<some P> { return Builder { S() } }
protocol P {} struct S: P {} struct Builder<T> { var build: () -> T func callAsFunction() -> T { build() } } func f2_5() -> Builder<some P> { return Builder { S() } }
protocol P {} extension P { func f() -> () -> some P { let fn = { self } return fn } }
(edited)protocol P {} extension P { func f() -> () -> some P { let fn = { self } return fn } }
(edited)protocol P {} struct S: P {} func f() -> () -> some P { let fn = { S() } return fn }
protocol P {} struct S: P {} func f() -> () -> some P { let fn = { S() } return fn }
protocol P {} struct S: P {} func f() -> () -> some P { return { S() } }
protocol P {} struct S: P {} func f() -> () -> some P { return { S() } }
<stdin>:4:12: error: cannot convert value of type 'S' to closure result type 'some P' return { S() } ^~~
// FIXME: This still doesn't work because the '() -> (some P)' propagates // backwards into the closure literal's return type /* public func f3() -> () -> (some P) { return { self } } */
(edited)let aaa: [Int] = [1, 2, 3] for case .some(let v) in aaa { print(v) }
(edited)let aaa: [Int] = [1, 2, 3] for case .some(let v) in aaa { print(v) }
(edited)Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7.1 (swift-5.7.1-RELEASE) 2. Compiling with the current language version 3. While evaluating request ASTLoweringRequest(Lowering AST to SIL for module main) Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend(+0x551a083)[0x5616f5dd5083] /usr/bin/swift-frontend(+0x5517fae)[0x5616f5dd2fae] /usr/bin/swift-frontend(+0x551a40a)[0x5616f5dd540a] /lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7fc688d3e520] /usr/bin/swift-frontend(+0x1bf67db)[0x5616f24b17db] /usr/bin/swift-frontend(+0xb6d1ac)[0x5616f14281ac] /usr/bin/swift-frontend(+0xb64271)[0x5616f141f271] /usr/bin/swift-frontend(+0xb64b0d)[0x5616f141fb0d] /usr/bin/swift-frontend(+0xae8807)[0x5616f13a3807] /usr/bin/swift-frontend(+0xb5daa7)[0x5616f1418aa7] /usr/bin/swift-frontend(+0xb27883)[0x5616f13e2883] /usr/bin/swift-frontend(+0xf8aabf)[0x5616f1845abf] /usr/bin/swift-frontend(+0x10171bc)[0x5616f18d21bc] /usr/bin/swift-frontend(+0xf9c989)[0x5616f1857989] /usr/bin/swift-frontend(+0xf9d296)[0x5616f1858296] /usr/bin/swift-frontend(+0x100f476)[0x5616f18ca476] /usr/bin/swift-frontend(+0x100f278)[0x5616f18ca278] /usr/bin/swift-frontend(+0xffce4f)[0x5616f18b7e4f] /usr/bin/swift-frontend(+0x10171f1)[0x5616f18d21f1] /usr/bin/swift-frontend(+0xffc1d8)[0x5616f18b71d8] /usr/bin/swift-frontend(+0xff7a1d)[0x5616f18b2a1d] /usr/bin/swift-frontend(+0xf795a5)[0x5616f18345a5] /usr/bin/swift-frontend(+0xf79fd3)[0x5616f1834fd3] /usr/bin/swift-frontend(+0xff758f)[0x5616f18b258f] /usr/bin/swift-frontend(+0xff74a9)[0x5616f18b24a9] /usr/bin/swift-frontend(+0xf7ce18)[0x5616f1837e18] /usr/bin/swift-frontend(+0xf7ac74)[0x5616f1835c74] /usr/bin/swift-frontend(+0xa41120)[0x561
(edited)let aaa: [Int] = [1, 2, 3] for case .some(let v) in aaa { print(v) }
(edited)<stdin>:2:26: error: type 'Int' has no member 'some' for case .some(let v) in aaa { ^~~
struct S { private var _x = [1, 2, 3] var x: [Int] { _read { yield _x } _modify { yield &_x } } } var s = S() s.x.append(4) debugPrint(s)
(edited)struct S { private var _x = [1, 2, 3] var x: [Int] { _read { yield _x } _modify { yield &_x } } } var s = S() s.x.append(4) debugPrint(s)
(edited)main.S(_x: [1, 2, 3, 4])
(edited)struct S { private var _x = [1, 2, 3] var x: [Int] { _read { yield _x } _modify { yield &_x } } } var s = S() s.x.append(4) debugPrint(s)
(edited)main.S(_x: [1, 2, 3, 4])
(edited)struct S { private var _x = [1, 2, 3] var x: [Int] { _read { yield _x } _modify { yield &_x } } } var s = S() s.x.append(4) debugPrint(s)
(edited)main.S(_x: [1, 2, 3, 4])
_read, _modify
は結構前からありますねprint(#stringify(1 + 1))
(edited)print(#stringify(1 + 1))
(edited)(source_file "<stdin>" (top_level_code_decl range=[<stdin>:1:1 - line:1:24] (brace_stmt implicit range=[<stdin>:1:1 - line:1:24] (call_expr type='<null>' (overloaded_decl_ref_expr type='<null>' name=print number_of_decls=2 function_ref=single) (argument_list (argument (macro_expansion_expr type='<null>' name=stringify (argument_list (argument (binary_expr type='<null>' (overloaded_decl_ref_expr type='<null>' name=+ number_of_decls=35 function_ref=single) (argument_list implicit (argument (integer_literal_expr type='<null>' value=1 builtin_initializer=**NULL** initializer=**NULL**)) (argument (integer_literal_expr type='<null>' value=1 builtin_initializer=**NULL** initializer=**NULL**)))))))))))))
stderr:<stdin>:1:1: error: failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) print(#stringify(1 + 1)) ^
(edited)func foo() -> (Int...) -> Void { return { (a: Int...) in } }
(edited)func foo() -> (Int...) -> Void { return { (a: Int...) in } }
(edited)(source_file "<stdin>" (func_decl range=[<stdin>:1:1 - line:1:60] "foo()" interface type='() -> (Int...) -> Void' access=internal (parameter_list range=[<stdin>:1:9 - line:1:10]) (result (type_function (type_tuple (type_ident (component id='Int' bind=Swift.(file).Int))) (type_ident (component id='Void' bind=Swift.(file).Void)))) (brace_stmt range=[<stdin>:1:32 - line:1:60] (return_stmt range=[<stdin>:1:34 - line:1:58] (closure_expr type='(Int...) -> ()' location=<stdin>:1:41 range=[<stdin>:1:41 - line:1:58] discriminator=0 escaping (parameter_list (parameter "a" type='[Int]' interface type='[Int]' variadic) range=[<stdin>:1:43 - line:1:53]) (brace_stmt range=[<stdin>:1:41 - line:1:58]))))))
stderr:
(edited)func foo() -> (Int...) -> Void { return { (a: Int...) in } }
(edited)(source_file "<stdin>" (func_decl range=[<stdin>:1:1 - line:1:60] "foo()" interface type='() -> (Int...) -> Void' access=internal (parameter_list range=[<stdin>:1:9 - line:1:10]) (result (type_function (type_tuple (pack_expansion (type_ident (component id='Int' bind=Swift.(file).Int)))) (type_ident (component id='Void' bind=Swift.(file).Void)))) (brace_stmt range=[<stdin>:1:32 - line:1:60] (return_stmt range=[<stdin>:1:34 - line:1:58] (closure_expr type='(Int...) -> Void' location=<stdin>:1:41 range=[<stdin>:1:41 - line:1:58] discriminator=0 escaping (parameter_list range=[<stdin>:1:43 - line:1:53] (parameter "a" type='Int...' interface type='Int...' variadic)) (brace_stmt range=[<stdin>:1:41 - line:1:58]))))))
stderr:
(edited)PackExpansionTypeRepr
は 2022年9月に実装されていて、最新版だと dump-astに pack_expansion
が含まれて、これで表現されているけど、TupleTypeExpr
が、hasEllipsis
と getEllipsisIndex
を持っていて、それで ...
の情報を保持していた。func foo(a: Int..., b: Bool, c: Int...) {} func foo() -> (Int..., Bool, Int...) -> Void { return { (a: Int..., b: Bool, c: Int...) in } }
func foo(a: Int..., b: Bool, c: Int...) {} func foo() -> (Int..., Bool, Int...) -> Void { return { (a: Int..., b: Bool, c: Int...) in } }
<stdin>:3:33: error: only a single element can be variadic func foo() -> (Int..., Bool, Int...) -> Void { ~~~ ^~~ <stdin>:4:26: error: no parameters may follow a variadic parameter in a closure return { (a: Int..., b: Bool, c: Int...) in } ^
func foo(a: Int..., b: Bool, c: Int...) {} var a: ([Int], Bool, [Int]) = foo(a:b:c:)
func foo(a: Int..., b: Bool, c: Int...) {} var a: ([Int], Bool, [Int]) = foo(a:b:c:)
<stdin>:2:31: error: cannot convert value of type '(Int..., Bool, Int...) -> ()' to specified type '([Int], Bool, [Int])' var a: ([Int], Bool, [Int]) = foo(a:b:c:) ^~~~~~~~~~~
func foo(a: Int..., b: Bool, c: Int...) {} var a: (Int..., Bool, Int...) -> Void = foo(a:b:c:) // ng print(type(of: a))
func foo(a: Int..., b: Bool, c: Int...) {} var a: (Int..., Bool, Int...) -> Void = foo(a:b:c:) // ng print(type(of: a))
<stdin>:2:26: error: only a single element can be variadic var a: (Int..., Bool, Int...) -> Void = foo(a:b:c:) // ng ~~~ ^~~
func foo(a: Int..., b: Bool, c: Int...) {} var a = foo(a:b:c:) // ok print(type(of: a))
func foo(a: Int..., b: Bool, c: Int...) {} var a = foo(a:b:c:) // ok print(type(of: a))
(Int..., Bool, Int...) -> ()
func foo(a: Int..., b: Bool, c: Int...) {} var a = foo(a:b:c:) a(1, false, 2) // ng
func foo(a: Int..., b: Bool, c: Int...) {} var a = foo(a:b:c:) a(1, false, 2) // ng
<stdin>:3:4: error: missing argument for parameter #2 in call a(1, false, 2) // ng ^ , <#Bool#> <stdin>:2:5: note: 'a' declared here var a = foo(a:b:c:) ^ <stdin>:3:6: error: cannot convert value of type 'Bool' to expected argument type 'Int' a(1, false, 2) // ng ^
func foo(a: Int..., b: Bool, c: Int...) {} var a = foo(a:b:c:) a(a: 1, b: false, c: 2)
func foo(a: Int..., b: Bool, c: Int...) {} var a = foo(a:b:c:) a(a: 1, b: false, c: 2)
<stdin>:3:2: error: extraneous argument labels 'a:b:c:' in call a(a: 1, b: false, c: 2) ^~~~ ~~~ ~~~
var f: (Int..., Bool) -> Void = { a, b in print(a, b) } f(1, false) // ng
var f: (Int..., Bool) -> Void = { a, b in print(a, b) } f(1, false) // ng
<stdin>:2:4: error: missing argument for parameter #2 in call f(1, false) // ng ^ , <#Bool#> <stdin>:1:5: note: 'f' declared here var f: (Int..., Bool) -> Void = { a, b in print(a, b) } ^ <stdin>:2:6: error: cannot convert value of type 'Bool' to expected argument type 'Int' f(1, false) // ng ^
var f: (Bool, Int...) -> Void = { a, b in print(a, b) } f(false, 1, 2, 3) // ok
var f: (Bool, Int...) -> Void = { a, b in print(a, b) } f(false, 1, 2, 3) // ok
false [1, 2, 3]
func f(a: Int, b: String..., c: String...) { print("b", b, "c", c) } let a = f(a:b:c:) a(1, "", "", "")
(edited)func f(a: Int, b: String..., c: String...) { print("b", b, "c", c) } let a = f(a:b:c:) a(1, "", "", "")
(edited)b ["", "", ""] c []
(edited)Swift version 4.1.3 (swift-4.1.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.0.3 (swift-4.0.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.2.4 (swift-4.2.4-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.1.5 (swift-5.1.5-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.1.3 (swift-4.1.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.2.4 (swift-4.2.4-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.2.5 (swift-5.2.5-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 4.0.3 (swift-4.0.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.4.3 (swift-5.4.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.3.3 (swift-5.3.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.6.3 (swift-5.6.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.5.3 (swift-5.5.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.8-dev (LLVM ec11c492d2fb63b, Swift 1f3e159cfe518fb) Target: x86_64-unknown-linux-gnu
Swift version 5.7.1 (swift-5.7.1-RELEASE) Target: x86_64-unknown-linux-gnu
import Foundation extension NSLock { func synchronized<T>(_ closure: () throws -> T) rethrows -> T { self.lock() defer { self.unlock() } return try closure() } } func test() throws { let task = Process() task.executableURL = URL(fileURLWithPath: "/usr/bin/which") task.arguments = [] let stdoutPipe = Pipe() let dataLock = NSLock() task.standardOutput = stdoutPipe var stdoutData = Data() stdoutPipe.fileHandleForReading.readabilityHandler = { fh in dataLock.synchronized { stdoutData.append(Data()) } } try task.run() task.waitUntilExit() stdoutPipe.fileHandleForReading.readabilityHandler = nil try dataLock.synchronized { if let d = try stdoutPipe.fileHandleForReading.readToEnd() { stdoutData.append(d) } } } for _ in 0..<100 { DispatchQueue.global().async { try! test() } }
(edited)import Foundation extension NSLock { func synchronized<T>(_ closure: () throws -> T) rethrows -> T { self.lock() defer { self.unlock() } return try closure() } } func test() throws { let task = Process() task.executableURL = URL(fileURLWithPath: "/usr/bin/which") task.arguments = [] let stdoutPipe = Pipe() let dataLock = NSLock() task.standardOutput = stdoutPipe var stdoutData = Data() stdoutPipe.fileHandleForReading.readabilityHandler = { fh in dataLock.synchronized { stdoutData.append(Data()) } } try task.run() task.waitUntilExit() stdoutPipe.fileHandleForReading.readabilityHandler = nil try dataLock.synchronized { if let d = try stdoutPipe.fileHandleForReading.readToEnd() { stdoutData.append(d) } } } for _ in 0..<100 { DispatchQueue.global().async { try! test() } }
(edited)import Foundation extension NSLock { func synchronized<T>(_ closure: () throws -> T) rethrows -> T { self.lock() defer { self.unlock() } return try closure() } } func test() throws { let task = Process() task.executableURL = URL(fileURLWithPath: "/usr/bin/which") task.arguments = [] let stdoutPipe = Pipe() let dataLock = NSLock() task.standardOutput = stdoutPipe var stdoutData = Data() stdoutPipe.fileHandleForReading.readabilityHandler = { fh in dataLock.synchronized { stdoutData.append(Data()) } } try task.run() task.waitUntilExit() stdoutPipe.fileHandleForReading.readabilityHandler = nil try dataLock.synchronized { if let d = try stdoutPipe.fileHandleForReading.readToEnd() { stdoutData.append(d) } } } for _ in 0..<100 { DispatchQueue.global().async { try! test() } }
(edited)curl -X POST "https://swiftfiddle.com/runner/5.7/run" \ -H "Content-Type:application/json" \ --data '{"code": "import Foundation\nprint(\"Hello World\")"}'
あとBotのホスティング1台で済むのなら私が使ってるDigitalOceanのサーバのリソースを余らせてるのでそこにデプロイしますよ。Swift version 5.8-dev (LLVM 0e21831b79c13d9, Swift 87b9e5758b1c75f) Target: x86_64-unknown-linux-gnu
protocol P1<C> { associatedtype C } protocol P2<C> { associatedtype C func f() -> any P1<C> } func g(_ p: any P2) { let _ = p.f() }
(edited)protocol P1<C> { associatedtype C } protocol P2<C> { associatedtype C func f() -> any P1<C> } func g(_ p: any P2) { let _ = p.f() }
(edited)Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7.2 (swift-5.7.2-RELEASE) 2. Compiling with the current language version 3. While evaluating request TypeCheckSourceFileRequest(source_file "<stdin>") 4. While evaluating request TypeCheckFunctionBodyRequest(main.(file).g@<stdin>:10:6) 5. While type-checking statement at [<stdin>:10:21 - line:12:1] RangeText="{ let _ = p.f() " 6. While type-checking declaration 0x560c45448848 (at <stdin>:11:5) 7. While evaluating request PatternBindingEntryRequest((unknown decl), 0, 0) 8. While type-checking expression at [<stdin>:11:13 - line:11:17] RangeText="p.f(" 9. While type-checking-target starting at <stdin>:11:15 Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend(+0x551a103)[0x560c41ab1103] /usr/bin/swift-frontend(+0x551802e)[0x560c41aaf02e] /usr/bin/swift-frontend(+0x551a48a)[0x560c41ab148a] /lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7fc37a23d520] /usr/bin/swift-frontend(+0x16fbd24)[0x560c3dc92d24] /usr/bin/swift-frontend(+0x17205b8)[0x560c3dcb75b8] /usr/bin/swift-frontend(+0x16fbb8b)[0x560c3dc92b8b] /usr/bin/swift-frontend(+0x16fa3b7)[0x560c3dc913b7] /usr/bin/swift-frontend(+0x171e6bf)[0x560c3dcb56bf] /usr/bin/swift-frontend(+0x16f9375)[0x560c3dc90375] /usr/bin/swift-frontend(+0x16f83a1)[0x560c3dc8f3a1] /usr/bin/swift-frontend(+0x15f8b31)[0x560c3db8fb31] /usr/bin/swift-frontend(+0x15f88a4)[0x560c3db8f8a4] /usr/bin/swift-frontend(+0x15f9e08)[0x560c3db90e08] /usr/bin/swift-frontend(+0x15f9ff7)[0x560c3db90ff7] /usr/bin/swift-frontend(+0x16b46a1)[0x560c3dc4b6a1] /usr/bin/swift-frontend(+0x1617d12)[0x560c3dbaed12] /usr/bin/swift-frontend(+0x160a727)[0x560c3dba1727] /usr/bin/swift-frontend(+0x162
(edited)protocol P1<C> { associatedtype C } protocol P2<C> { associatedtype C func f() -> any P1<C> } func g(_ p: any P2) { let _ = p.f() }
(edited)Unhandled coercion: (existential_type (protocol_composition_type)) (opened_archetype_type address=0xad7f7b8 (interface_type=dependent_member_type assoc_type=main.(file).P2.C@<stdin>:6:20 (base=generic_type_param_type depth=0 index=0)) (opened_existential=existential_type (protocol_type decl=main.(file).P2@<stdin>:5:10)) opened_existential_id=95EB1234-89D8-11ED-8FD6-4280E2F077D9) Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.8-dev (LLVM 0e21831b79c13d9, Swift a2934c0a847db7a) 2. Compiling with the current language version 3. While evaluating request TypeCheckSourceFileRequest(source_file "<stdin>") 4. While evaluating request TypeCheckFunctionBodyRequest(main.(file).g@<stdin>:10:6) 5. While type-checking statement at [<stdin>:10:21 - line:12:1] RangeText="{ let _ = p.f() " 6. While type-checking declaration 0xad5d230 (at <stdin>:11:5) 7. While evaluating request PatternBindingEntryRequest((unknown decl), 0, 0) 8. While type-checking expression at [<stdin>:11:13 - line:11:17] RangeText="p.f(" 9. While type-checking-target starting at <stdin>:11:15 Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it): /usr/bin/swift-frontend[0x6543683] /usr/bin/swift-frontend[0x65413be] /usr/bin/swift-frontend[0x6543a0f] /lib/x86_64-linux-gnu/libpthread.so.0(+0x14420)[0x7fa21cd94420] /lib/x86_64-linux-gnu/libc.so.6(gsignal+0xcb)[0x7fa21c20500b] /lib/x86_64-linux-gnu/libc.so.6(abort+0x12b)[0x7fa21c1e4859] /usr/bin/swift-frontend[0x1ada7cb] /usr/bin/swift-frontend[0x1af9f69] /usr/bin/swift-frontend[0x1afc38d] /usr/bin/swift-frontend[0x1ada046] /usr/bin/swift-frontend[0x1ad646a] /usr/bin/swift-frontend[0x1ad523e] /usr/bin/swift-frontend[0x1ad3532] /usr/bin/swift-fro
fatalError("llvm-symbolizer入れました")
fatalError("llvm-symbolizer入れました")
main/<stdin>:1: Fatal error: llvm-symbolizer入れました Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -O -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.8-dev (LLVM ab856b0fa3177ee, Swift 71c62c04ace2b5b) 2. Compiling with the current language version 3. While running user code "<stdin>" #0 0x00005634ff32ac63 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/usr/bin/swift-frontend+0x6989c63) #1 0x00005634ff328a3e llvm::sys::RunSignalHandlers() (/usr/bin/swift-frontend+0x6987a3e) #2 0x00005634ff32afea SignalHandler(int) Signals.cpp:0:0 #3 0x00007fbdae785520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520) #4 0x00007fbdaee57558 $ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_SSAHSus6UInt32VtF (/usr/lib/swift/linux/libswiftCore.so+0x15e558) #5 0x00007fbdaecf8077 #6 0x00005634f98382fd llvm::orc::runAsMain(int (*)(int, char**), llvm::ArrayRef<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, llvm::Optional<llvm::StringRef>) (/usr/bin/swift-frontend+0xe972fd) #7 0x00005634f96de3d8 swift::RunImmediately(swift::CompilerInstance&, std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, swift::IRGenOptions const&, swift::SILOptions const&, std::unique_ptr<swift::SILModule, std::default_delete<swift::SILModule> >&&) (/usr/bin/swift-frontend+0xd3d3d8) #8 0x00005634f9698b30 processCommandLineAndRunImmediately(swift::CompilerInstance&, std::unique_ptr<swift::SILModule, std::default_delete<swift::SILModule> >&&, llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, swift::FrontendObserver*, int&) FrontendTool.cpp:0:0 #9 0x00005634f969445b performCompileStepsPostSILGen(swift::CompilerInstance&, std::unique_ptr<swif
fatalError("llvm-symbolizer入れました")
fatalError("出力を添付ファイルとしてアップロードするテスト")
fatalError("出力を添付ファイルとしてアップロードするテスト")
fatalError("出力が20行以上もしくは2000文字以上になったら、出力の先頭3行を本文へ切り出し、全文をファイルとしてアップロードする")
(edited)fatalError("出力が20行以上もしくは2000文字以上になったら、出力の先頭3行を本文へ切り出し、全文をファイルとしてアップロードする")
(edited)main/<stdin>:1: Fatal error: 出力が20行以上もしくは2000文字以上になったら、出力の先頭3行を本文へ切り出し、全文をファイルとしてアップロードする Current stack trace: 0 libswiftCore.so 0x00007f48f5378460 _swift_stdlib_reportFatalErrorInFile + 112
(edited).swift
拡張子をもつ添付ファイルを実行 カレントディレクトリに生成されたファイルをアップロード @swift-5.8.1.swift
拡張子をもつ添付ファイルを実行 カレントディレクトリに生成されたファイルをアップロード @swift-5.8.1 print("Hello world!")
(edited)print("Hello world!")
(edited)Hello world!
(edited)protocol P<A> { associatedtype A } struct S: P<String> {} func f<T: P<String>>(_ a: T) {}
protocol P<A> { associatedtype A } struct S: P<String> {} func f<T: P<String>>(_ a: T) {}
<stdin>:4:8: error: cannot inherit from protocol type with generic argument 'P<String>' struct S: P<String> {} ^ <stdin>:4:8: error: type 'S' does not conform to protocol 'P' struct S: P<String> {} ^ <stdin>:2:18: note: protocol requires nested type 'A'; do you want to add it? associatedtype A ^
protocol P<A> { associatedtype A } struct S: P<String> {} func f<T: P<String>>(_ a: T) {}
<stdin>:4:8: error: cannot inherit from protocol type with generic argument 'P<String>' struct S: P<String> {} ^ <stdin>:4:8: error: type 'S' does not conform to protocol 'P' struct S: P<String> {} ^ <stdin>:2:18: note: protocol requires nested type 'A'; do you want to add it? associatedtype A ^
protocol P<A> { associatedtype A } struct S: P<String> {} func f<T: P<String>>(_ a: T) {}
<stdin>:4:8: error: cannot inherit from protocol type with generic argument 'P<String>' struct S: P<String> {} ^ <stdin>:4:8: error: type 'S' does not conform to protocol 'P' struct S: P<String> {} ^ <stdin>:2:18: note: protocol requires nested type 'A'; do you want to add it? associatedtype A ^
protocol P { func p() } struct Box<T> { var value: T } func f() -> Box<some P> { struct S: P { func p() { print("S in f()") } } return Box(value: S()) } let result = f() result.value.p()
(edited)protocol P { func p() } struct Box<T> { var value: T } func f() -> Box<some P> { struct S: P { func p() { print("S in f()") } } return Box(value: S()) } let result = f() result.value.p()
(edited)S in f()
(edited)protocol P { func p() } struct Box<T> { var value: T } func f() -> Box<some P> { struct S: P { func p() { print("S in f()") } } return Box(value: S()) } let result = f() result.value.p()
(edited)Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.7.3 (swift-5.7.3-RELEASE)
(edited)protocol P { func p() } struct Box<T> { var value: T } func f() -> Box<some P> { struct S: P { func p() { print("S in f()") } } return Box(value: S()) } let result = f() result.value.p()
(edited)Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main 1. Swift version 5.8-dev (LLVM 44d4f9d4b49845f, Swift b9562e1a860ec0b)
timeout
がSIGSEGV
を捕捉した場合(128+11)かな? (edited)swift
の実行はenv
とtimeout
を挟んでこんな感じ。 /usr/bin/env -i PATH\=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin timeout --signal\=KILL 30 swift -
Swift version 5.9-dev (LLVM a34ab3cb279018d, Swift 7abb1e5f91476e2) Target: x86_64-unknown-linux-gnu
Swift version 5.8 (swift-5.8-RELEASE) Target: x86_64-unknown-linux-gnu
func p(to output: inout TextOutputStream) { print("", to: &output) }
func p(to output: inout TextOutputStream) { print("", to: &output) }
import Foundation let url = URL(fileURLWithPath: "/tmp") print(url.appendingPathComponent(""))
(edited)import Foundation let url = URL(fileURLWithPath: "/tmp") print(url.appendingPathComponent(""))
(edited)file:///tmp//
(edited)import Foundation let url = URL(fileURLWithPath: "/tmp") print(url.appendingPathComponent(""))
(edited)file:///tmp//
(edited)import _Observation public final class MyObject: Observable { public var someProperty: String = "AAAA" public var someOtherProperty: Int = 0 let observationRegistrar = ObservationRegistrar<MyObject>() public func changes<Isolation>(for properties: TrackedProperties<MyObject>, isolatedTo isolation: Isolation) -> ObservedChanges<MyObject, Isolation> where Isolation : Actor { observationRegistrar.changes(for: properties, isolatedTo: isolation) } public func values<Member>(for keyPath: KeyPath<MyObject, Member>) -> ObservedValues<MyObject, Member> where Member : Sendable { observationRegistrar.values(for: keyPath) } }
import _Observation public final class MyObject: Observable { public var someProperty: String = "AAAA" public var someOtherProperty: Int = 0 let observationRegistrar = ObservationRegistrar<MyObject>() public func changes<Isolation>(for properties: TrackedProperties<MyObject>, isolatedTo isolation: Isolation) -> ObservedChanges<MyObject, Isolation> where Isolation : Actor { observationRegistrar.changes(for: properties, isolatedTo: isolation) } public func values<Member>(for keyPath: KeyPath<MyObject, Member>) -> ObservedValues<MyObject, Member> where Member : Sendable { observationRegistrar.values(for: keyPath) } }
import _Observation @Observable final class ChangesExample { @MainActor var someField: Int = 0 @MainActor var someOtherField: String = "" }
import _Observation @Observable final class ChangesExample { @MainActor var someField: Int = 0 @MainActor var someOtherField: String = "" }
<stdin>:3:1: error: unknown attribute 'Observable' @Observable final class ChangesExample { ^
var output: TextOutputStream = "" print("", to: &output)
var output: TextOutputStream = "" print("", to: &output)
<stdin>:2:1: error: protocol type 'TextOutputStream' cannot conform to 'TextOutputStream' because only concrete types can conform to protocols print("", to: &output) ^
ScrollView { Image("hoge") .resizable() .scaledToFit() } ScrollView(.init()) { Image("hoge") .resizable() .scaledToFit() }
上と下でImageの表示に差がでるのは何故でしょうか? 下は理想の表示になるのに対して、上だとScrollViewいっぱい?に大きく表示されてしまいます。class Box<T> { private var value: T init(_ value: T) { self.value = value } func mutate(_ mutation: (inout T) -> Void) { mutation(&self.value) } } func f() { let box = Box { } let s = "meow" box.mutate { value in value = { s } } } f()
(edited)class Box<T> { private var value: T init(_ value: T) { self.value = value } func mutate(_ mutation: (inout T) -> Void) { mutation(&self.value) } } func f() { let box = Box { } let s = "meow" box.mutate { value in value = { s } } } f()
(edited)<stdin>:22:13: warning: expression of type 'String' is unused s ^
(edited)class Box<T> { private var value: T init(_ value: T) { self.value = value } func mutate(_ mutation: (inout T) -> Void) { mutation(&self.value) } } func f() { let box = Box { } let s = "meow" box.mutate { value in value = { s } } } f()
class Box<T> { private var value: T init(_ value: T) { self.value = value } func mutate(_ mutation: (inout T) -> Void) { mutation(&self.value) } } func f() { let box = Box { } let s = "meow" box.mutate { value in value = { s } } } f()
<stdin>:22:13: warning: expression of type 'String' is unused s ^
class Box<T> { private var value: T init(_ value: T) { self.value = value } func mutate(_ mutation: (inout T) -> Void) { mutation(&self.value) } } func f() { let box = Box { } let s = "meow" box.mutate { value in value = { s } } } f()
class Box<T> { private var value: T init(_ value: T) { self.value = value } func mutate(_ mutation: (inout T) -> Void) { mutation(&self.value) } } func f() { let box = Box { } let s = "meow" box.mutate { value in value = { s } } } f()
<stdin>:22:13: warning: expression of type 'String' is unused s ^
class Box<T> { private var value: T init(_ value: T) { self.value = value } func mutate(_ mutation: (inout T) -> Void) { mutation(&self.value) } } func f() { let box = Box { } let s = "meow" box.mutate { value in value = { s } } } f()
class Box<T> { private var value: T init(_ value: T) { self.value = value } func mutate(_ mutation: (inout T) -> Void) { mutation(&self.value) } } func f() { let box = Box { } let s = "meow" box.mutate { value in value = { s } } } f()
<stdin>:22:13: warning: expression of type 'String' is unused s ^
protocol Foo {} struct A { var x: Foo var y: Codable var z: Error }
protocol Foo {} struct A { var x: Foo var y: Codable var z: Error }
<stdin>:3:12: error: use of protocol 'Foo' as a type must be written 'any Foo' var x: Foo ^~~ any Foo
protocol Foo {} struct A { var x: Foo var y: Codable var z: Error }
protocol Foo {} struct A { var x: Foo var y: Codable var z: Error }
<stdin>:3:12: error: use of protocol 'Foo' as a type must be written 'any Foo' var x: Foo ^~~ any Foo <stdin>:4:12: error: use of 'Codable' (aka 'Decodable & Encodable') as a type must be written 'any Codable' (aka 'any Decodable & Encodable') var y: Codable ^~~~~~~ any Codable <stdin>:4:12: error: use of 'Codable' (aka 'Decodable & Encodable') as a type must be written 'any Codable' (aka 'any Decodable & Encodable') var y: Codable ^~~~~~~ any Codable <stdin>:5:12: error: use of protocol 'Error' as a type must be written 'any Error' var z: Error ^~~~~ any Error
func foo() -> Result<Int, Error> { fatalError() }
func foo() -> Result<Int, Error> { fatalError() }
<stdin>:1:27: error: use of protocol 'Error' as a type must be written 'any Error' func foo() -> Result<Int, Error> { fatalError() } ^~~~~ any Error
import Foundation URL(fileURLWithPath: ".").appending(path: "foo")
import Foundation URL(fileURLWithPath: ".").appending(path: "foo")
<stdin>:2:27: error: value of type 'URL' has no member 'appending' URL(fileURLWithPath: ".").appending(path: "foo") ~~~~~~~~~~~~~~~~~~~~~~~~~ ^~~~~~~~~
func animate( animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil ) { print("animations") animations() print("completion") completion?(true) } animate { print(1) }
func animate( animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil ) { print("animations") animations() print("completion") completion?(true) } animate { print(1) }
<stdin>:11:16: error: missing argument for parameter 'animations' in call animate { print(1) } ^ (animations: <#() -> Void#>) <stdin>:1:14: note: 'animate(animations:completion:)' declared here func animate( ^ <stdin>:11:17: error: cannot convert value of type '() -> ()' to expected argument type '((Bool) -> Void)?' animate { print(1) } ^
func animate( animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil ) { print("animations") animations() print("completion") completion?(true) } animate { print(1) }
animations 1 completion
func animate( animations: (() -> Void)? = nil, completion: (() -> Void)? = nil ) { print("animations") animations?() print("completion") completion?() } animate { print(1) }
func animate( animations: (() -> Void)? = nil, completion: (() -> Void)? = nil ) { print("animations") animations?() print("completion") completion?() } animate { print(1) }
animations completion 1
func animate( animations: (() -> Void)? = nil, completion: (() -> Void)? = nil ) { print("animations") animations?() print("completion") completion?() } animate { print(1) }
animations completion 1
<stdin>:11:17: warning: backward matching of the unlabeled trailing closure is deprecated; label the argument with 'completion' to suppress this warning animate { print(1) } ^ (completion: ) <stdin>:1:14: note: 'animate(animations:completion:)' declared here func animate( ^
func animate( animations: (() -> Void)? = nil, completion: (() -> Void)? = nil ) { print("animations") animations?() print("completion") completion?() } animate { print(1) }
func animate( animations: (() -> Void)? = nil, completion: (() -> Void)? = nil ) { print("animations") animations?() print("completion") completion?() } animate { print(1) }
animations 1 completion
func animate( animations: (() -> Void)? = nil, completion: (() -> Void)? = nil ) { print("animations") animations?() print("completion") completion?() } animate { print(1) }
func animate( animations: (() -> Void)? = nil, completion: (() -> Void)? = nil ) { print("animations") animations?() print("completion") completion?() } animate { print(1) }
animations completion 1
<stdin>:11:17: warning: backward matching of the unlabeled trailing closure is deprecated; label the argument with 'completion' to suppress this warning animate { print(1) } ^ (completion: ) <stdin>:1:14: note: 'animate(animations:completion:)' declared here func animate( ^
protocol P {} protocol Q<T> { associatedtype T } typealias PQ<T> = P & Q<T> func f() { let foo: any Q<Int> let bar: any P & Q<Int> let baz: any (P & Q<Int>) let qux: any PQ<Int> }
(edited)protocol P {} protocol Q<T> { associatedtype T } typealias PQ<T> = P & Q<T> func f() { let foo: any Q<Int> let bar: any P & Q<Int> let baz: any (P & Q<Int>) let qux: any PQ<Int> }
(edited)<stdin>:8:22: error: non-protocol, non-class type 'Q<Int>' cannot be used within a protocol-constrained type let bar: any P & Q<Int> ^ <stdin>:9:23: error: non-protocol, non-class type 'Q<Int>' cannot be used within a protocol-constrained type let baz: any (P & Q<Int>) ^
(edited)protocol P {} protocol Q<T> { associatedtype T } typealias PQ<T> = P & Q<T> func f() { let foo: any Q<Int> let bar: any P & Q<Int> let baz: any (P & Q<Int>) let qux: any PQ<Int> }
(edited)<stdin>:8:22: error: non-protocol, non-class type 'Q<Int>' cannot be used within a protocol-constrained type let bar: any P & Q<Int> ^ <stdin>:9:23: error: non-protocol, non-class type 'Q<Int>' cannot be used within a protocol-constrained type let baz: any (P & Q<Int>) ^
(edited)/// Not supported as a protocol composition term for now protocol SomeProto {} func protocolCompositionNotSupported1(_: SomeProto & Sequence<Int>) {} // expected-error@-1 {{non-protocol, non-class type 'Sequence<Int>' cannot be used within a protocol-constrained type}} func protocolCompositionNotSupported2(_: any SomeProto & Sequence<Int>) {} // expected-error@-1 {{non-protocol, non-class type 'Sequence<Int>' cannot be used within a protocol-constrained type}}
protocol Middleware<Input, Output, NextInput, NextOutput> { associatedtype Input associatedtype Output associatedtype NextInput associatedtype NextOutput } protocol Routes<Input, Output> { associatedtype Input associatedtype Output } extension Routes { func compose<M>(_ middleware: M) -> any Routes<M.NextInput, M.NextOutput> where M: Middleware, M.Input == Input, M.Output == Output { fatalError() } func mapInput<NewInput>( _ transform: @escaping (Input) -> NewInput ) -> any Routes<NewInput, Output> { fatalError() } } struct Request {} struct Response {} struct User {} struct AuthMiddleware<Input, Output>: Middleware { typealias NextInput = (Input, login: User) typealias NextOutput = Output } func main(routes: any Routes<Request, Response>) { let routes = routes.compose(AuthMiddleware()) .mapInput { (request: $0.0, login: $0.login) } }
protocol Middleware<Input, Output, NextInput, NextOutput> { associatedtype Input associatedtype Output associatedtype NextInput associatedtype NextOutput } protocol Routes<Input, Output> { associatedtype Input associatedtype Output } extension Routes { func compose<M>(_ middleware: M) -> any Routes<M.NextInput, M.NextOutput> where M: Middleware, M.Input == Input, M.Output == Output { fatalError() } func mapInput<NewInput>( _ transform: @escaping (Input) -> NewInput ) -> any Routes<NewInput, Output> { fatalError() } } struct Request {} struct Response {} struct User {} struct AuthMiddleware<Input, Output>: Middleware { typealias NextInput = (Input, login: User) typealias NextOutput = Output } func main(routes: any Routes<Request, Response>) { let routes = routes.compose(AuthMiddleware()) .mapInput { (request: $0.0, login: $0.login) } }
<stdin>:39:9: warning: initialization of immutable value 'routes' was never used; consider replacing with assignment to '_' or removing it let routes = routes.compose(AuthMiddleware()) ~~~~^~~~~~
protocol Middleware<Input, Output, NextInput, NextOutput> { associatedtype Input associatedtype Output associatedtype NextInput associatedtype NextOutput } protocol Routes<Input, Output> { associatedtype Input associatedtype Output } extension Routes { func compose<M>(_ middleware: M) -> any Routes<M.NextInput, M.NextOutput> where M: Middleware, M.Input == Input, M.Output == Output { fatalError() } func mapInput<NewInput>( _ transform: @escaping (Input) -> NewInput ) -> any Routes<NewInput, Output> { fatalError() } } struct Request {} struct Response {} struct User {} struct AuthMiddleware<Input, Output>: Middleware { typealias NextInput = (Input, login: User) typealias NextOutput = Output } func main(routes: any Routes<Request, Response>) { let routes = routes.compose(AuthMiddleware()) .mapInput { (request: $0.0, login: $0.login) } }
swift-frontend: /home/build-user/swift/lib/AST/RequirementMachine/Symbol.cpp:93: swift::rewriting::Symbol::Storage::Storage(Symbol::Kind, swift::CanType, ArrayRef<swift::rewriting::Term>): Assertion `!type->hasTypeVariable()' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -plugin-path /usr/lib/swift/host/plugins -plugin-path /usr/local/lib/swift/host/plugins -resource-dir /usr/lib/swift -module-name main
protocol Middleware<Input, Output, NextInput, NextOutput> { associatedtype Input associatedtype Output associatedtype NextInput associatedtype NextOutput } protocol Routes<Input, Output> { associatedtype Input associatedtype Output } extension Routes { func compose<M>(_ middleware: M) -> any Routes<M.NextInput, M.NextOutput> where M: Middleware, M.Input == Input, M.Output == Output { fatalError() } func mapInput<NewInput>( _ transform: @escaping (Input) -> NewInput ) -> any Routes<NewInput, Output> { fatalError() } } struct Request {} struct Response {} struct User {} struct AuthMiddleware<Input, Output>: Middleware { typealias NextInput = (Input, login: User) typealias NextOutput = Output } func main(routes: any Routes<Request, Response>) { let routes = routes.compose(AuthMiddleware()) .mapInput { (request: $0.0, login: $0.login) } }
swift-frontend: /home/build-user/swift/lib/AST/RequirementMachine/Symbol.cpp:93: swift::rewriting::Symbol::Storage::Storage(Symbol::Kind, swift::CanType, ArrayRef<swift::rewriting::Term>): Assertion `!type->hasTypeVariable()' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -plugin-path /usr/lib/swift/host/plugins -plugin-path /usr/local/lib/swift/host/plugins -resource-dir /usr/lib/swift -module-name main
swift:5.8.1
来てるのにボットが更新されないの何故かと調べたら、arm64しか更新されてないからだった。swift:5.8.1
来てるのにボットが更新されないの何故かと調べたら、arm64しか更新されてないからだった。 Swift version 5.8 (swift-5.8-RELEASE) Target: x86_64-unknown-linux-gnu
swift-5.8.1-RELEASE
ですが、amd64だとswift-5.8-RELEASE
になってます。let flag = Bool.random() let num1 = if flag { 1.0 } else { 0.5 } let num2 = flag ? 1.0 : 0.5 let num3 = flag ? 1.0 : if flag { 1.0 } else { 0.5 }
let flag = Bool.random() let num1 = if flag { 1.0 } else { 0.5 } let num2 = flag ? 1.0 : 0.5 let num3 = flag ? 1.0 : if flag { 1.0 } else { 0.5 }
<stdin>:5:25: error: 'if' may only be used as expression in return, throw, or as the source of an assignment let num3 = flag ? 1.0 : if flag { 1.0 } else { 0.5 } ^
<stdin>:5:25: error: 'if' may only be used as expression in return, throw, or as the source of an assignment let num3 = flag ? 1.0 : if flag { 1.0 } else { 0.5 } ^
func check<each T>(_ val: repeat each T) { print("check begin") repeat print(each val, terminator: " ") print("\ncheck end") } check(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250)
func check<each T>(_ val: repeat each T) { print("check begin") repeat print(each val, terminator: " ") print("\ncheck end") } check(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250)
check begin 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 check end
print(if Bool.random() { 1 } else { 2 })
print(if Bool.random() { 1 } else { 2 })
<stdin>:1:7: error: 'if' may only be used as expression in return, throw, or as the source of an assignment print(if Bool.random() { 1 } else { 2 }) ^
let v = if Bool.random() { 1 } else { 2 } print(v)
let v = if Bool.random() { 1 } else { 2 } print(v)
2
struct Foo: ~Copyable { consuming func foo() { _ = consume self } }
struct Foo: ~Copyable { consuming func foo() { _ = consume self } }
enum E: Int32, CaseIterable { case aaa case bbb = -1 case ccc } print(E.allCases.map(\.rawValue))
enum E: Int32, CaseIterable { case aaa case bbb = -1 case ccc } print(E.allCases.map(\.rawValue))
<stdin>:4:8: error: raw value for enum case is not unique case ccc ^ <stdin>:3:14: note: raw value auto-incremented from here case bbb = -1 ^ <stdin>:2:8: note: raw value previously used here case aaa ^ <stdin>:2:8: note: raw value implicitly auto-incremented from zero case aaa ^
1
になったりするのではなく、エラーとして検出されるenum E { case foo(values: Int...) }
(edited)enum E { case foo(values: Int...) }
(edited)<stdin>:2:12: error: variadic enum cases are not supported case foo(values: Int...) ^
(edited)import Foundation let data = """ "Hello" """.data(using: .utf8)! print(try! JSONDecoder().decode(String.self, from: data))
(edited)import Foundation let data = """ "Hello" """.data(using: .utf8)! print(try! JSONDecoder().decode(String.self, from: data))
(edited)Hello
import Foundation let data = """ "Hello" """.data(using: .utf8)! print(try! JSONDecoder().decode(String.self, from: data))
(edited)<stdin>:5:23: error: argument passed to call that takes no arguments print(try! JSONDecoder(String.self, from: data)) ^~~~~~~~~~~~~~~~~~~~~~~~~
import Foundation let data = """ "Hello" """.data(using: .utf8)! print(try! JSONDecoder().decode(String.self, from: data))
(edited)<stdin>:5:52: error: value of optional type 'Data?' must be unwrapped to a value of type 'Data' print(try! JSONDecoder().decode(String.self, from: data)) ^ <stdin>:5:52: note: coalesce using '??' to provide a default when the optional value contains 'nil' print(try! JSONDecoder().decode(String.self, from: data)) ^ ?? <#default value#> <stdin>:5:52: note: force-unwrap using '!' to abort execution if the optional value contains 'nil' print(try! JSONDecoder().decode(String.self, from: data)) ^ !
import Foundation let data = """ "Hello" """.data(using: .utf8)! print(try! JSONDecoder().decode(String.self, from: data))
(edited)Hello
Swift version 5.9-dev (LLVM df22cff92bb6f9d, Swift fdf50a99df2d1b0) Target: x86_64-unknown-linux-gnu
(edited)import Foundation struct TupleValue<T> { let value: T init(_ value: T) { print("✅", "init Type-A") self.value = value } init<each C>(_ value: T) where T == (repeat each C) { print("✅", "init Type-B") self.value = (repeat each value) } } _ = TupleValue(1) _ = TupleValue((1, 2))
Swift version 5.9-dev (LLVM 3708b80be7731a7, Swift aaafc31485ff571) Target: x86_64-unknown-linux-gnu
import Foundation struct TupleValue<T> { let value: T init(_ value: T) { print("✅", "init Type-A") self.value = value } init<each C>(_ value: T) where T == (repeat each C) { print("✅", "init Type-B") self.value = (repeat each value) } } _ = TupleValue(1) _ = TupleValue((1, 2))
✅ init Type-A ✅ init Type-A
Swift version 5.9 (swift-5.9-RELEASE) Target: x86_64-unknown-linux-gnu
var a = 1 let b = consume a
var a = 1 let b = consume a
<stdin>:2:17: error: 'consume' applied to value that the compiler does not support. This is a compiler bug. Please file a bug with a small example of the bug let b = consume a ^
var a = "" let b = consume a
var a = "" let b = consume a
<stdin>:2:17: error: 'consume' applied to value that the compiler does not support. This is a compiler bug. Please file a bug with a small example of the bug let b = consume a ^
func main() { var a = "" let b = consume a }
func main() { var a = "" let b = consume a }
<stdin>:2:7: warning: variable 'a' was never mutated; consider changing to 'let' constant var a = "" ~~~ ^ let <stdin>:3:7: warning: initialization of immutable value 'b' was never used; consider replacing with assignment to '_' or removing it let b = consume a ~~~~^ _
func main() { var a = 1 let b = consume a }
func main() { var a = 1 let b = consume a }
<stdin>:2:7: warning: variable 'a' was never mutated; consider changing to 'let' constant var a = 1 ~~~ ^ let <stdin>:3:7: warning: initialization of immutable value 'b' was never used; consider replacing with assignment to '_' or removing it let b = consume a ~~~~^ _ <stdin>:3:19: error: 'consume' applied to value that the compiler does not support. This is a compiler bug. Please file a bug with a small example of the bug let b = consume a ^
public func callee() async -> (() -> ()) { fatalError() } public func caller() async { async let future = callee() let result = await future result() }
public func callee() async -> (() -> ()) { fatalError() } public func caller() async { async let future = callee() let result = await future result() }
<unknown>:0: error: fatal error encountered during compilation; please submit a bug report (https://swift.org/contributing/#reporting-bugs) <unknown>:0: note: SmallVector unable to grow. Requested capacity (4294967296) is larger than maximum value for size type (4294967295) Stack dump:
public func callee() async -> (() -> ()) { fatalError() } public func caller() async { async let future = callee() let result = await future result() }
public func callee() async -> (() -> ()) { fatalError() } public func caller() async { async let future = callee() let result = await future result() }
<unknown>:0: error: fatal error encountered during compilation; please submit a bug report (https://swift.org/contributing/#reporting-bugs) <unknown>:0: note: SmallVector unable to grow. Requested capacity (4294967296) is larger than maximum value for size type (4294967295) Stack dump:
public func callee() async -> (() -> ()) { fatalError() } public func caller() async { async let future = callee() let result = await future result() }
public func callee() async -> (() -> ()) { fatalError() } public func caller() async { async let future = callee() let result = await future result() }
swift-frontend: /home/build-user/swift/lib/SILGen/SILGenPoly.cpp:2859: void (anonymous namespace)::ResultPlanner::plan(swift::Lowering::AbstractionPattern, swift::CanType, swift::Lowering::AbstractionPattern, swift::CanType, swift::CanSILFunctionType, swift::CanSILFunctionType): Assertion `AllInnerResults.empty()' failed. Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main -plugin-path /usr/lib/swift/host/plugins -plugin-path /usr/local/lib/swift/host/plugins
public func callee() async -> (() -> ()) { fatalError() } public func caller() async { async let future = callee() let result = await future result() }
public func callee() async -> (() -> ()) { fatalError() } public func caller() async { async let future = callee() let result = await future result() }
$s11SwiftSyntax09AttributeB0V9argumentsAC9ArgumentsOSgvg ---> SwiftSyntax.AttributeSyntax.arguments.getter : SwiftSyntax.AttributeSyntax.Arguments?
var a = [1] a.popFirst()
var a = [1] a.popFirst()
<stdin>:2:3: error: referencing instance method 'popFirst()' on 'Collection' requires the types '[Int]' and 'ArraySlice<Int>' be equivalent a.popFirst() ^ Swift.Collection:1:11: note: where 'Self' = '[Int]', 'Self.SubSequence' = 'ArraySlice<Int>' extension Collection where Self == Self.SubSequence { ^
var a = [1, 2] var b = a[...] print(b) print(b.popFirst()) print(b)
var a = [1, 2] var b = a[...] print(b) print(b.popFirst()) print(b)
[1, 2] Optional(1) [2]
<stdin>:4:7: warning: expression implicitly coerced from 'Int?' to 'Any' print(b.popFirst()) ^~~~~~~~~~~~ <stdin>:4:9: note: provide a default value to avoid this warning print(b.popFirst()) ~~^~~~~~~~~~ ?? <#default value#> <stdin>:4:9: note: force-unwrap the value to avoid this warning print(b.popFirst()) ~~^~~~~~~~~~ ! <stdin>:4:9: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(b.popFirst()) ~~^~~~~~~~~~ as Any
func use<each T>(_ values: repeat each T) { for value in repeat each values { print(type(of: value)) } }
func use<each T>(_ values: repeat each T) { for value in repeat each values { print(type(of: value)) } }
<stdin>:2:18: error: value pack expansion can only appear inside a function argument list or tuple element for value in repeat each values { ^
func use<each T>(_ values: repeat each T) { for value in repeat each values { print(type(of: value)) } }
func use<each T>(_ values: repeat each T) { for value in repeat each values { print(type(of: value)) } }
<stdin>:2:18: error: value pack expansion can only appear inside a function argument list or tuple element for value in repeat each values { ^
import _Differentiation @differentiable(reverse) func x_2(_ x: Double) -> Double { return x * x } let x: Double = 1.0 let grad_x = gradient(of: { (x: Double) in x_2(x) })(x) print(grad_x)
import _Differentiation @differentiable(reverse) func x_2(_ x: Double) -> Double { return x * x } let x: Double = 1.0 let grad_x = gradient(of: { (x: Double) in x_2(x) })(x) print(grad_x)
2.0
struct S {} extension S { func f() { _ = consume self } }
struct S {} extension S { func f() { _ = consume self } }
struct S {} extension S { func f() { _ = consume self } }
func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000_000) print(Thread.isMainThread) } Task { @MainActor in await nonIsolatedFunc() }
func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000_000) print(Thread.isMainThread) } Task { @MainActor in await nonIsolatedFunc() }
<stdin>:2:11: error: cannot find 'Thread' in scope print(Thread.isMainThread) ^~~~~~ <stdin>:5:11: error: cannot find 'Thread' in scope print(Thread.isMainThread) ^~~~~~
func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000_000) print(Thread.isMainThread) } Task { @MainActor in await nonIsolatedFunc() }
<stdin>:2:11: error: cannot find 'Thread' in scope print(Thread.isMainThread) ^~~~~~ <stdin>:5:11: error: cannot find 'Thread' in scope print(Thread.isMainThread) ^~~~~~
import Foundation func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000_000) print(Thread.isMainThread) } Task { @MainActor in await nonIsolatedFunc() }
import Foundation func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000_000) print(Thread.isMainThread) } Task { @MainActor in await nonIsolatedFunc() }
false
import Foundation func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000_000) print(Thread.isMainThread) } Task { @MainActor in await nonIsolatedFunc() }
false false
import Foundation func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000_000) print(Thread.isMainThread) } @MainActor func mainIsolatedFunc() async { await nonIsolatedFunc() } Task { await mainIsolatedFunc() }
import Foundation func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000_000) print(Thread.isMainThread) } @MainActor func mainIsolatedFunc() async { await nonIsolatedFunc() } Task { await mainIsolatedFunc() }
false
import Foundation func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000_000) print(Thread.isMainThread) } @MainActor func mainIsolatedFunc() async { await nonIsolatedFunc() } Task { await mainIsolatedFunc() }
false false
timeout: the monitored command dumped core
import Foundation func nonIsolatedFunc() async { print("nonIsolated: \(Thread.isMainThread)") } @MainActor func mainIsolatedFunc() async { print("MainActor: \(Thread.isMainThread)") await nonIsolatedFunc() } Task { await mainIsolatedFunc() }
import Foundation func nonIsolatedFunc() async { print("nonIsolated: \(Thread.isMainThread)") } @MainActor func mainIsolatedFunc() async { print("MainActor: \(Thread.isMainThread)") await nonIsolatedFunc() } Task { await mainIsolatedFunc() }
import Foundation func nonIsolatedFunc() async { print("nonIsolated: \(Thread.isMainThread)") } @MainActor func mainIsolatedFunc() async { print("MainActor: \(Thread.isMainThread)") await nonIsolatedFunc() } Task { await mainIsolatedFunc() }
import Foundation func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000) print(Thread.isMainThread) } @MainActor func mainIsolatedFunc() async { await nonIsolatedFunc() print("aaa") } Task { await mainIsolatedFunc() }
import Foundation func nonIsolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000) print(Thread.isMainThread) } @MainActor func mainIsolatedFunc() async { await nonIsolatedFunc() print("aaa") } Task { await mainIsolatedFunc() }
false
Task { @MainActor in await Task { await mainIsolatedFunc() }.value }
import Foundation let lock = NSRecursiveLock() func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor func mainIsolatedFunc() async { await nonIsolatedFunc() } Task { await mainIsolatedFunc() lock.unlock() } lock.lock()
import Foundation let lock = NSRecursiveLock() func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor func mainIsolatedFunc() async { await nonIsolatedFunc() } Task { await mainIsolatedFunc() lock.unlock() } lock.lock()
import Foundation let semaphore = DispatchSemaphore(value: 0) func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor func mainIsolatedFunc() async { await nonIsolatedFunc() } Task { await mainIsolatedFunc() semaphore.signal() } semaphore.wait()
import Foundation let semaphore = DispatchSemaphore(value: 0) func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor func mainIsolatedFunc() async { await nonIsolatedFunc() } Task { await mainIsolatedFunc() semaphore.signal() } semaphore.wait()
@main
は5.5.2だったのか (edited)import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await Task { await mainIsolatedFunc() }.value } }
import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await Task { await mainIsolatedFunc() }.value } }
error: option '-parse-as-library' is not supported by 'swift'; did you mean to use 'swiftc'?
import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await Task { await mainIsolatedFunc() }.value } }
import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await Task { await mainIsolatedFunc() }.value } }
false
@MainActor
で実験するのをやめたらどうかと思ったのです-parse-as-library
がうまくいかないtry """ import Glibc setbuf(stdout, nil) /* Start user code. Do not edit comment generated here */ \(code) """ .data(using: .utf8)? .write(to: temporaryPath.appendingPathComponent("main.swift"))
import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await Task { await mainIsolatedFunc() }.value } }
import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await Task { await mainIsolatedFunc() }.value } }
false
try """ import Glibc setbuf(stdout, nil) /* Start user code. Do not edit comment generated here */ \(code) """ .data(using: .utf8)? .write(to: temporaryPath.appendingPathComponent("main.swift"))
import Foundation func nonIsolatedFunc() async { let thread = (Thread.current.threadDictionary["thread"] as? String) ?? "runtime thread" print("\(thread) at \(#function)") } actor A { func actorMethod() async { Thread.current.threadDictionary["thread"] = "actor thread" await nonIsolatedFunc() } } @main struct Main { static func main() async { let a = A() await a.actorMethod() } }
(edited)import Foundation func nonIsolatedFunc() async { let thread = (Thread.current.threadDictionary["thread"] as? String) ?? "runtime thread" print("\(thread) at \(#function)") } actor A { func actorMethod() async { Thread.current.threadDictionary["thread"] = "actor thread" await nonIsolatedFunc() } } @main struct Main { static func main() async { let a = A() await a.actorMethod() } }
(edited)actor thread at nonIsolatedFunc()
(edited)import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @HogeActor static func isolatedFunc() async { print(Thread.isMainThread) } static func main() async { print(Thread.isMainThread) await Task { print(Thread.isMainThread) await isolatedFunc() print(Thread.isMainThread) }.value } }
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @HogeActor static func isolatedFunc() async { print(Thread.isMainThread) } static func main() async { print(Thread.isMainThread) await Task { print(Thread.isMainThread) await isolatedFunc() print(Thread.isMainThread) }.value } }
true false false false
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @HogeActor static func isolatedFunc() async { print(Thread.isMainThread) } static func main() async { print(Thread.isMainThread) await isolatedFunc() print(Thread.isMainThread) } }
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @HogeActor static func isolatedFunc() async { print(Thread.isMainThread) } static func main() async { print(Thread.isMainThread) await isolatedFunc() print(Thread.isMainThread) } }
true false false
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @HogeActor static func isolatedFunc() async { print(Thread.isMainThread) } static func main() async { print(Thread.isMainThread) await isolatedFunc() print(Thread.isMainThread) } }
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @HogeActor static func isolatedFunc() async { print(Thread.isMainThread) } static func main() async { print(Thread.isMainThread) await isolatedFunc() print(Thread.isMainThread) } }
true false false
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @HogeActor static func isolatedFunc() async { print(Thread.isMainThread) } @MainActor static func main() async { print(Thread.isMainThread) await isolatedFunc() print(Thread.isMainThread) } }
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @HogeActor static func isolatedFunc() async { print(Thread.isMainThread) } @MainActor static func main() async { print(Thread.isMainThread) await isolatedFunc() print(Thread.isMainThread) } }
true false false
@main
の main
がawait後にmain actorに戻ってこれない問題It calls some other async function which then returns, resuming the caller.
と戻ってくるケースも引き継ぐと書いてあるので true, falseになれば引き継がれることが証明できるかなと思ったんですが、mainがMainActorじゃダメですね... static func main() async { print(Thread.isMainThread) await isolatedFunc() print(Thread.isMainThread) }import Foundation func nonIsolatedFunc() async { Thread.sleep(forTimeInterval: 1) } actor A { func isolatedFunc() async { let begin = Date() print("begin") for _ in 0..<4 { Task { await nonIsolatedFunc() } } Thread.sleep(forTimeInterval: 1) let dur = Date().timeIntervalSince(begin) print("end \(dur)") } } @main struct Main { @MainActor static func main() async { await A().isolatedFunc() } }
(edited)import Foundation func nonIsolatedFunc() async { Thread.sleep(forTimeInterval: 1) } actor A { func isolatedFunc() async { let begin = Date() print("begin") for _ in 0..<4 { Task { await nonIsolatedFunc() } } Thread.sleep(forTimeInterval: 1) let dur = Date().timeIntervalSince(begin) print("end \(dur)") } } @main struct Main { @MainActor static func main() async { await A().isolatedFunc() } }
(edited)begin end 1.0875169038772583
(edited)import Foundation func nonIsolatedFunc() async { Thread.sleep(forTimeInterval: 1) } actor A { func isolatedFunc() async { let begin = Date() print("begin") for _ in 0..<32 { Task { await nonIsolatedFunc() } } Thread.sleep(forTimeInterval: 1) await Task.yield() let dur = Date().timeIntervalSince(begin) print("end \(dur)") } } @main struct Main { @MainActor static func main() async { await A().isolatedFunc() } }
(edited)import Foundation func nonIsolatedFunc() async { Thread.sleep(forTimeInterval: 1) } actor A { func isolatedFunc() async { let begin = Date() print("begin") for _ in 0..<32 { Task { await nonIsolatedFunc() } } Thread.sleep(forTimeInterval: 1) await Task.yield() let dur = Date().timeIntervalSince(begin) print("end \(dur)") } } @main struct Main { @MainActor static func main() async { await A().isolatedFunc() } }
(edited)begin end 4.000944972038269
(edited)import Foundation func nonIsolatedFunc() async { Thread.sleep(forTimeInterval: 1) } actor A { func isolatedFunc() async { let begin = Date() print("begin") for _ in 0..<32 { Task { await nonIsolatedFunc() } } Thread.sleep(forTimeInterval: 1) await Task.yield() let dur = Date().timeIntervalSince(begin) print("end \(dur)") } } @main struct Main { @MainActor static func main() async { await A().isolatedFunc() } }
import Foundation func nonIsolatedFunc() async { Thread.sleep(forTimeInterval: 1) } actor A { func isolatedFunc() async { let begin = Date() print("begin") for _ in 0..<32 { Task { await nonIsolatedFunc() } } Thread.sleep(forTimeInterval: 1) await Task.yield() let dur = Date().timeIntervalSince(begin) print("end \(dur)") } } @main struct Main { @MainActor static func main() async { await A().isolatedFunc() } }
begin end 4.000761032104492
import Foundation func nonIsolatedFunc() async { Thread.sleep(forTimeInterval: 1) } actor A { func isolatedFunc() async { let begin = Date() print("begin") for _ in 0..<32 { Task { await nonIsolatedFunc() } } Thread.sleep(forTimeInterval: 1) await Task.yield() let dur = Date().timeIntervalSince(begin) print("end \(dur)") } } @main struct Main { @MainActor static func main() async { await A().isolatedFunc() } }
import Foundation func nonIsolatedFunc() async { Thread.sleep(forTimeInterval: 1) } actor A { func isolatedFunc() async { let begin = Date() print("begin") for _ in 0..<32 { Task { await nonIsolatedFunc() } } Thread.sleep(forTimeInterval: 1) await Task.yield() let dur = Date().timeIntervalSince(begin) print("end \(dur)") } } @main struct Main { @MainActor static func main() async { await A().isolatedFunc() } }
begin end 4.016860008239746
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @MainActor static func mainActorFunc() async { } static func nonisolatedFunc() async { print(Thread.isMainThread) await mainActorFunc() print(Thread.isMainThread) } static func main() async { await Task { @HogeActor in await nonisolatedFunc() }.value } }
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @MainActor static func mainActorFunc() async { } static func nonisolatedFunc() async { print(Thread.isMainThread) await mainActorFunc() print(Thread.isMainThread) } static func main() async { await Task { @HogeActor in await nonisolatedFunc() }.value } }
false false
@_unsafeInheritExecutor This async function uses the pre-SE-0338 semantics of unsafely inheriting the caller's executor. This is an underscored feature because the right way of inheriting an executor is to pass in the required executor and switch to it. Unfortunately, there are functions in the standard library which need to inherit their caller's executor but cannot change their ABI because they were not defined as @_alwaysEmitIntoClient in the initial release.
@_unsafeInheritExecutor
つけることで実現されてたんですね@_unsafeInheritExecutor
つけることで実現されてたんですね testAsyncFunction
が (nonisolatedな)callee
を呼ぶ流れを見ると (edited)hop_to_exector
が無い (CHECK-NOT) だからcallee
が内部で自分でグローバルアクターにhopするからCHECK: hop_to_executor MyActor
ではなくCHECK NOT
なのはなぜでしょう...?CHECK: hop_to_executor MyActor
ではなくCHECK NOT
なのはなぜでしょう...? hop_to_executor.swift
をよく読めばどういう規則になっていたかわかりそうではあるimport Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @MainActor static func mainActorFunc() async { } static func nonisolatedFunc() async { print(Thread.isMainThread) await mainActorFunc() print(Thread.isMainThread) } static func main() async { await Task { @HogeActor in await nonisolatedFunc() }.value } }
import Foundation @globalActor actor HogeActor { static var shared = HogeActor() } @main struct Main { @MainActor static func mainActorFunc() async { } static func nonisolatedFunc() async { print(Thread.isMainThread) await mainActorFunc() print(Thread.isMainThread) } static func main() async { await Task { @HogeActor in await nonisolatedFunc() }.value } }
false false
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
true
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
true
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
<stdin>:4:34: error: consecutive declarations on a line must be separated by ';' static func nonisolatedFunc() async { ^
import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await mainIsolatedFunc() } }
import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await mainIsolatedFunc() } }
true
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
true
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
true
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
false
import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await Task { await mainIsolatedFunc() }.value } }
import Foundation @main struct Main { static func nonIsolatedFunc() async { print(Thread.isMainThread) } @MainActor static func mainIsolatedFunc() async { await nonIsolatedFunc() } static func main() async { await Task { await mainIsolatedFunc() }.value } }
false
import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) await Task { print(Thread.isMainThread) }.value } }
import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) await Task { print(Thread.isMainThread) }.value } }
true false
import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) await Task { print(Thread.isMainThread) }.value } }
import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) await Task { print(Thread.isMainThread) }.value } }
true false
import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) await Task { @MainActor in print(Thread.isMainThread) }.value } }
import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) await Task { @MainActor in print(Thread.isMainThread) }.value } }
true false
import Foundation @main struct Main { static func main() async { MainActor.shared.assertIsolated() await Task { @MainActor in MainActor.shared.assertIsolated() }.value } }
import Foundation @main struct Main { static func main() async { MainActor.shared.assertIsolated() await Task { @MainActor in MainActor.shared.assertIsolated() }.value } }
import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) Task { @MainActor in print(Thread.isMainThread) } print("blocking!!!") sleep(2) print("blocking end") } }
(edited)import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) Task { @MainActor in print(Thread.isMainThread) } print("blocking!!!") sleep(2) print("blocking end") } }
(edited)true blocking!!! blocking end
(edited)import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) Task { @MainActor in print(Thread.isMainThread) } print("blocking!!!") sleep(2) print("blocking end") sleep(1) } }
import Foundation @main struct Main { static func main() async { print(Thread.isMainThread) Task { @MainActor in print(Thread.isMainThread) } print("blocking!!!") sleep(2) print("blocking end") sleep(1) } }
true blocking!!! blocking end
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000) print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
(edited)import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000) print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
(edited)true false
(edited)import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000) print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
(edited)true false
(edited)import Foundation @main struct Main { static func nonisolatedFunc() async { print(Thread.isMainThread) try? await Task.sleep(nanoseconds: 1_000) print(Thread.isMainThread) } static func main() async { await nonisolatedFunc() } }
(edited)false false
(edited)import Foundation let int: Int = 0 let uint: UInt = 0 print(int == uint)
import Foundation let int: Int = 0 let uint: UInt = 0 print(int == uint)
true
==
ってIntとUInt比較できるような感じで定義されてるんですね (コード書いててコンパイル通って驚いた)actor Foo { var values: [Int] = [] func f() { Task { await useSome(values[0]) } } } func useSome(_ v: Int) async {}
actor Foo { var values: [Int] = [] func f() { Task { await useSome(values[0]) } } } func useSome(_ v: Int) async {}
<stdin>:5:27: error: actor-isolated property 'values' cannot be passed 'inout' to 'async' function call await useSome(values[0]) ^ <stdin>:2:9: note: property declared here var values: [Int] = [] ^
actor Foo { var values: [Int] = [] func f() { Task { _ = values[0] } } }
actor Foo { var values: [Int] = [] func f() { Task { _ = values[0] } } }
actor Foo { var values: [Int] = [] func f() { Task { await asyncFn() _ = values[0] } } } func asyncFn() async {}
(edited)actor Foo { var values: [Int] = [] func f() { Task { await asyncFn() _ = values[0] } } } func asyncFn() async {}
(edited){ [values]
が楽そうfunc f() -> Int { return fatalError() }
func f() -> Int { return fatalError() }
<stdin>:2:10: error: cannot convert return expression of type 'Never' to return type 'Int' return fatalError() ^~~~~~~~~~~~
import RegexBuilder let regex = Regex { "x" } let text = "xxx" print(text.matches(of: regex).count)
(edited)import RegexBuilder let regex = Regex { "x" } let text = "xxx" print(text.matches(of: regex).count)
(edited)3
(edited)import RegexBuilder let regex = Regex { NegativeLookahead { Regex { Optionally(Anchor.wordBoundary.inverted) ":" ZeroOrMore(CharacterClass.anyOf(":").inverted) } } "_" NegativeLookahead { Regex { ZeroOrMore(CharacterClass.anyOf(":").inverted) ":" Optionally(Anchor.wordBoundary.inverted) } } } let txt = "\u{200C}:c_huzer01:" _ = txt.matches(of: regex)
(edited)import RegexBuilder let regex = Regex { NegativeLookahead { Regex { Optionally(Anchor.wordBoundary.inverted) ":" ZeroOrMore(CharacterClass.anyOf(":").inverted) } } "_" NegativeLookahead { Regex { ZeroOrMore(CharacterClass.anyOf(":").inverted) ":" Optionally(Anchor.wordBoundary.inverted) } } } let txt = "\u{200C}:c_huzer01:" _ = txt.matches(of: regex)
(edited)import RegexBuilder let regex = Regex { NegativeLookahead { Regex { Optionally(Anchor.wordBoundary.inverted) ":" ZeroOrMore(CharacterClass.anyOf(":").inverted) } } "_" NegativeLookahead { Regex { ZeroOrMore(CharacterClass.anyOf(":").inverted) ":" Optionally(Anchor.wordBoundary.inverted) } } }.wordBoundaryKind(.simple) let txt = "\u{200C}:c_huzer01:" _ = txt.matches(of: regex)
import RegexBuilder let regex = Regex { NegativeLookahead { Regex { Optionally(Anchor.wordBoundary.inverted) ":" ZeroOrMore(CharacterClass.anyOf(":").inverted) } } "_" NegativeLookahead { Regex { ZeroOrMore(CharacterClass.anyOf(":").inverted) ":" Optionally(Anchor.wordBoundary.inverted) } } }.wordBoundaryKind(.simple) let txt = "\u{200C}:c_huzer01:" _ = txt.matches(of: regex)
final class C: Sendable { @MainActor var a: [Int] = [] @MainActor func b() {} func foo() async { await MainActor.run { self.a = [1] self.b() } } } @MainActor func main() async { let c = C() c.a = [1] c.b() }
final class C: Sendable { @MainActor var a: [Int] = [] @MainActor func b() {} func foo() async { await MainActor.run { self.a = [1] self.b() } } } @MainActor func main() async { let c = C() c.a = [1] c.b() }
<stdin>:2:20: warning: stored property 'a' of 'Sendable'-conforming class 'C' is mutable @MainActor var a: [Int] = [] ^
import Foundation print(Thread.current.isMainThread) func main() async { let task = Task { @MainActor () in print(Thread.current.isMainThread) } await task.value } await main()
(edited)import Foundation print(Thread.current.isMainThread) func main() async { let task = Task { @MainActor () in print(Thread.current.isMainThread) } await task.value } await main()
(edited)true false
(edited)import Foundation MainActor.preconditionIsolated() print(Thread.current.isMainThread) func main() async { let task = Task { @MainActor () in MainActor.preconditionIsolated() print(Thread.current.isMainThread) } await task.value } await main()
(edited)import Foundation MainActor.preconditionIsolated() print(Thread.current.isMainThread) func main() async { let task = Task { @MainActor () in MainActor.preconditionIsolated() print(Thread.current.isMainThread) } await task.value } await main()
(edited)true false
let task = Task { print(1) MainActor.preconditionIsolated("it should be fail") print(2) } await task.value
(edited)let task = Task { print(1) MainActor.preconditionIsolated("it should be fail") print(2) } await task.value
(edited)1 2
(edited)let task = Task.detached { print(1) MainActor.preconditionIsolated("it should be fail") print(2) } await task.value
let task = Task.detached { print(1) MainActor.preconditionIsolated("it should be fail") print(2) } await task.value
main/<stdin>:3: Precondition failed: Incorrect actor executor assumption; Expected 'UnownedSerialExecutor(executor: (Opaque Value))' executor. it should be fail #0 0x0000555ae7c8b977 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/usr/bin/swift-frontend+0x7852977) #1 0x0000555ae7c896ce llvm::sys::RunSignalHandlers() (/usr/bin/swift-frontend+0x78506ce)
typealias Foo = () -> Void typealias Bar = @escaping () -> Void typealias Baz = @MainActor @escaping () -> Void print(MemoryLayout<Foo>.size) print(MemoryLayout<Bar>.size) print(MemoryLayout<Baz>.size)
typealias Foo = () -> Void typealias Bar = @escaping () -> Void typealias Baz = @MainActor @escaping () -> Void print(MemoryLayout<Foo>.size) print(MemoryLayout<Bar>.size) print(MemoryLayout<Baz>.size)
<stdin>:2:17: error: @escaping attribute may only be used in function parameter position typealias Bar = @escaping () -> Void ^~~~~~~~~~ <stdin>:3:28: error: @escaping attribute may only be used in function parameter position typealias Baz = @MainActor @escaping () -> Void ^~~~~~~~~~
import Foundation let task = Task { @MainActor () in print(Thread.current.isMainThread) dispatchPrecondition(condition: .onQueue(.main)) dispatchPrecondition(condition: .notOnQueue(.main)) } await task.value
(edited)import Foundation let task = Task { @MainActor () in print(Thread.current.isMainThread) dispatchPrecondition(condition: .onQueue(.main)) dispatchPrecondition(condition: .notOnQueue(.main)) } await task.value
(edited) #0 0x000055e9b7c2d977 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/usr/bin/swift-frontend+0x7852977) #1 0x000055e9b7c2b6ce llvm::sys::RunSignalHandlers() (/usr/bin/swift-frontend+0x78506ce) #2 0x000055e9b7c2dfea SignalHandler(int) Signals.cpp:0:0
(edited)MainActor A singleton actor whose executor is equivalent to the main dispatch queue.
説明もそうなっとるし。func foo<I: Actor>(actor: isolated I, body: @Sendable () -> Void) { // await不要 bar(actor: actor, body: body) } func bar<I: Actor>(actor: isolated I, body: @Sendable () -> Void) {} @MainActor func main() async { // await必要。なんで? await foo(actor: MainActor.shared, body: { }) }
func foo<I: Actor>(actor: isolated I, body: @Sendable () -> Void) { // await不要 bar(actor: actor, body: body) } func bar<I: Actor>(actor: isolated I, body: @Sendable () -> Void) {} @MainActor func main() async { // await必要。なんで? await foo(actor: MainActor.shared, body: { }) }
func foo(actor: isolated MainActor) { gui() } @MainActor func gui() {}
func foo(actor: isolated MainActor) { gui() } @MainActor func gui() {}
<stdin>:2:3: error: call to main actor-isolated global function 'gui()' in a synchronous actor-isolated context gui() ^ <stdin>:5:6: note: calls to global function 'gui()' from outside of its actor context are implicitly asynchronous func gui() {} ^
MainActor.shared
以外のインスタンスが存在する可能性がある@T
書ける案あったlet a = (5)
let a = (5)
let a = (5)
let a = (5)
let a = (5)
let a: Int = (5)
let a = (5)
let a = (5)
let a = ("a")
let a: (String) = ("a")
let _: (x: Int)
let _: (x: Int)
<stdin>:1:9: error: cannot create a single-element tuple with an element label let _: (x: Int) ^~~
func something(p: Int, q: Int){} let a = (1, 2) something(a)
の話です…?func foo(_ f: ((Int, Int)) -> Void) {} foo { (x, y) in print(x, y) }
ごめん逆だった。タプル1つの関数を受け取るところに、複数引数の関数を渡せる。これは関係ないですね。print((Int).self)
/// TupleExpr - Parenthesized expressions like '(a=x+x)' and '(x, y, 4)'. Tuple /// types automatically decay if they have a single element, this means that /// single element tuple literals, such as "(4)", will exist in the AST, but /// have a result type that is the same as the input operand type. /// /// When a tuple element is formed with a default value for the type, the /// corresponding SubExpr element will be null. class TupleExpr : public Expr {
/// TupleExpr - Parenthesized expressions like '(a=x+x)' and '(x, y, 4)'. Tuple /// types automatically decay if they have a single element, this means that /// single element tuple literals, such as "(4)", will exist in the AST, but /// have a result type that is the same as the input operand type. /// /// When a tuple element is formed with a default value for the type, the /// corresponding SubExpr element will be null. class TupleExpr : public Expr {
import Foundation print(NSTemporaryDirectory())
import Foundation print(NSTemporaryDirectory())
/tmp/
import Foundation print(FileManager.default.temporaryDirectory.absoluteString)
import Foundation print(FileManager.default.temporaryDirectory.absoluteString)
file:///tmp/
func f<each T>( _ value: repeat each T ) -> (repeat each T) { return (repeat each value) } func g<T>( _ value: T ) -> T { return value } let value: Int? = 2 f(value).unsafelyUnwrapped g(value).unsafelyUnwrapped
(edited)func f<each T>( _ value: repeat each T ) -> (repeat each T) { return (repeat each value) } func g<T>( _ value: T ) -> T { return value } let value: Int? = 2 f(value).unsafelyUnwrapped g(value).unsafelyUnwrapped
(edited)<stdin>:15:10: error: value of tuple type '(_: Int?)' has no member 'unsafelyUnwrapped' f(value).unsafelyUnwrapped ~~~~~~~~ ^~~~~~~~~~~~~~~~~ <stdin>:16:10: warning: expression of type 'Int' is unused g(value).unsafelyUnwrapped ~~~~~~~~~^~~~~~~~~~~~~~~~~
(edited)func f<each T>( _ value: repeat each T ) -> (repeat each T) { return (repeat each value) } func g<T>( _ value: T ) -> T { return value } let value: Int? = 2 f(value).unsafelyUnwrapped g(value).unsafelyUnwrapped
(edited)<stdin>:15:10: warning: expression of type 'Int' is unused f(value).unsafelyUnwrapped ~~~~~~~~~^~~~~~~~~~~~~~~~~ <stdin>:16:10: warning: expression of type 'Int' is unused g(value).unsafelyUnwrapped ~~~~~~~~~^~~~~~~~~~~~~~~~~
func f<each T>( _ value: repeat each T ) -> (repeat each T) { return (repeat each value) } f(1, 2).0.description
error: value pack expansion can only appear inside a function argument list or tuple element
ってなりますfunc f<each T>( _ value: repeat each T ) -> (repeat each T) { return (repeat each value) } f(1, 2).0.description
<stdin>:7:9: error: value pack expansion can only appear inside a function argument list or tuple element f(1, 2).0.description ^
executeTarget
: /usr/bin/env -i PATH\=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin timeout --signal\=KILL 30 swift -
func f() async -> some CustomStringConvertible { return 42 } let r = await f() print(r.description)
func f() async -> some CustomStringConvertible { return 42 } let r = await f() print(r.description)
42
enum FooError: Error { case foo } func throwFoo() throws(FooError) { throw .foo }
enum FooError: Error { case foo } func throwFoo() throws(FooError) { throw .foo }
<stdin>:5:23: error: unexpected code '(FooError)' in function func throwFoo() throws(FooError) { ^~~~~~~~~~ <stdin>:1:1: error: new Swift parser generated errors for code that C++ parser accepted enum FooError: Error { ^ <stdin>:5:24: error: typed throws is an experimental feature func throwFoo() throws(FooError) { ^
enum FooError: Error { case foo } func throwFoo() throws(FooError) { throw .foo }
enum FooError: Error { case foo } func throwFoo() throws(FooError) { throw .foo }
enum FooError: Error { case foo } func throwFoo() throws(FooError) { throw .foo } func nonThrowing1() { do { try throwFoo() } catch { switch error { case .foo: break } } } func nonThrowing2() { do { try throwFoo() } catch .foo { } }
enum FooError: Error { case foo } func throwFoo() throws(FooError) { throw .foo } func nonThrowing1() { do { try throwFoo() } catch { switch error { case .foo: break } } } func nonThrowing2() { do { try throwFoo() } catch .foo { } }
<stdin>:22:9: error: errors thrown from here are not handled because the enclosing catch is not exhaustive try throwFoo() ^
enum FooError: Error { case foo } func throwFoo() throws(FooError) { throw .foo } func nonThrowing1() { do { try throwFoo() } catch { switch error { case .foo: break } } }
enum FooError: Error { case foo } func throwFoo() throws(FooError) { throw .foo } func nonThrowing1() { do { try throwFoo() } catch { switch error { case .foo: break } } }
catch
がconditionalだと網羅チェックしてくれないとは書いてたんですが、catch .foo
とかも一律でだめということですかね https://github.com/apple/swift-evolution/blob/main/proposals/0413-typed-throws.md
struct MyError: Error {} func canThrow() throws { throw MyError() }; protocol SomeRandomProtocol {} do { try canThrow() } catch let error where error is SomeRandomProtocol, { print("SomeRandomProtocol: \(error)") } catch { print("Default: \(error)") }
(edited)struct MySet<Element: Hashable> {} struct MyArray<Element> { func set() -> MySet<Element> { .init() } }
struct MySet<Element: Hashable> {} struct MyArray<Element> { func set() -> MySet<Element> { .init() } }
<stdin>:5:19: error: type 'Element' does not conform to protocol 'Hashable' func set() -> MySet<Element> { ^
protocol P {} struct MySet<Element: Hashable> {} struct MyArray<Element> { func set() -> MySet<Element> where Element: P { .init() } }
protocol P {} struct MySet<Element: Hashable> {} struct MyArray<Element> { func set() -> MySet<Element> where Element: P { .init() } }
protocol P {} struct MySet<Element: Hashable> {} struct MyArray<Element> { func set() -> MySet<Element> where Element: P { .init() } } class NonHashable {} func foo() { let array = MyArray<NonHashable>() array.set() }
protocol P {} struct MySet<Element: Hashable> {} struct MyArray<Element> { func set() -> MySet<Element> where Element: P { .init() } } class NonHashable {} func foo() { let array = MyArray<NonHashable>() array.set() }
<stdin>:16:11: error: instance method 'set()' requires that 'NonHashable' conform to 'Hashable' array.set() ^ <stdin>:7:10: note: where 'Element' = 'NonHashable' func set() -> MySet<Element> where Element: P { ^ <stdin>:16:11: error: instance method 'set()' requires that 'NonHashable' conform to 'P' array.set() ^ <stdin>:7:10: note: where 'Element' = 'NonHashable' func set() -> MySet<Element> where Element: P { ^
where Element: P
を付けたら暗黙的にElement: Hashable
も付く…?extension MyArray where Element: ... { }
のsugarみたいなものだからですねwhere
があるとextension MyArray where Element: ...
のようなコンテキストが生成されて、そこにMySet
由来のElement: Hashable
も含まれるwhere
がないとコンテキストが生成されないのでMyArray
のElement
に影響しないfunc globalFunc<E>(myArray: MyArray<E>) -> MySet<E>
階層が異なるというのは、推論が必要となる関数の外側のスコープでGenericsが宣言されてる場合ですね。 例示していただいてるコードの通らない方は、まさにその例です。func withMemoryCSVWriter<each T: LosslessStringConvertible>( headers: repeat (String, (each T).Type), task: (_ emit: (_ row: (repeat each T)) throws -> () ) throws -> () ) throws { var arrayHeaders: [String] = [] repeat arrayHeaders.append((each headers).0) print(arrayHeaders) try task { (_ row: (repeat each T)) in var arrayRow: [String] = [] repeat arrayRow.append((each row).description) print(arrayRow) } } try withMemoryCSVWriter(headers: ("aaa", Int.self), ("iii", String.self) ) { (emit) in try emit((1, "hello")) }
func withMemoryCSVWriter<each T: LosslessStringConvertible>( headers: repeat (String, (each T).Type), task: (_ emit: (_ row: (repeat each T)) throws -> () ) throws -> () ) throws { var arrayHeaders: [String] = [] repeat arrayHeaders.append((each headers).0) print(arrayHeaders) try task { (_ row: (repeat each T)) in var arrayRow: [String] = [] repeat arrayRow.append((each row).description) print(arrayRow) } } try withMemoryCSVWriter(headers: ("aaa", Int.self), ("iii", String.self) ) { (emit) in try emit((1, "hello")) }
<unknown>:0: error: INTERNAL ERROR: feature not implemented: reabstraction of pack values Stack dump: 0. Program arguments: /usr/bin/swift-frontend -frontend -interpret - -disable-objc-interop -new-driver-path /usr/bin/swift-driver -empty-abi-descriptor -resource-dir /usr/lib/swift -module-name main -plugin-path /usr/lib/swift/host/plugins -plugin-path /usr/local/lib/swift/host/plugins
func withMemoryCSVWriter<each T: LosslessStringConvertible>( headers: repeat (String, (each T).Type), task: (_ emit: (_ row: repeat each T) throws -> () ) throws -> () ) throws { var arrayHeaders: [String] = [] repeat arrayHeaders.append((each headers).0) print(arrayHeaders) try task { (_ row: repeat each T) in var arrayRow: [String] = [] repeat arrayRow.append((each row).description) print(arrayRow) } } try withMemoryCSVWriter(headers: ("aaa", Int.self), ("iii", String.self) ) { (emit: (Int, String) throws -> ()) in try emit(1, "hello") }
func withMemoryCSVWriter<each T: LosslessStringConvertible>( headers: repeat (String, (each T).Type), task: (_ emit: (_ row: repeat each T) throws -> () ) throws -> () ) throws { var arrayHeaders: [String] = [] repeat arrayHeaders.append((each headers).0) print(arrayHeaders) try task { (_ row: repeat each T) in var arrayRow: [String] = [] repeat arrayRow.append((each row).description) print(arrayRow) } } try withMemoryCSVWriter(headers: ("aaa", Int.self), ("iii", String.self) ) { (emit: (Int, String) throws -> ()) in try emit(1, "hello") }
["aaa", "iii"] ["1", "hello"]
Swift version 5.9.2 (swift-5.9.2-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.5.3 (swift-5.5.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.6.3 (swift-5.6.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.2.5 (swift-5.2.5-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.7.3 (swift-5.7.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.4.3 (swift-5.4.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.3.3 (swift-5.3.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.8.1 (swift-5.8.1-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.10-dev (LLVM e8e5be8d5b39f46, Swift 935dc3eae905669) Target: x86_64-unknown-linux-gnu
Swift version 5.11-dev (LLVM 13124099c3f0229, Swift d6871edc839adec) Target: x86_64-unknown-linux-gnu
import Dispatch protocol P {} extension Int: P {} func useP(_ p: some P) {} struct S: P { init(@SBuilder builder: () -> [any P]) { self.ps = builder() } var ps: [any P] } @resultBuilder struct SBuilder { static func buildBlock(_ components: (any P)...) -> [any P] { components } } extension P where Self == S { static func s(@SBuilder builder: () -> [any P]) -> S { S(builder: builder) } } func main() { // これはできる useP(S { 1 2 3 }) // これはできない useP(.s { 1 2 3 }) }
import Dispatch protocol P {} extension Int: P {} func useP(_ p: some P) {} struct S: P { init(@SBuilder builder: () -> [any P]) { self.ps = builder() } var ps: [any P] } @resultBuilder struct SBuilder { static func buildBlock(_ components: (any P)...) -> [any P] { components } } extension P where Self == S { static func s(@SBuilder builder: () -> [any P]) -> S { S(builder: builder) } } func main() { // これはできる useP(S { 1 2 3 }) // これはできない useP(.s { 1 2 3 }) }
<stdin>:38:9: warning: integer literal is unused 1 ^ <stdin>:39:9: warning: integer literal is unused 2 ^ <stdin>:40:9: warning: integer literal is unused 3 ^ <stdin>:41:5: error: missing return in closure expected to return '[any P]' }) ^
protocol P {} extension Int: P {} func useP(_ p: some P) {} struct S: P { init(builder: () -> ()) { } } extension P where Self == S { static func s(builder: () -> ()) -> Self { S(builder: builder) } } func main() { useP(S { 1 2 3 }) useP(.s { 1 2 3 }) }
T
can be inferred, writing .member1.member2.(...).memberN
Will behave as if the user had written: T.member1.member2.(...).memberN
https://github.com/apple/swift-evolution/blob/97c3e1d35ab217d7627e1e601fff5c4b33c17ef8/proposals/0299-extend-generic-static-member-lookup.md?plain=1#L199-L203
Toggle("Wi-Fi", isOn: $isWiFiEnabled) .toggleStyle(.switch)
.toggleStyle(.switch)
, the reference to the member .switch
is re-written to be SwitchToggleStyle.switch
in the type-checked AST. S.s { ... }
と書いたときと同等に動くべきと読めるので、バグで良いと思います。
(edited)ConstraintSystem::resolveClosure()
から呼ばれるはずのConstraintSystem::matchResultBuilder()
が何らかの理由で呼ばれてないみたい。 (edited)Task { print("Task.isCancelled:", Task.isCancelled) await withTaskCancellationHandler { print("work") } onCancel: { print("onCancel") } }.cancel()
Task { print("Task.isCancelled:", Task.isCancelled) await withTaskCancellationHandler { print("work") } onCancel: { print("onCancel") } }.cancel()
Task.isCancelled: true onCancel work
withTaskCancellationHandler
、キャンセル状態でこれに入ったら先にキャンセルしてから中が実行される/// ### Already cancelled tasks /// When `withTaskCancellationHandler` is used in a `Task` that has already been cancelled, /// the `onCancel` cancellation ``handler`` will be executed immediately before operation gets /// to execute. This allows the cancellation handler to set some external "cancelled" flag that the /// operation may be *atomically* checking for in order to avoid performing any actual work once /// the operation gets to run.
Task.checkCancellation()
呼んでれば結局大丈夫なことが多そうwithTaskCancellationHandler
の前にそれ呼んでおけば安心ですねclass TableView { protocol Delegate: AnyObject { func tableView(_: TableView, didSelectRowAtIndex: Int) } }
class TableView { protocol Delegate: AnyObject { func tableView(_: TableView, didSelectRowAtIndex: Int) } }
print("hello")
import Foundation print(NSDecimalNumber.self)
(edited)import Foundation print(NSDecimalNumber.self)
(edited)NSDecimalNumber
(edited)import Foundation extension Date: Identifiable {}
import Foundation extension Date: Identifiable {}
<stdin>:2:1: warning: extension declares a conformance of imported type 'Date' to imported protocol 'Identifiable'; this will not behave correctly if the owners of 'Foundation' introduce this conformance in the future extension Date: Identifiable {} ^ <stdin>:2:1: note: add '@retroactive' to silence this warning extension Date: Identifiable {} ^ ~~~~~~~~~~~~ @retroactive Identifiable <stdin>:2:1: error: type 'Date' does not conform to protocol 'Identifiable' extension Date: Identifiable {} ^ Swift.Identifiable:3:16: note: candidate would match if 'Date' conformed to 'AnyObject' public var id: ObjectIdentifier { get } ^ Swift.Identifiable:4:9: note: protocol requires property 'id' with type 'ObjectIdentifier' var id: Self.ID { get } ^
import Foundation extension Date: Identifiable {}
import Foundation extension Date: Identifiable {}
<stdin>:2:1: warning: extension declares a conformance of imported type 'Date' to imported protocol 'Identifiable'; this will not behave correctly if the owners of 'Foundation' introduce this conformance in the future extension Date: Identifiable {} ^ <stdin>:2:1: note: add '@retroactive' to silence this warning extension Date: Identifiable {} ^ ~~~~~~~~~~~~ @retroactive Identifiable <stdin>:2:1: error: type 'Date' does not conform to protocol 'Identifiable' extension Date: Identifiable {} ^ Swift.Identifiable:3:16: note: candidate would match if 'Date' conformed to 'AnyObject' public var id: ObjectIdentifier { get } ^ Swift.Identifiable:4:9: note: protocol requires property 'id' with type 'ObjectIdentifier' var id: Self.ID { get } ^
@retroactive
の警告はデフォルトで有効なんだswift -version
Swift version 5.10-dev (LLVM 7c3b53ecaad54fb, Swift d7111290a279135) Target: x86_64-unknown-linux-gnu
(edited)swift -help
OVERVIEW: Swift compiler USAGE: swift
(edited)@available(SwiftStdlib 5.10, *) func f() {}
(edited)@available(SwiftStdlib 5.10, *) func f() {}
(edited)swift -
<stdin>:1:12: warning: unrecognized platform name 'SwiftStdlib' @available(SwiftStdlib 5.10, *) ^
(edited)@available(SwiftStdlib 5.10, *) func f() {}
(edited)swift -enable-experimental-feature AvailabilityMacro\=SwiftStdlib\ 5.10:macOS\ 14.4,\ iOS\ 17.4,\ watchOS\ 10.4,\ tvOS\ 17.4 -
no output (edited)@available(SwiftStdlib 5.10, *) func f() {}
(edited)swift -Xfrontend -define-availability -Xfrontend SwiftStdlib\ 5.10:macOS\ 14.4,\ iOS\ 17.4,\ watchOS\ 10.4,\ tvOS\ 17.4 -
no outputfinal class NonSendable { var a = 1 func mutate() { a += 1 } } @MainActor func setMainActorState(_ x: NonSendable?) {} func main() async { let ns = await withCheckedContinuation { continuation in Task { @MainActor in let ns = NonSendable() continuation.resume(returning: ns) setMainActorState(ns) } } ns.mutate() }
(edited)final class NonSendable { var a = 1 func mutate() { a += 1 } } @MainActor func setMainActorState(_ x: NonSendable?) {} func main() async { let ns = await withCheckedContinuation { continuation in Task { @MainActor in let ns = NonSendable() continuation.resume(returning: ns) setMainActorState(ns) } } ns.mutate() }
(edited)final class NonSendable { var a = 1 func mutate() { a += 1 } } @MainActor func setMainActorState(_ x: NonSendable?) {} func main() async { let ns = await withCheckedContinuation { continuation in Task { @MainActor in let ns = NonSendable() continuation.resume(returning: ns) setMainActorState(ns) } } ns.mutate() }
(edited)final class NonSendable { var a = 1 func mutate() { a += 1 } } @MainActor func setMainActorState(_ x: NonSendable?) {} func main() async { let ns = await withCheckedContinuation { continuation in Task { @MainActor in let ns = NonSendable() continuation.resume(returning: ns) setMainActorState(ns) } } ns.mutate() }
(edited)func f() throws -> String { "" } let _ = try switch f() { default: "" }
func f() throws -> String { "" } let _ = try switch f() { default: "" }
<stdin>:2:20: warning: call can throw but is not marked with 'try'; this is an error in Swift 6 let _ = try switch f() { ^~~ <stdin>:2:20: note: did you mean to use 'try'? let _ = try switch f() { ^ try <stdin>:2:20: note: did you mean to handle error as optional value? let _ = try switch f() { ^ try? <stdin>:2:20: note: did you mean to disable error propagation? let _ = try switch f() { ^ try! <stdin>:2:9: warning: 'try' has no effect on 'switch' expression let _ = try switch f() { ^~~
func f() throws -> String { "" } let _ = try switch f() { default: "" }
<stdin>:2:20: warning: call can throw but is not marked with 'try'; this is an error in Swift 6 1 │ func f() throws -> String { "" } 2 │ let _ = try switch f() { │ ├─ warning: call can throw but is not marked with 'try'; this is an error in Swift 6 │ ├─ note: did you mean to use 'try'? │ ├─ note: did you mean to handle error as optional value? │ ╰─ note: did you mean to disable error propagation? 3 │ default: "" 4 │ } <stdin>:2:9: warning: 'try' has no effect on 'switch' expression 1 │ func f() throws -> String { "" } 2 │ let _ = try switch f() { │ ╰─ warning: 'try' has no effect on 'switch' expression 3 │ default: "" 4 │ }
func f() throws -> String { "" } let _ = try switch f() { default: "" }
error: unable to invoke subcommand: /usr/bin/swift-<@&887546264059797525> (No such file or directory)
error: unable to invoke subcommand: /usr/bin/swift-<@&887546264059797525> (No such file or directory)
error: unable to invoke subcommand: /usr/bin/swift-<@&887546264059797525> (No such file or directory)
Swift version 5.6.3 (swift-5.6.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.7.3 (swift-5.7.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 5.8.1 (swift-5.8.1-RELEASE) Target: x86_64-unknown-linux-gnu
Swift version 6.0-dev (LLVM 7fe091223bc821e, Swift 92f5eeeefc88005) Target: x86_64-unknown-linux-gnu
Swift version 5.9.2 (swift-5.9.2-RELEASE) Target: x86_64-unknown-linux-gnu
protocol Controller { associatedtype Deps typealias Routes = GenericRoutes<Self> } struct Request {} protocol Provider { associatedtype ServiceType func provide(for request: Request) throws -> ServiceType } struct GenericRoutes<C: Controller> { public init<P: Provider>( provider: P ) where P.ServiceType == C.Deps { } } struct VariadicProvider< each T: Provider >: Provider { public typealias ServiceType = (repeat (each T).ServiceType) public init(_ providers: repeat each T) { self.providers = (repeat each providers) } public var providers: (repeat each T) public func provide(for request: Request) throws -> ServiceType { return (repeat try (each providers).provide(for: request)) } } protocol DKey { associatedtype Value } struct Dependencies { func get<K: DKey>(_ key: K) -> K.Value { fatalError() } func forRequest<each K: DKey>( _ keys: repeat each K ) -> VariadicProvider<repeat (each K).Value> { return VariadicProvider<repeat (each K).Value>( repeat self.get(each keys) ) } } struct A {} struct B {} struct C {} struct WController: Controller { typealias Deps = (A, B, C) } struct AP: Provider { func provide(for request: Request) throws -> A { fatalError() } } struct BP: Provider { func provide(for request: Request) throws -> B { fatalError() } } struct CP: Provider { func provide(for request: Request) throws -> C { fatalError() } } struct AK: DKey { typealias Value = AP } extension DKey where Self == AK { static var a: AK { AK() } } struct BK: DKey { typealias Value = BP } extension DKey where Self == BK { static var b: BK { BK() } } struct CK: DKey { typealias Value = CP } extension DKey where Self == CK { static var c: CK { CK() } } func main(d: Dependencies) { let vp1: VariadicProvider<AP, BP, CP> = VariadicProvider( d.get(.a), d.get(.b), d.get(.c) ) let r1 = WController.Routes( provider: vp1 ) // write direct vp let r2 = WController.Routes( provider: VariadicProvider( d.get(.a), d.get(.b), d.get(.c) ) ) // build vp from forRequest let vp3: VariadicProvider<AP, BP, CP> = d.forRequest( .a, .b, .c ) let r3 = WController.Routes( provider: vp3 ) // write direct forRequest let r4 = WController.Routes( provider: d.forRequest( .a, .b, .c ) ) }
protocol Controller { associatedtype Deps typealias Routes = GenericRoutes<Self> } struct Request {} protocol Provider { associatedtype ServiceType func provide(for request: Request) throws -> ServiceType } struct GenericRoutes<C: Controller> { public init<P: Provider>( provider: P ) where P.ServiceType == C.Deps { } } struct VariadicProvider< each T: Provider >: Provider { public typealias ServiceType = (repeat (each T).ServiceType) public init(_ providers: repeat each T) { self.providers = (repeat each providers) } public var providers: (repeat each T) public func provide(for request: Request) throws -> ServiceType { return (repeat try (each providers).provide(for: request)) } } protocol DKey { associatedtype Value } struct Dependencies { func get<K: DKey>(_ key: K) -> K.Value { fatalError() } func forRequest<each K: DKey>( _ keys: repeat each K ) -> VariadicProvider<repeat (each K).Value> { return VariadicProvider<repeat (each K).Value>( repeat self.get(each keys) ) } } struct A {} struct B {} struct C {} struct WController: Controller { typealias Deps = (A, B, C) } struct AP: Provider { func provide(for request: Request) throws -> A { fatalError() } } struct BP: Provider { func provide(for request: Request) throws -> B { fatalError() } } struct CP: Provider { func provide(for request: Request) throws -> C { fatalError() } } struct AK: DKey { typealias Value = AP } extension DKey where Self == AK { static var a: AK { AK() } } struct BK: DKey { typealias Value = BP } extension DKey where Self == BK { static var b: BK { BK() } } struct CK: DKey { typealias Value = CP } extension DKey where Self == CK { static var c: CK { CK() } } func main(d: Dependencies) { let vp1: VariadicProvider<AP, BP, CP> = VariadicProvider( d.get(.a), d.get(.b), d.get(.c) ) let r1 = WController.Routes( provider: vp1 ) // write direct vp let r2 = WController.Routes( provider: VariadicProvider( d.get(.a), d.get(.b), d.get(.c) ) ) // build vp from forRequest let vp3: VariadicProvider<AP, BP, CP> = d.forRequest( .a, .b, .c ) let r3 = WController.Routes( provider: vp3 ) // write direct forRequest let r4 = WController.Routes( provider: d.forRequest( .a, .b, .c ) ) }
<stdin>:125:14: error: initializer 'init(provider:)' requires the types 'WController.Deps' (aka '(A, B, C)') and 'A, B, C' be equivalent let r4 = WController.Routes( ^ <stdin>:15:12: note: where 'C.Deps' = 'WController.Deps' (aka '(A, B, C)'), 'P.ServiceType' = 'A, B, C' public init<P: Provider>( ^
protocol Controller { associatedtype Deps typealias Routes = GenericRoutes<Self> } struct Request {} protocol Provider { associatedtype ServiceType func provide(for request: Request) throws -> ServiceType } struct GenericRoutes<C: Controller> { public init<P: Provider>( provider: P ) where P.ServiceType == C.Deps { } } struct VariadicProvider< each T: Provider >: Provider { public typealias ServiceType = (repeat (each T).ServiceType) public init(_ providers: repeat each T) { self.providers = (repeat each providers) } public var providers: (repeat each T) public func provide(for request: Request) throws -> ServiceType { return (repeat try (each providers).provide(for: request)) } } protocol DKey { associatedtype Value } struct Dependencies { func get<K: DKey>(_ key: K) -> K.Value { fatalError() } func forRequest<each K: DKey>( _ keys: repeat each K ) -> VariadicProvider<repeat (each K).Value> { return VariadicProvider<repeat (each K).Value>( repeat self.get(each keys) ) } } struct A {} struct B {} struct C {} struct WController: Controller { typealias Deps = (A, B, C) } struct AP: Provider { func provide(for request: Request) throws -> A { fatalError() } } struct BP: Provider { func provide(for request: Request) throws -> B { fatalError() } } struct CP: Provider { func provide(for request: Request) throws -> C { fatalError() } } struct AK: DKey { typealias Value = AP } extension DKey where Self == AK { static var a: AK { AK() } } struct BK: DKey { typealias Value = BP } extension DKey where Self == BK { static var b: BK { BK() } } struct CK: DKey { typealias Value = CP } extension DKey where Self == CK { static var c: CK { CK() } } func main(d: Dependencies) { let vp1: VariadicProvider<AP, BP, CP> = VariadicProvider( d.get(.a), d.get(.b), d.get(.c) ) let r1 = WController.Routes( provider: vp1 ) // write direct vp let r2 = WController.Routes( provider: VariadicProvider( d.get(.a), d.get(.b), d.get(.c) ) ) // build vp from forRequest let vp3: VariadicProvider<AP, BP, CP> = d.forRequest( .a, .b, .c ) let r3 = WController.Routes( provider: vp3 ) // write direct forRequest let r4 = WController.Routes( provider: d.forRequest( .a, .b, .c ) ) }
<stdin>:125:14: error: initializer 'init(provider:)' requires the types 'WController.Deps' (aka '(A, B, C)') and 'A, B, C' be equivalent 13 │ 14 │ struct GenericRoutes<C: Controller> { 15 │ public init<P: Provider>( │ ╰─ note: where 'C.Deps' = 'WController.Deps' (aka '(A, B, C)'), 'P.ServiceType' = 'A, B, C' 16 │ provider: P 17 │ ) where P.ServiceType == C.Deps { ┆ 123 │ 124 │ // write direct forRequest 125 │ let r4 = WController.Routes( │ ╰─ error: initializer 'init(provider:)' requires the types 'WController.Deps' (aka '(A, B, C)') and 'A, B, C' be equivalent 126 │ provider: d.forRequest( 127 │ .a, .b, .c
protocol Controller { associatedtype Deps typealias Routes = GenericRoutes<Self> } struct Request {} protocol Provider { associatedtype ServiceType func provide(for request: Request) throws -> ServiceType } struct GenericRoutes<C: Controller> { public init<P: Provider>( provider: P ) where P.ServiceType == C.Deps { } } struct VariadicProvider< each T: Provider >: Provider { public typealias ServiceType = (repeat (each T).ServiceType) public init(_ providers: repeat each T) { self.providers = (repeat each providers) } public var providers: (repeat each T) public func provide(for request: Request) throws -> ServiceType { return (repeat try (each providers).provide(for: request)) } } protocol DKey { associatedtype Value } struct Dependencies { func get<K: DKey>(_ key: K) -> K.Value { fatalError() } func forRequest<each K: DKey>( _ keys: repeat each K ) -> VariadicProvider<repeat (each K).Value> { return VariadicProvider<repeat (each K).Value>( repeat self.get(each keys) ) } } struct A {} struct B {} struct C {} struct WController: Controller { typealias Deps = (A, B, C) } struct AP: Provider { func provide(for request: Request) throws -> A { fatalError() } } struct BP: Provider { func provide(for request: Request) throws -> B { fatalError() } } struct CP: Provider { func provide(for request: Request) throws -> C { fatalError() } } struct AK: DKey { typealias Value = AP } extension DKey where Self == AK { static var a: AK { AK() } } struct BK: DKey { typealias Value = BP } extension DKey where Self == BK { static var b: BK { BK() } } struct CK: DKey { typealias Value = CP } extension DKey where Self == CK { static var c: CK { CK() } } func main(d: Dependencies) { let vp1: VariadicProvider<AP, BP, CP> = VariadicProvider( d.get(.a), d.get(.b), d.get(.c) ) let r1 = WController.Routes( provider: vp1 ) // write direct vp let r2 = WController.Routes( provider: VariadicProvider( d.get(.a), d.get(.b), d.get(.c) ) ) // build vp from forRequest let vp3: VariadicProvider<AP, BP, CP> = d.forRequest( .a, .b, .c ) let r3 = WController.Routes( provider: vp3 ) // write direct forRequest let r4 = WController.Routes( provider: d.forRequest( .a, .b, .c ) ) }
<stdin>:102:9: warning: initialization of immutable value 'r1' was never used; consider replacing with assignment to '_' or removing it let r1 = WController.Routes( ~~~~^~ _ <stdin>:107:9: warning: initialization of immutable value 'r2' was never used; consider replacing with assignment to '_' or removing it let r2 = WController.Routes( ~~~~^~ _ <stdin>:120:9: warning: initialization of immutable value 'r3' was never used; consider replacing with assignment to '_' or removing it let r3 = WController.Routes( ~~~~^~ _ <stdin>:125:9: warning: initialization of immutable value 'r4' was never used; consider replacing with assignment to '_' or removing it let r4 = WController.Routes( ~~~~^~ _
struct S { var a = 0 } func foo(_ x: (S) -> Int) {} foo(\.a)
struct S { var a = 0 } func foo(_ x: (S) -> Int) {} foo(\.a)
struct S { var a = 0 } func foo(_ x: (S) -> Int) {} foo(\.a)
struct S { var a = 0 } func foo(_ x: ((S) -> Int)? = nil) {} foo(\.a)
struct S { var a = 0 } func foo(_ x: ((S) -> Int)? = nil) {} foo(\.a)
<stdin>:7:5: error: cannot convert value of type '_' to expected argument type '((S) -> Int)?' foo(\.a) ^ <stdin>:7:5: error: cannot infer key path type from context; consider explicitly specifying a root type foo(\.a) ^ <#Root#>
struct S { var a = 0 } func foo(_ x: ((S) -> Int)? = nil) {} foo(\.a)
struct S { var a = 0 } func foo(_ x: ((S) -> Int)? = nil) {} foo(\.a)
<stdin>:7:5: error: cannot convert value of type '_' to expected argument type '((S) -> Int)?' foo(\.a) ^ <stdin>:7:5: error: cannot infer key path type from context; consider explicitly specifying a root type foo(\.a) ^ <#Root#>
struct S { var a = 0 } func foo(_ x: ((S) -> Int)? = nil) {} foo(\.a)
@MainActor func doSomething() async { await withUnsafeContinuation { continuation in if #available(macOS 14.0, *) { MainActor.shared.assertIsolated() } continuation.resume(returning: ()) } } await Task.detached { await doSomething() }.value
@MainActor func doSomething() async { await withUnsafeContinuation { continuation in if #available(macOS 14.0, *) { MainActor.shared.assertIsolated() } continuation.resume(returning: ()) } } await Task.detached { await doSomething() }.value
main/<stdin>:5: Fatal error: Incorrect actor executor assumption; Expected 'UnownedSerialExecutor(executor: (Opaque Value))' executor. #0 0x0000558634074067 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/usr/bin/swift-frontend+0x7a71067) #1 0x0000558634071dbe llvm::sys::RunSignalHandlers() (/usr/bin/swift-frontend+0x7a6edbe)
Swift version 6.0-dev (LLVM 3312447e53da9b3, Swift b62c39583c53f5b) Target: x86_64-unknown-linux-gnu
var _aa = 1 _aa += 1 let aa = consume _aa
var _aa = 1 _aa += 1 let aa = consume _aa
<stdin>:3:18: error: 'consume' cannot be applied to globals let aa = consume _aa ^
class Super { } @MainActor final class Sub: Super { }
class Super { } @MainActor final class Sub: Super { }
<stdin>:6:13: warning: main actor-isolated class 'Sub' has different actor isolation from nonisolated superclass 'Super'; this is an error in Swift 6 final class Sub: Super { ^
class Super { } @MainActor final class Sub: Super { }
class C {} final class C2: C, Sendable {}
class C {} final class C2: C, Sendable {}
<stdin>:2:13: error: 'Sendable' class 'C2' cannot inherit from another class final class C2: C, Sendable {} ^
class C: @unchecked Sendable {} final class C2<NotSendable>: C, Sendable { var foo: NotSendable }
class C: @unchecked Sendable {} final class C2<NotSendable>: C, Sendable { var foo: NotSendable }
<stdin>:2:13: error: class 'C2' has no initializers final class C2<NotSendable>: C, Sendable { ^ <stdin>:3:7: note: stored property 'foo' without initial value prevents synthesized initializers var foo: NotSendable ^
func f(_ a: Int?) {} func f(_ a: Any) {} f(3)
(edited)func f(_ a: Int?) {} func f(_ a: Any) {} f(3)
(edited)(source_file "<stdin>" (func_decl range=[<stdin>:1:1 - line:1:20] "f(_:)" interface type='(Int?) -> ()' access=internal (parameter_list range=[<stdin>:1:7 - line:1:17] (parameter "a" type='Int?' interface type='Int?')) (brace_stmt range=[<stdin>:1:19 - line:1:20])) (func_decl range=[<stdin>:3:1 - line:3:19] "f(_:)" interface type='(Any) -> ()' access=internal (parameter_list range=[<stdin>:3:7 - line:3:16] (parameter "a" type='Any' interface type='Any')) (brace_stmt range=[<stdin>:3:18 - line:3:19])) (top_level_code_decl range=[<stdin>:5:1 - line:5:4] (brace_stmt implicit range=[<stdin>:5:1 - line:5:4] (call_expr type='()' location=<stdin>:5:1 range=[<stdin>:5:1 - line:5:4] nothrow arg_labels=_: (declref_expr type='(Any) -> ()' location=<stdin>:5:1 range=[<stdin>:5:1 - line:5:1] decl=main.(file).f@<stdin>:3:6 function_ref=single) (paren_expr type='(Any)' location=<stdin>:5:3 range=[<stdin>:5:2 - line:5:4] (erasure_expr implicit type='Any' location=<stdin>:5:3 range=[<stdin>:5:3 - line:5:3] (integer_literal_expr type='Int' location=<stdin>:5:3 range=[<stdin>:5:3 - line:5:3] value=3 builtin_initializer=Swift.(file).Int.init(_builtinIntegerLiteral:) initializer=**NULL**)))))))
---Constraint solving at [<stdin>:5:1 - line:5:4]--- (common result type for $T0 is ()) ---Initial constraints for the given expression---
(edited)func f(_ a: Int?) {} func f(_ a: Any) {} f(3)
(edited)(source_file "<stdin>" (func_decl range=[<stdin>:1:1 - line:1:20] "f(_:)" interface type='(Int?) -> ()' access=internal (parameter_list range=[<stdin>:1:7 - line:1:17] (parameter "a" interface type='Int?')) (brace_stmt range=[<stdin>:1:19 - line:1:20])) (func_decl range=[<stdin>:3:1 - line:3:19] "f(_:)" interface type='(Any) -> ()' access=internal (parameter_list range=[<stdin>:3:7 - line:3:16] (parameter "a" interface type='Any')) (brace_stmt range=[<stdin>:3:18 - line:3:19])) (top_level_code_decl range=[<stdin>:5:1 - line:5:4] (brace_stmt implicit range=[<stdin>:5:1 - line:5:4] (call_expr type='()' location=<stdin>:5:1 range=[<stdin>:5:1 - line:5:4] nothrow isolationCrossing=none (declref_expr type='(Any) -> ()' location=<stdin>:5:1 range=[<stdin>:5:1 - line:5:1] decl=main.(file).f@<stdin>:3:6 function_ref=single) (argument_list (argument (erasure_expr implicit type='Any' location=<stdin>:5:3 range=[<stdin>:5:3 - line:5:3] (integer_literal_expr type='Int' location=<stdin>:5:3 range=[<stdin>:5:3 - line:5:3] value=3 builtin_initializer=Swift.(file).Int.init(_builtinIntegerLiteral:) initializer=**NULL**))))))))
---Constraint solving at [<stdin>:5:1 - line:5:4]--- (common result type for $T0 is ())
struct Box {} struct AsyncBox {} func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } func hoge() async { await f(.init()) } await hoge()
(edited)struct Box {} struct AsyncBox {} func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } func hoge() async { await f(.init()) } await hoge()
(edited)async
(edited)struct Box {} struct AsyncBox {} func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } func hoge() async { await f(.init()) } await hoge()
(edited)async
(edited)struct Box {} struct AsyncBox {} func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } await f(.init())
struct Box {} struct AsyncBox {} func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } await f(.init())
sync
<stdin>:11:1: warning: no 'async' operations occur within 'await' expression await f(.init()) ^
struct Box {} struct AsyncBox {} func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } await f(.init())
sync
<stdin>:11:1: warning: no 'async' operations occur within 'await' expression await f(.init()) ^
enum Box { case doing(() -> Void) } enum AsyncBox { case doing(() async -> Void) } func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } func hoge() async { await f(.doing {}) } await hoge()
(edited)enum Box { case doing(() -> Void) } enum AsyncBox { case doing(() async -> Void) } func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } func hoge() async { await f(.doing {}) } await hoge()
(edited)sync
<stdin>:12:5: warning: no 'async' operations occur within 'await' expression await f(.doing {}) ^
(edited)enum Box { case doing(() -> Void) } enum AsyncBox { case doing(() async -> Void) } func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } func hoge() async { await f(.doing {}) } await hoge()
(edited)sync
<stdin>:12:5: warning: no 'async' operations occur within 'await' expression await f(.doing {}) ^
(edited)enum Box { case doing(() -> Void) } enum AsyncBox { case doing(() async -> Void) } func f(_ a: Box) { print("sync") } func f(_ a: AsyncBox) async { print("async") } func hoge() async { await f(.doing {}) } await hoge()
(edited)sync
(edited)--- Solution #0 --- Fixed score: [component: sync-in-asynchronous(s), value: 1] ... --- Solution #1 --- Fixed score: [component: sync-in-asynchronous(s), value: 1] ...
(edited)enum Box { case doing(() -> Void) } enum AsyncBox { case doing(asyncAction: () async -> Void) case doing(action: () -> Void) } func f(_ a: Box...) { print("sync") } func f(_ a: AsyncBox...) async { print("async") } func hoge() async { await f(.doing {}) } await hoge()
enum Box { case doing(() -> Void) } enum AsyncBox { case doing(asyncAction: () async -> Void) case doing(action: () -> Void) } func f(_ a: Box...) { print("sync") } func f(_ a: AsyncBox...) async { print("async") } func hoge() async { await f(.doing {}) } await hoge()
async
import Foundation func cat(length: Int) throws { let data = Data(repeating: 0, count: length) let (stdin, stdout, stderr) = (Pipe(), Pipe(), Pipe()) let process = Process() process.standardInput = stdin process.standardOutput = stdout process.standardError = stderr process.executableURL = URL(fileURLWithPath: "/bin/cat") try process.run() print("write:\(length)") try stdin.fileHandleForWriting.write(contentsOf: data) print("close:\(length)") try stdin.fileHandleForWriting.close() print("waitUntilExit:\(length)") process.waitUntilExit() print("finished:\(length)") } try cat(length: 100) try cat(length: 102400)
import Foundation func cat(length: Int) throws { let data = Data(repeating: 0, count: length) let (stdin, stdout, stderr) = (Pipe(), Pipe(), Pipe()) let process = Process() process.standardInput = stdin process.standardOutput = stdout process.standardError = stderr process.executableURL = URL(fileURLWithPath: "/bin/cat") try process.run() print("write:\(length)") try stdin.fileHandleForWriting.write(contentsOf: data) print("close:\(length)") try stdin.fileHandleForWriting.close() print("waitUntilExit:\(length)") process.waitUntilExit() print("finished:\(length)") } try cat(length: 100) try cat(length: 102400)
extension Sequence where Element == Int { // var count ... func count( _ predicate: (Int) -> Bool ) -> Int { 0 } } func f(_ a: ((Int) -> Bool) -> Int) { print("func") } func f(_ a: Int) { print("var") } f([1, 2, 3].count)
extension Sequence where Element == Int { // var count ... func count( _ predicate: (Int) -> Bool ) -> Int { 0 } } func f(_ a: ((Int) -> Bool) -> Int) { print("func") } func f(_ a: Int) { print("var") } f([1, 2, 3].count)
var
// @_typeEraser(AnyP) protocol P {} struct ConcreteP1: P {} struct ConcreteP2: P {} struct AnyP: P { init(erasing base: some P) {} } struct Foo { dynamic var p: some P { ConcreteP1() } } extension Foo { @_dynamicReplacement(for: p) var replacedP: some P { ConcreteP2() } } print(Foo().p)
// @_typeEraser(AnyP) protocol P {} struct ConcreteP1: P {} struct ConcreteP2: P {} struct AnyP: P { init(erasing base: some P) {} } struct Foo { dynamic var p: some P { ConcreteP1() } } extension Foo { @_dynamicReplacement(for: p) var replacedP: some P { ConcreteP2() } } print(Foo().p)
JIT session error: Symbols not found: [ $s4main3FooV9replacedPQrvgTX ] Failed to materialize symbols: { (main, { get_witness_table 4main10ConcreteP1VAA1PHPyHC.1, $s4main3FooV1pQrvpQOy_Qo_MD, $ss27_finalizeUninitializedArrayySayxGABnlF, $s4main3FooV1pQrvpQOMk, $s4main4AnyPVMn, symbolic _____y_Qo_ 4main3FooV1pQrvpQO, $s4main3FooV1pQrvpQOMg, $s4main10ConcreteP1VMa, $s4mainMXM, symbolic $s4main1PP, $s4main3FooV9replacedPQrvpQOMQ, $s4main10ConcreteP2VN, main, $sSa12_endMutationyyF, $s4main3FooV1pQrvg, get_witness_table 4main10ConcreteP2VAA1PHPyHC.2, $s4main10ConcreteP1VN, $s4main3FooVMa, $s4main3FooVACycfC, $s4main4AnyPVAA1PAAWP, symbolic _____ 4main4AnyPV, $ss5print_9separator10terminatoryypd_S2StFfA1_, $s4main10ConcreteP1VAA1PAAWP, $s4main10ConcreteP1VMn, $s4main3FooV1pQrvpQOMQ, $s4main4AnyPVAA1PAAMc, $s4main3FooVN, $s4main10ConcreteP2VMa, $s4main10ConcreteP2VMn, $ss5print_9separator10terminatoryypd_S2StFfA0_, symbolic x, $s4main3FooV9replacedPQrvgTI, $s4main3FooV9replacedPQrvg, $s4main1PMp, $s4main10ConcreteP1VACycfC, $s4main3FooVMn, $s4main3FooV1pQrvpQOMh, __swift_instantiateConcreteTypeFromMangledName, $s4main4AnyPVMa, $s4main3FooV1pQrvgTx, $s4main3FooV9replacedPQrvpQOMg, __swift_allocate_boxed_opaque_existential_0, $s4main4AnyPVN, $s4main10ConcreteP2VACycfC, $s4main3FooV1pQrvgTX, symbolic _____ 4main10ConcreteP2V, symbolic _____ 4main3FooV, $s4main3FooV1pQrvpQOMj, $s4main10ConcreteP2VAA1PAAMc, $s4main10ConcreteP2VAA1PAAWP, symbolic _____ 4main10ConcreteP1V, $s4main10ConcreteP1VAA1PAAMc }) }
@_typeEraser(AnyP) protocol P {} struct ConcreteP1: P {} struct AnyP: P { init(erasing base: some P) {} } struct Foo { dynamic var p: some P { ConcreteP1() } } print(Foo().p)
@_typeEraser(AnyP) protocol P {} struct ConcreteP1: P {} struct AnyP: P { init(erasing base: some P) {} } struct Foo { dynamic var p: some P { ConcreteP1() } } print(Foo().p)
AnyP()
@_typeEraser(AnyP) protocol P {} struct ConcreteP1: P {} struct AnyP: P { init(erasing base: some P) { print("Erasing:", base) } } struct Foo { dynamic var p: some P { ConcreteP1() } } print(Foo().p)
(edited)@_typeEraser(AnyP) protocol P {} struct ConcreteP1: P {} struct AnyP: P { init(erasing base: some P) { print("Erasing:", base) } } struct Foo { dynamic var p: some P { ConcreteP1() } } print(Foo().p)
(edited)Erasing: ConcreteP1() AnyP()
(edited)protocol P { } extension P { static func value(_ a: Bool) { } } struct A: P { var string: String } extension Optional: P where Wrapped: P { } extension A { static var value: A? { A(string: "A") } } let a: A? = .value print(a)
(edited)protocol P { } extension P { static func value(_ a: Bool) { } } struct A: P { var string: String } extension Optional: P where Wrapped: P { } extension A { static var value: A? { A(string: "A") } } let a: A? = .value print(a)
(edited)<stdin>:16:14: error: value of optional type 'A?' must be unwrapped to a value of type 'A' let a: A? = .value ^
(edited)protocol P { } extension P { static func value(_ a: Bool) { } } struct A: P { var string: String } extension Optional: P where Wrapped: P { } extension A { static var value: A? { A(string: "A") } } let a: A? = .value print(a)
(edited)Optional(main.A(string: "A"))
<stdin>:17:7: warning: expression implicitly coerced from 'A?' to 'Any' print(a) ^ <stdin>:17:7: note: provide a default value to avoid this warning print(a) ^ ?? <#default value#> <stdin>:17:7: note: force-unwrap the value to avoid this warning print(a) ^ ! <stdin>:17:7: note: explicitly cast to 'Any' with 'as Any' to silence this warning print(a) ^ as Any
struct A { static var value: A? { A() } } extension Optional { static func value(_ a: Bool) { } } let a: A? = .value
(edited)struct A { static var value: A? { A() } } extension Optional { static func value(_ a: Bool) { } } let a: A? = .value
(edited)<stdin>:8:14: error: value of optional type 'A?' must be unwrapped to a value of type 'A' let a: A? = .value ^ <stdin>:8:14: note: coalesce using '??' to provide a default when the optional value contains 'nil' let a: A? = .value ^ ?? <#default value#> <stdin>:8:14: note: force-unwrap using '!' to abort execution if the optional value contains 'nil' let a: A? = .value ^ !
(edited)struct A { static var value: A? { A() } } extension Optional { static func value(_ a: Bool) { } } let a: A? = .value
(edited)func f( _ operations: [() async throws -> ()] ) async throws { } try await f([ { print("Hello") }, ])
(edited)func f( _ operations: [() async throws -> ()] ) async throws { } try await f([ { print("Hello") }, ])
(edited)<unknown>:0: error: fatal error encountered during compilation; please submit a bug report (https://swift.org/contributing/#reporting-bugs) <unknown>:0: note: SmallVector unable to grow. Requested capacity (4294967297) is larger than maximum value for size type (4294967295) Stack dump:
(edited)func f( _ operations: [() async throws -> ()] ) async throws { } try await f([ { print("Hello") }, ])
(edited)@MainActor func doSomething() async { await withUnsafeContinuation { continuation in if #available(macOS 14.0, *) { MainActor.shared.assertIsolated() } continuation.resume(returning: ()) } } await Task.detached { await doSomething() }.value
(edited)@MainActor func doSomething() async { await withUnsafeContinuation { continuation in if #available(macOS 14.0, *) { MainActor.shared.assertIsolated() } continuation.resume(returning: ()) } } await Task.detached { await doSomething() }.value
(edited)main/<stdin>:5: Fatal error: Incorrect actor executor assumption; Expected 'UnownedSerialExecutor(executor: (Opaque Value))' executor. #0 0x000055b122f77623 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/usr/bin/swift-frontend+0x61b7623) #1 0x000055b122f755de llvm::sys::RunSignalHandlers() (/usr/bin/swift-frontend+0x61b55de)
(edited)@MainActor func doSomething() async { await withUnsafeContinuation { continuation in if #available(macOS 14.0, *) { MainActor.shared.assertIsolated() } continuation.resume(returning: ()) } } await Task.detached { await doSomething() }.value
(edited)@MainActor func doSomething() async { await withUnsafeContinuation { continuation in if #available(macOS 14.0, *) { MainActor.shared.assertIsolated() } continuation.resume(returning: ()) } } await Task.detached { await doSomething() }.value
(edited)struct E: Error {} func foo() throws(E) -> {}
struct E: Error {} func foo() throws(E) -> {}
<stdin>:3:18: error: consecutive statements on a line must be separated by ';' func foo() throws(E) -> {} ^ ; <stdin>:3:6: error: expected '{' in body of function declaration func foo() throws(E) -> {} ^ <stdin>:3:25: error: expected type after '->' func foo() throws(E) -> {} ^
struct E: Error {} func foo() throws(E) -> {}
<stdin>:3:25: error: expected type for function result 1 | struct E: Error {} 2 | 3 | func foo() throws(E) -> {} | `- error: expected type for function result 4 |
protocol P { mutating func mutatingFunc1() mutating func mutatingFunc2() func nonMutatingFunc() } extension P { mutating func mutatingFunc1() { print("mutatingFunc1 of P") } func mutatingFunc2() { print("mutatingFunc2 of P") } func nonMutatingFunc() { print("nonMutatingFunc of P") } } struct S: P { mutating func mutatingFunc1() { print("mutatingFunc1 of S") } mutating func mutatingFunc2() { print("mutatingFunc2 of S") } func nonMutatingFunc() { print("nonMutatingFunc of S") } } func useP(_ p: some P) { p.mutatingFunc2() p.nonMutatingFunc() } func useMutableP(_ p: inout some P) { p.mutatingFunc1() p.mutatingFunc2() p.nonMutatingFunc() } var s = S() print("--- useP ---") useP(s) print("--- useMutableP ---") useMutableP(&s)
protocol P { mutating func mutatingFunc1() mutating func mutatingFunc2() func nonMutatingFunc() } extension P { mutating func mutatingFunc1() { print("mutatingFunc1 of P") } func mutatingFunc2() { print("mutatingFunc2 of P") } func nonMutatingFunc() { print("nonMutatingFunc of P") } } struct S: P { mutating func mutatingFunc1() { print("mutatingFunc1 of S") } mutating func mutatingFunc2() { print("mutatingFunc2 of S") } func nonMutatingFunc() { print("nonMutatingFunc of S") } } func useP(_ p: some P) { p.mutatingFunc2() p.nonMutatingFunc() } func useMutableP(_ p: inout some P) { p.mutatingFunc1() p.mutatingFunc2() p.nonMutatingFunc() } var s = S() print("--- useP ---") useP(s) print("--- useMutableP ---") useMutableP(&s)
--- useP --- mutatingFunc2 of P nonMutatingFunc of S --- useMutableP --- mutatingFunc1 of S mutatingFunc2 of S nonMutatingFunc of S
public final class Function<R, each A> { public init( _ body: @escaping (repeat each A) -> R ) { self.body = body } public var body: (repeat each A) -> R public func callAsFunction(_ args: repeat each A) -> R { body(repeat each args) } }
public final class Function<R, each A> { public init( _ body: @escaping (repeat each A) -> R ) { self.body = body } public var body: (repeat each A) -> R public func callAsFunction(_ args: repeat each A) -> R { body(repeat each args) } }
<stdin>:5:19: error: type of expression is ambiguous without a type annotation self.body = body ~~~~~~~~~~^~~~~~ <stdin>:11:13: error: missing argument for parameter #1 in call body(repeat each args) ^ <#repeat each A#>, <stdin>:8:16: note: 'body' declared here public var body: (repeat each A) -> R ^
public final class Function<R, each A> { public init( _ body: @escaping (repeat each A) -> R ) { self.body = body } public var body: (repeat each A) -> R public func callAsFunction(_ args: repeat each A) -> R { body(repeat each args) } }
import Foundation try? await ContinuousClock().sleep(for: .seconds(1))
import Foundation try? await ContinuousClock().sleep(for: .seconds(1))
@MainActor func doSomething() async { await withUnsafeContinuation { continuation in continuation.resume(returning: ()) } }
@MainActor func doSomething() async { await withUnsafeContinuation { continuation in continuation.resume(returning: ()) } }
sil_stage canonical import Builtin
@MainActor func doSomething() async { await withUnsafeContinuation { continuation in continuation.resume(returning: ()) } }
@MainActor func doSomething() async { await withUnsafeContinuation { continuation in continuation.resume(returning: ()) } }
sil_stage raw import Builtin
actor Counter { var count = 0 func increment() { count += 1 } func incrementCounters(c: isolated Counter) async { for _ in 0..<1_000 { await self.increment() c.increment() } } } let c1 = Counter() let c2 = Counter() let t1 = Task.detached { await c1.incrementCounters(c: c2) } let t2 = Task.detached { await c2.incrementCounters(c: c1) } await (t1.value, t2.value) await print(c1.count, c2.count)
actor Counter { var count = 0 func increment() { count += 1 } func incrementCounters(c: isolated Counter) async { for _ in 0..<1_000 { await self.increment() c.increment() } } } let c1 = Counter() let c2 = Counter() let t1 = Task.detached { await c1.incrementCounters(c: c2) } let t2 = Task.detached { await c2.incrementCounters(c: c1) } await (t1.value, t2.value) await print(c1.count, c2.count)
2000 2000
<stdin>:19:7: warning: expression of type '((), ())' is unused await (t1.value, t2.value) ^~~~~~~~~~~~~~~~~~~~
actor Counter { var count = 0 func increment() { count += 1 } func incrementCounters(c: isolated Counter) async { for _ in 0..<1_000 { await self.increment() c.increment() } } } let c1 = Counter() let c2 = Counter() let t1 = Task.detached { await c1.incrementCounters(c: c2) } let t2 = Task.detached { await c2.incrementCounters(c: c1) } await (t1.value, t2.value) await print(c1.count, c2.count)
2000 2000
Swift version 4.0.3 (swift-4.0.3-RELEASE) Target: x86_64-unknown-linux-gnu
Swift Package Manager - Swift 6.0.0-dev
func f() { inner() return; func inner() { print("after return") } } f()
(edited)func f() { inner() return; func inner() { print("after return") } } f()
(edited)after return
func f() { inner() return; func inner() { print("after return") } } f()
(edited)after return
struct S {} func run <R>(body: () -> R) -> R { body() } func foo(x: S) -> S {x} func main() { run { let x = S() let y = foo(x: x) return y } }
struct S {} func run <R>(body: () -> R) -> R { body() } func foo(x: S) -> S {x} func main() { run { let x = S() let y = foo(x: x) return y } }
<stdin>:10:9: error: cannot infer return type for closure with multiple statements; add explicit type to disambiguate run { ^ () -> <#Result#> in
func transform<each T>(_ v: (repeat each T)) -> (repeat each T) { return (repeat each v) } let myTuple = (1, "Hello", 3.14) let transformedTuple = transform(myTuple) print(transformedTuple)
func transform<each T>(_ v: (repeat each T)) -> (repeat each T) { return (repeat each v) } let myTuple = (1, "Hello", 3.14) let transformedTuple = transform(myTuple) print(transformedTuple)
<unknown>:0: error: fatal error encountered during compilation; please submit a bug report (https://swift.org/contributing/#reporting-bugs) <unknown>:0: note: unsupported collection upcast kind Stack dump:
func transform<each T>(_ v: (repeat each T)) -> (repeat each T) { return (repeat each v) } let myTuple = (1, "Hello", 3.14) let transformedTuple = transform(myTuple) print(transformedTuple)
(1, "Hello", 3.14)
extension String { static func foo(_ int: Int, other: Bool = true) -> String { "foo" } } func f() { let a = switch "" { case .foo(.zero): true default: false } switch "" { case .foo(.zero): break default: break } }
extension String { static func foo(_ int: Int, other: Bool = true) -> String { "foo" } } func f() { let a = switch "" { case .foo(.zero): true default: false } switch "" { case .foo(.zero): break default: break } }
<stdin>:7:16: error: value of tuple type '(Int, other: Bool)' has no member 'zero' case .foo(.zero): true ~^~~~
extension String { static func foo(_ int: Int, other: Bool = true) -> String { "foo" } } func f() { let a = switch "" { case .foo(.zero): true default: false } switch "" { case .foo(.zero): break default: break } }
<stdin>:7:16: error: value of tuple type '(Int, other: Bool)' has no member 'zero' 5 | func f() { 6 | let a = switch "" { 7 | case .foo(.zero): true | `- error: value of tuple type '(Int, other: Bool)' has no member 'zero' 8 | default: false 9 | }
Swift version 5.10.1 (swift-5.10.1-RELEASE) Target: x86_64-unknown-linux-gnu
// The Swift Programming Language // https://docs.swift.org/swift-book print("Hello, world!") class TaskRunner { private(set) var count = 0 func callAsFunction() async { Task { count += 1 print(count) } } } let runner = TaskRunner() await runner()
// The Swift Programming Language // https://docs.swift.org/swift-book print("Hello, world!") class TaskRunner { private(set) var count = 0 func callAsFunction() async { Task { count += 1 print(count) } } } let runner = TaskRunner() await runner()
Hello, world! 1
// The Swift Programming Language // https://docs.swift.org/swift-book import Foundation print("Hello, world!") class TaskRunner { private(set) var count = 0 func callAsFunction() async { print(Thread.isMainThread) Task { print(Thread.isMainThread) count += 1 print(count) } print("End of callAsFunction") } } func main() { let runner = TaskRunner() print(Thread.isMainThread) Task { await runner() print("End of runner") } print("End of main") } main() print("End")
// The Swift Programming Language // https://docs.swift.org/swift-book import Foundation print("Hello, world!") class TaskRunner { private(set) var count = 0 func callAsFunction() async { print(Thread.isMainThread) Task { print(Thread.isMainThread) count += 1 print(count) } print("End of callAsFunction") } } func main() { let runner = TaskRunner() print(Thread.isMainThread) Task { await runner() print("End of runner") } print("End of main") } main() print("End")
Hello, world! true false End of callAsFunction End of runner false 1 End of main End
import Foundation import FoundationNetworking let url = URL(string: "https://api.isevenapi.xyz/api/iseven/6/")! let (data, _) = try await URLSession.shared.data(from: url) print(String(decoding: data, as: UTF8.self))
import Foundation import FoundationNetworking let url = URL(string: "https://api.isevenapi.xyz/api/iseven/6/")! let (data, _) = try await URLSession.shared.data(from: url) print(String(decoding: data, as: UTF8.self))
<stdin>:6:45: error: value of type 'URLSession' has no member 'data' let (data, _) = try await URLSession.shared.data(from: url) ~~~~~~~~~~~~~~~~~ ^~~~
import Foundation import FoundationNetworking let url = URL(string: "https://api.isevenapi.xyz/api/iseven/6/")! let (data, _) = try await URLSession.shared.data(from: url) print(String(decoding: data, as: UTF8.self))
{"ad":"WANTED: Air Traffic Control. No Exp. Needed; we train, HS grads 17-34. Great pay, benefits. Must relocate. Call 284-555-7133","iseven":true}
Swift version 6.0-dev (LLVM 579155491d559cc, Swift 64869e5a42221b2) Target: x86_64-unknown-linux-gnu
enum Foo { case foo(baz: Int) case foo(bar: Int) // NO ERROR!!!! }
enum Foo { case foo(baz: Int) case foo(bar: Int) // NO ERROR!!!! }
enum Foo { case foo(baz: Int) case foo(bar: Int) // NO ERROR!!!! } let foo: Foo = .foo(baz: 0) switch foo { case .foo(baz: let baz): print(baz.description) case .foo(bar: let bar): // ERROR print(bar.description) }
enum Foo { case foo(baz: Int) case foo(bar: Int) // NO ERROR!!!! } let foo: Foo = .foo(baz: 0) switch foo { case .foo(baz: let baz): print(baz.description) case .foo(bar: let bar): // ERROR print(bar.description) }
<stdin>:8:11: error: tuple pattern element label 'baz' must be 'bar' 6 | let foo: Foo = .foo(baz: 0) 7 | switch foo { 8 | case .foo(baz: let baz): | `- error: tuple pattern element label 'baz' must be 'bar' 9 | print(baz.description) 10 | case .foo(bar: let bar): // ERROR
enum Foo { case foo(v1: String) case foo(v2: String) } let foo = Foo.foo(v1: "Hello") print(foo) switch foo { case .foo(v1: let string): print(string) case .foo(v2: let string): print(string) }
enum Foo { case foo(v1: String) case foo(v2: String) } let foo = Foo.foo(v1: "Hello") print(foo) switch foo { case .foo(v1: let string): print(string) case .foo(v2: let string): print(string) }
swift-frontend: /home/buildnode/jenkins/workspace/oss-swift-5.4-package-linux-ubuntu-18_04/swift/lib/Sema/TypeCheckPattern.cpp:99: swift::EnumElementDecl *filterForEnumElement(swift::DeclContext *, swift::SourceLoc, bool, swift::LookupResult): Assertion `!foundElement && "ambiguity in enum case name lookup?!"' failed. Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump:
enum Foo { case foo(v1: String) case foo(v2: String) } let foo = Foo.foo(v1: "Hello") print(foo) switch foo { case .foo(v1: let string): print(string) case .foo(v2: let string): print(string) }
swift-frontend: /home/buildnode/jenkins/workspace/oss-swift-5.5-package-linux-ubuntu-18_04/swift/lib/Sema/TypeCheckPattern.cpp:100: swift::EnumElementDecl *filterForEnumElement(swift::DeclContext *, swift::SourceLoc, bool, swift::LookupResult): Assertion `!foundElement && "ambiguity in enum case name lookup?!"' failed. Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project and the crash backtrace. Stack dump:
enum Foo { case foo(v1: String) case foo(v2: String) } let foo = Foo.foo(v1: "Hello") print(foo) switch foo { case .foo(v1: let string): print(string) case .foo(v2: let string): print(string) }
<stdin>:11:12: error: tuple pattern element label 'v1' must be 'v2' case .foo(v1: let string): ^
let foo = { () -> some Codable in 1 }() print(foo)
let foo = { () -> some Codable in 1 }() print(foo)
<stdin>:1:19: error: 'some' types are only permitted in properties, subscripts, and functions 1 | let foo = { () -> some Codable in 1 }() | `- error: 'some' types are only permitted in properties, subscripts, and functions 2 | print(foo) 3 |
@freestanding(codeItem) macro Foo() = #externalMacro(module: "", type: "")
@freestanding(codeItem) macro Foo() = #externalMacro(module: "", type: "")
<stdin>:1:15: error: codeItem macros are an experimental feature that is not enabled 1 | @freestanding(codeItem) | `- error: codeItem macros are an experimental feature that is not enabled 2 | macro Foo() = #externalMacro(module: "", type: "") 3 | <stdin>:2:7: warning: external macro implementation type '.' could not be found for macro 'Foo()'; plugin for module '' not found 1 | @freestanding(codeItem) 2 | macro Foo() = #externalMacro(module: "", type: "") | `- warning: external macro implementation type '.' could not be found for macro 'Foo()'; plugin for module '' not found 3 |
let foo: (String) -> some CustomStringConvertible = { s in struct Foo: CustomStringConvertible { var description: String } return Foo(description: s) }
let foo: (String) -> some CustomStringConvertible = { s in struct Foo: CustomStringConvertible { var description: String } return Foo(description: s) }
<stdin>:5:12: error: cannot convert value of type 'Foo' to closure result type 'some CustomStringConvertible' 3 | var description: String 4 | } 5 | return Foo(description: s) | `- error: cannot convert value of type 'Foo' to closure result type 'some CustomStringConvertible' 6 | } 7 |
let foo: (String) -> any CustomStringConvertible = { s in struct Foo: CustomStringConvertible { var description: String } return Foo(description: s) }
let foo: (String) -> any CustomStringConvertible = { s in struct Foo: CustomStringConvertible { var description: String } return Foo(description: s) }
UInt64(Double(UInt64.max))
UInt64(Double(UInt64.max))
<stdin>:1:1: warning: result of 'UInt64' initializer is unused UInt64(Double(UInt64.max)) ^ ~~~~~~~~~~~~~~~~~~~~
print(UInt64.max) print(Double(UInt64.max))
print(UInt64.max) print(Double(UInt64.max))
18446744073709551615 1.8446744073709552e+19
enum SomeError: Error {} protocol MyProtocol { init(param: String) throws init(param: String) throws(SomeError) }
enum SomeError: Error {} protocol MyProtocol { init(param: String) throws init(param: String) throws(SomeError) }
<stdin>:5:5: error: invalid redeclaration of 'init(param:)' 3 | protocol MyProtocol { 4 | init(param: String) throws 5 | init(param: String) throws(SomeError) | `- error: invalid redeclaration of 'init(param:)' 6 | } 7 |
protocol MyProtocol { func a(param: String) throws(any LocalizedError) }
protocol MyProtocol { func a(param: String) throws(any LocalizedError) }
<stdin>:2:38: error: cannot find type 'LocalizedError' in scope 1 | protocol MyProtocol { 2 | func a(param: String) throws(any LocalizedError) | `- error: cannot find type 'LocalizedError' in scope 3 | } 4 | <stdin>:2:34: error: thrown type '<<error type>>' does not conform to the 'Error' protocol 1 | protocol MyProtocol { 2 | func a(param: String) throws(any LocalizedError) | `- error: thrown type '<<error type>>' does not conform to the 'Error' protocol 3 | } 4 |
import Foundation protocol MyProtocol { func a(param: String) throws(any LocalizedError) }
import Foundation protocol MyProtocol { func a(param: String) throws(any LocalizedError) }
<stdin>:4:34: error: thrown type 'any LocalizedError' does not conform to the 'Error' protocol 2 | 3 | protocol MyProtocol { 4 | func a(param: String) throws(any LocalizedError) | `- error: thrown type 'any LocalizedError' does not conform to the 'Error' protocol 5 | } 6 |
protocol MyProtocol { func a(param: String) throws(Error) func a(param: String) throws(Never) }
protocol MyProtocol { func a(param: String) throws(Error) func a(param: String) throws(Never) }
<stdin>:3:10: error: invalid redeclaration of 'a(param:)' 1 | protocol MyProtocol { 2 | func a(param: String) throws(Error) 3 | func a(param: String) throws(Never) | `- error: invalid redeclaration of 'a(param:)' 4 | } 5 |
import Foundation public protocol AnyOptionalType { static var wrappedType: Any.Type { get } static var `nil`: Any { get } var wrappedValue: Any? { get } } public protocol OptionalType: AnyOptionalType { associatedtype Wrapped init(_ wrapped: Wrapped) } extension OptionalType { public static var wrappedType: Any.Type { return Wrapped.self } } extension Optional: OptionalType { public static var `nil`: Any { Self.none as Any } public var wrappedValue: Any? { self } } func main(x: Int?) async throws { if let x = x as? any AnyOptionalType { if case .some(let x) = x.wrappedValue { print("AnyOptionalType: \(x)") } else { print("AnyOptionalType none") } } else { print("not AnyOptionalType") } } try await main(x: nil)
import Foundation public protocol AnyOptionalType { static var wrappedType: Any.Type { get } static var `nil`: Any { get } var wrappedValue: Any? { get } } public protocol OptionalType: AnyOptionalType { associatedtype Wrapped init(_ wrapped: Wrapped) } extension OptionalType { public static var wrappedType: Any.Type { return Wrapped.self } } extension Optional: OptionalType { public static var `nil`: Any { Self.none as Any } public var wrappedValue: Any? { self } } func main(x: Int?) async throws { if let x = x as? any AnyOptionalType { if case .some(let x) = x.wrappedValue { print("AnyOptionalType: \(x)") } else { print("AnyOptionalType none") } } else { print("not AnyOptionalType") } } try await main(x: nil)
AnyOptionalType none
import Foundation public protocol AnyOptionalType { static var wrappedType: Any.Type { get } static var `nil`: Any { get } var wrappedValue: Any? { get } } public protocol OptionalType: AnyOptionalType { associatedtype Wrapped init(_ wrapped: Wrapped) } extension OptionalType { public static var wrappedType: Any.Type { return Wrapped.self } } extension Optional: OptionalType { public static var `nil`: Any { Self.none as Any } public var wrappedValue: Any? { self } } func main(x: Int?) async throws { if let x = x as? any AnyOptionalType { if case .some(let x) = x.wrappedValue { print("AnyOptionalType: \(x)") } else { print("AnyOptionalType none") } } else { print("not AnyOptionalType") } } try await main(x: nil)
AnyOptionalType none
import Foundation public protocol AnyOptionalType { static var wrappedType: Any.Type { get } static var `nil`: Any { get } var wrappedValue: Any? { get } } public protocol OptionalType: AnyOptionalType { associatedtype Wrapped init(_ wrapped: Wrapped) } extension OptionalType { public static var wrappedType: Any.Type { return Wrapped.self } } extension Optional: OptionalType { public static var `nil`: Any { Self.none as Any } public var wrappedValue: Any? { self } } func main(x: Int?) async throws { if let x = x as? any AnyOptionalType { if case .some(let x) = x.wrappedValue { print("AnyOptionalType: \(x)") } else { print("AnyOptionalType none") } } else { print("not AnyOptionalType") } } try await main(x: nil)
AnyOptionalType none
AnyOptionalType none
で終了したよ。 (edited)enum E: Sendable { case a, b, c } actor A { func foo(e: E = .a) {} } struct Main: Sendable { let a: A = A() init() {} func run() async { await a.foo(e: .a) } }
enum E: Sendable { case a, b, c } actor A { func foo(e: E = .a) {} } struct Main: Sendable { let a: A = A() init() {} func run() async { await a.foo(e: .a) } }
enum E: Sendable { case a, b, c } actor A { func foo(e: E = .a) {} } struct Main: Sendable { let a: A = A() init() {} func run() async { await a.foo(e: .a) } }
enum E: Sendable { case a, b, c } actor A { func foo(e: E = .a) {} } struct Main: Sendable { let a: A = A() init() {} func run() async { await a.foo(e: .a) } }
enum E: Sendable { case a, b, c } actor A { func foo(e: E = .a) {} } struct Main: Sendable { let a: A = A() init() {} func run() async { await a.foo(e: .a) } }
struct Foo<Bar> { func foo() { struct Body: Codable { } } }
struct Foo<Bar> { func foo() { struct Body: Codable { } } }
<stdin>:3:12: error: type 'Body' cannot be nested in generic function 'foo()' 1 | struct Foo<Bar> { 2 | func foo() { 3 | struct Body: Codable { | `- error: type 'Body' cannot be nested in generic function 'foo()' 4 | 5 | }
print([1,2,3].randomElement()!)
struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
$ pbpaste|swift - -strict-concurrency=complete $ swift -strict-concurrency=complete (pbpaste|psub) /var/folders/kt/2mwy9b_56_7993x190pl_1fh0000gn/T/.psub.4cIohIsV1d:8:13: warning: sending 'self'-isolated value of type 'S' with later accesses to actor-isolated context risks causing data races; this is an error in the Swift 6 language mode 6 | 7 | func main(a: A) async { 8 | await a.foo() | `- warning: sending 'self'-isolated value of type 'S' with later accesses to actor-isolated context risks causing data races; this is an error in the Swift 6 language mode 9 | } $ swift -version swift-driver version: 1.112.3 Apple Swift version 6.0 (swiftlang-6.0.0.6.8 clang-1600.0.23.1) Target: arm64-apple-macosx15.0
(edited)[omochi@omochi-mbp sen]$ cat a.swift struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() } print(1) [omochi@omochi-mbp sen]$ cat a.swift | swift - -strict-concurrency=complete 1
a
になってると思うけど (a.swift
の場合) (edited)print(#file)
[omochi@omochi-mbp sen]$ cat a.swift | swift -module-name main -strict-concurrency=complete - 1 <stdin>:8:13: warning: sending 'self'-isolated value of type 'S' with later accesses to actor-isolated context risks causing data races; this is an error in the Swift 6 language mode 6 | 7 | func main(a: A) async { 8 | await a.foo() | `- warning: sending 'self'-isolated value of type 'S' with later accesses to actor-isolated context risks causing data races; this is an error in the Swift 6 language mode 9 | } 10 |
[omochi@omochi-mbp sen]$ cat a.swift | swift -strict-concurrency=complete - 1 <stdin>:8:13: warning: sending 'self'-isolated value of type 'S' with later accesses to actor-isolated context risks causing data races; this is an error in the Swift 6 language mode 6 | 7 | func main(a: A) async { 8 | await a.foo() | `- warning: sending 'self'-isolated value of type 'S' with later accesses to actor-isolated context risks causing data races; this is an error in the Swift 6 language mode 9 | } 10 |
てかこれでいいですね-
の場所が違っています。 (edited)-
が左にあると (edited)struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
(edited)struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
(edited)struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
(edited)struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
(edited)=
がエスケープされてるな。 Jul 26 11:36:50 swiftmain-discord-bot web-pcflp `executeTarget`: `/usr/bin/env -i PATH\=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin timeout --signal\=KILL 30 swift -strict-concurrency\=complete -` Jul 26 11:36:50 swift60-discord-bot web-fdnmh `executeTarget`: `/usr/bin/env -i PATH\=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin timeout --signal\=KILL 30 swift -strict-concurrency\=complete -` Jul 26 11:36:52 swift510-discord-bot web-cqtb2 `executeTarget`: `/usr/bin/env -i PATH\=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin timeout --signal\=KILL 30 swift -strict-concurrency\=complete -`
$ pbpaste|swift -strict-concurrency=complete - <stdin>:8:13: warning: sending 'self'-isolated value of type 'S' with later accesses to actor-isolated context risks causing data races; this is an error in the Swift 6 language mode 6 | 7 | func main(a: A) async { 8 | await a.foo() | `- warning: sending 'self'-isolated value of type 'S' with later accesses to actor-isolated context risks causing data races; this is an error in the Swift 6 language mode 9 | } $ pbpaste|docker run --rm swiftlang/swift:nightly swift -strict-concurrency=complete - $ pbpaste|docker run --rm swiftlang/swift:nightly-6.0-jammy swift -strict-concurrency=complete - $ pbpaste|docker run --rm swift swift -strict-concurrency=complete -
$ docker run -it --rm swiftlang/swift:nightly ################################################################ # # # Swift Nightly Docker Image # # Tag: swift-DEVELOPMENT-SNAPSHOT-2024-07-22-a # # # ################################################################ root@6db06d8b9690:/# echo 'struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }'>a.swift root@6db06d8b9690:/# swift -strict-concurrency=complete a.swift root@6db06d8b9690:/# swift -version Swift version 6.0-dev (LLVM 3427f33b53c666b, Swift c21a3a974d40e14) Target: aarch64-unknown-linux-gnu
$ pbpaste|swift20240724 -strict-concurrency=complete - 1 $ swift20240724 -strict-concurrency=complete (pbpaste|psub) 1 $ swift20240724 -version Apple Swift version 6.0-dev (LLVM 3c6e1d334961f5e, Swift 384d7f77a53d8a0) Target: arm64-apple-macosx15.0
struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
struct S: Sendable {} actor A { func foo(e: S = S()) {} } func main(a: A) async { await a.foo() }
struct S { func foo() -> Int { 42 } } let fooRef = S.foo for any in [0, S()] { guard let s = any as? S else { continue } fooRef(s) }
struct S { func foo() -> Int { 42 } } let fooRef = S.foo for any in [0, S()] { guard let s = any as? S else { continue } fooRef(s) }
<stdin>:13:5: error: function is unused 11 | continue 12 | } 13 | fooRef(s) | `- error: function is unused 14 | } 15 |
struct S { func foo() -> Int { 42 } } let fooRef = S.foo fooRef(S()) fooRef(S())()
(edited)struct S { func foo() -> Int { 42 } } let fooRef = S.foo fooRef(S()) fooRef(S())()
(edited)<stdin>:8:1: error: function is unused 6 | 7 | let fooRef = S.foo 8 | fooRef(S()) | `- error: function is unused 9 | fooRef(S())() 10 | <stdin>:9:1: warning: result of call to function returning 'Int' is unused 7 | let fooRef = S.foo 8 | fooRef(S()) 9 | fooRef(S())() | `- warning: result of call to function returning 'Int' is unused 10 |
(edited)struct S { func foo() -> Int { 42 } } let fooRef = S.foo fooRef(S()) fooRef(S())()
(edited)<stdin>:8:1: error: function is unused fooRef(S()) ^~~~~~~~~~~ <stdin>:9:1: warning: result of call to function returning 'Int' is unused fooRef(S())() ^ ~~
_ = foo
なら許されたから_ =
が良さそうね (edited)Any
に関数を入れて放置したら壊れるということになってしまう。 単に呼び出し忘れだろうという判断をしているのだと思います。func main() { {} }
func main() { {} }
<stdin>:2:3: error: closure expression is unused 1 | func main() { 2 | {} | |- error: closure expression is unused | `- note: did you mean to use a 'do' statement? 3 | } 4 |
struct S { let foo: Int } func main() { \S.foo }
struct S { let foo: Int } func main() { \S.foo }
<stdin>:6:3: error: result of key path is unused 4 | 5 | func main() { 6 | \S.foo | `- error: result of key path is unused 7 | } 8 |
class R { func foo() async {} } Task { @MainActor () in let r = R() await r.foo() }
class R { func foo() async {} } Task { @MainActor () in let r = R() await r.foo() }
<stdin>:5:9: warning: passing argument of non-sendable type 'R' outside of main actor-isolated context may introduce data races await r.foo() ^ <stdin>:1:7: note: class 'R' does not conform to the 'Sendable' protocol class R { func foo() async {} } ^
class Repository { func doSomething() async { } } Task { @MainActor in let repository = Repository() await repository.doSomething() }
class Repository { func doSomething() async { } } Task { @MainActor in let repository = Repository() await repository.doSomething() }
<stdin>:8:11: warning: passing argument of non-sendable type 'Repository' outside of main actor-isolated context may introduce data races await repository.doSomething() ^ <stdin>:1:7: note: class 'Repository' does not conform to the 'Sendable' protocol class Repository { ^
class Repository { func doSomething() async { } } Task { @MainActor in let repository = Repository() await repository.doSomething() }
class Repository { func doSomething() async { } } Task { @MainActor in let repository = Repository() await repository.doSomething() }
class R { func foo() async {} } @MainActor func main() async { Task { @MainActor () in let r = R() await r.foo() } }
(edited)class R { func foo() async {} } @MainActor func main() async { Task { @MainActor () in let r = R() await r.foo() } }
(edited)<stdin>:7:11: warning: passing argument of non-sendable type 'R' outside of main actor-isolated context may introduce data races await r.foo() ^ <stdin>:1:7: note: class 'R' does not conform to the 'Sendable' protocol class R { func foo() async {} } ^
foo
は async
だからisolation domainがnon-isolatedになるから、 MainActor
からisolation boundaryをまたいでnon-Sendable
な self
( r
)を渡してることになるのか。そして、region based isolationで安全なことが確認されてSwift 6だとエラーにならなくなると。 (edited)class R { func foo() async {} } @MainActor func main() async { Task { @MainActor () in let r = R() await r.foo() } }
class R { func foo() async {} } @MainActor func main() async { Task { @MainActor () in let r = R() await r.foo() } }
<stdin>:5:11: warning: extraneous whitespace between attribute name and '('; this is an error in the Swift 6 language mode 3 | @MainActor 4 | func main() async { 5 | Task { @MainActor () in | `- warning: extraneous whitespace between attribute name and '('; this is an error in the Swift 6 language mode 6 | let r = R() 7 | await r.foo()
()
が @MainActor
に付いてると認識されてるのかimport Foundation print(DispatchQueue.concurrentPerform)
import Foundation print(DispatchQueue.concurrentPerform)
(Function)
@MainActor () in
は間違い? @MainActor () -> Void in
はいいみたいだけど。パースのルールが変わったのかな?@MainActor() () in
でもいいみたい (edited)class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() await repository.doSomething() repository.value += 1 }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() await repository.doSomething() repository.value += 1 }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() await repository.doSomething() repository.value += 1 }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() await repository.doSomething() repository.value += 1 }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() await repository.doSomething() repository.value += 1 }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() await repository.doSomething() repository.value += 1 }
@MainActor() () in
でもいいみたい (edited)await
してるから確かに同時には起こらないか。class Repository { var value: Int = 0 func doSomething() async { value += 1 } } let task = Task { @MainActor in let repository = Repository() async let x: Void = repository.doSomething() repository.value += 1 await x print(repository.value) } await task.value
(edited)class Repository { var value: Int = 0 func doSomething() async { value += 1 } } let task = Task { @MainActor in let repository = Repository() async let x: Void = repository.doSomething() repository.value += 1 await x print(repository.value) } await task.value
(edited)<stdin>:11:26: error: sending 'repository' risks causing data races 9 | let task = Task { @MainActor in 10 | let repository = Repository() 11 | async let x: Void = repository.doSomething() | |- error: sending 'repository' risks causing data races | `- note: sending 'repository' into async let risks causing data races between async let uses and local uses 12 | repository.value += 1 | `- note: access can happen concurrently 13 | await x 14 | print(repository.value)
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } let task = Task { @MainActor in let repository = Repository() async let x: Void = repository.doSomething() repository.value += 1 await x print(repository.value) } await task.value
(edited)<stdin>:11:26: error: sending 'repository' risks causing data races 9 | let task = Task { @MainActor in 10 | let repository = Repository() 11 | async let x: Void = repository.doSomething() | |- error: sending 'repository' risks causing data races | `- note: sending 'repository' into async let risks causing data races between async let uses and local uses 12 | repository.value += 1 | `- note: access can happen concurrently 13 | await x 14 | print(repository.value)
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() async let x: Void = repository.doSomething() repository.value += 1 await x }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() async let x: Void = repository.doSomething() repository.value += 1 await x }
<stdin>:11:26: error: sending 'repository' risks causing data races 9 | Task { @MainActor in 10 | let repository = Repository() 11 | async let x: Void = repository.doSomething() | |- error: sending 'repository' risks causing data races | `- note: sending 'repository' into async let risks causing data races between async let uses and local uses 12 | repository.value += 1 | `- note: access can happen concurrently 13 | await x 14 | }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() async let x: Void = repository.doSomething() repository.value += 1 await x }
<stdin>:11:26: error: sending 'repository' risks causing data races 9 | Task { @MainActor in 10 | let repository = Repository() 11 | async let x: Void = repository.doSomething() | |- error: sending 'repository' risks causing data races | `- note: sending 'repository' into async let risks causing data races between async let uses and local uses 12 | repository.value += 1 | `- note: access can happen concurrently 13 | await x 14 | }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() async let x: Void = repository.doSomething() // repository.value += 1 await x }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() async let x: Void = repository.doSomething() // repository.value += 1 await x }
class Repository { var value: Int = 0 func doSomething() async { value += 1 } } Task { @MainActor in let repository = Repository() async let x: Void = repository.doSomething() // repository.value += 1 await x }
class Foo { var value: Int = 0 } actor Bar { private let foo: Foo var value: Int { foo.value } init(foo: Foo) { self.foo = foo // fooはこのactorのdomainで保持される } } Task { @MainActor in let foo: Foo = .init() let bar: Bar = .init(foo: foo) // fooがbarのdomainに転送される foo.value += 1 // ここでfooに触るとdata raceを引き起こし得るので前の行の転送がエラー print(await bar.value) }
↑こういう別のisolation domainに転送されて保持されるような話かな?func nonIsolatedCallee(_ x: NonSendable) async { ... } func useValue(_ x: NonSendable) { ... } @MainActor func transferToMainActor<T>(_ t: T) { ... } actor MyActor { var state: NonSendable func example() async { // Regions: [{(), self}] let x = NonSendable() // Regions: [(x), {(), self}] // While nonIsolatedCallee executes the regions are: // Regions: [{(x), Task}, {(), self}] await nonIsolatedCallee(x) // Once it has finished executing, 'x' is disconnected again // Regions: [(x), {(), self}] // 'x' can be used since it is disconnected again. useValue(x) // (1) // 'x' can be transferred since it is disconnected again. await transferToMainActor(x) // (2) // Error! After transferring to main actor, permanently // in main actor, so we can't use it. useValue(x) // (3) } }
let f = { @MainActor(hogehoge) () in }
let f = { @MainActor(hogehoge) () in }
let f = { @MainActor(今日はカレーを食べよう) () in }
let f = { @MainActor(今日はカレーを食べよう) () in }
let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) }
let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) }
<stdin>:1:44: warning: extraneous whitespace between attribute name and '('; this is an error in the Swift 6 language mode 1 | let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) } | `- warning: extraneous whitespace between attribute name and '('; this is an error in the Swift 6 language mode 2 | <stdin>:1:72: error: cannot find 'a' in scope 1 | let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) } | `- error: cannot find 'a' in scope 2 | <stdin>:1:41: error: contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored 1 | let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) } | `- error: contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored 2 |
let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) }
<stdin>:1:44: warning: extraneous whitespace between attribute name and '('; this is an error in the Swift 6 language mode 1 | let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) } | `- warning: extraneous whitespace between attribute name and '('; this is an error in the Swift 6 language mode 2 | <stdin>:1:72: error: cannot find 'a' in scope 1 | let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) } | `- error: cannot find 'a' in scope 2 | <stdin>:1:41: error: contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored 1 | let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) } | `- error: contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored 2 |
let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) }
<stdin>:1:72: error: cannot find 'a' in scope let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) } ^ <stdin>:1:41: error: contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) in print(a) } ^ _ in
let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) -> Void in print(a) }
let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) -> Void in print(a) }
let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) -> Void in print(a) }
let f: @MainActor (Int) async -> Void = { @MainActor (a: Int) -> Void in print(a) }