Merge commit '510f29abf77e202780c11d5f6c7449313c819030' into swift-3-indexing-model

This commit is contained in:
Dmitri Gribenko
2016-04-14 13:45:27 -07:00
1151 changed files with 9048 additions and 8911 deletions

View File

@@ -3,6 +3,26 @@ Note: This is in reverse chronological order, so newer entries are added to the
Swift 3.0
-------
* [SE-0046] (https://github.com/apple/swift-evolution/blob/master/proposals/0046-first-label.md) Function parameters now have consistent labelling across all function parameters. With this update the first parameter declarations will now match the existing behavior of the second and later parameters. This change makes the language simpler.
Functions that were written and called as follows
```swift
func foo(x: Int, y: Int) {
}
foo(1, y: 2)
func bar(a a: Int, b: Int) {
}
bar(a: 3, b: 4)
```
will now be written as (to achieve the same behavior):
```swift
func foo(_ x: Int, y: Int) {}
foo(1, y: 2)
func bar(a: Int, b: Int) {}
bar(a: 3, b: 4)
```
* [SE-0037](https://github.com/apple/swift-evolution/blob/master/proposals/0037-clarify-comments-and-operators.md)
Comments are now treated as whitespace when determining whether an operator is
prefix, postfix, or binary. For example, these now work:

View File

@@ -14,14 +14,14 @@
// for performance measuring.
import TestsUtils
func ackermann(M : Int, _ N : Int) -> Int {
func ackermann(_ M: Int, _ N : Int) -> Int {
if (M == 0) { return N + 1 }
if (N == 0) { return ackermann(M - 1, 1) }
return ackermann(M - 1, ackermann(M, N - 1))
}
@inline(never)
func Ackermann(M : Int, _ N : Int) -> Int {
func Ackermann(_ M: Int, _ N : Int) -> Int {
// This if prevents optimizer from computing return value of Ackermann(3,9)
// at compile time.
if False() { return 0 }
@@ -33,7 +33,7 @@ func Ackermann(M : Int, _ N : Int) -> Int {
let ref_result = [5, 13, 29, 61, 125, 253, 509, 1021, 2045, 4093, 8189, 16381, 32765, 65533, 131069];
@inline(never)
public func run_Ackermann(N: Int) {
public func run_Ackermann(_ N: Int) {
let (m, n) = (3, 9)
var result = 0
for _ in 1...N {

View File

@@ -31,7 +31,7 @@ var words = [
"Bobby", "Dylan", "Johnny", "Phillip", "Craig"]
@inline(never)
public func run_AngryPhonebook(N: Int) {
public func run_AngryPhonebook(_ N: Int) {
// Permute the names.
for _ in 1...N {
for firstname in words {

View File

@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===//
@inline(never)
public func run_Array2D(N: Int) {
public func run_Array2D(_ N: Int) {
var A: [[Int]] = []
for _ in 0 ..< 1024 {
var B: [Int] = []

View File

@@ -15,7 +15,7 @@
import TestsUtils
@inline(never)
public func run_ArrayAppend(N: Int) {
public func run_ArrayAppend(_ N: Int) {
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()
@@ -27,7 +27,7 @@ public func run_ArrayAppend(N: Int) {
}
@inline(never)
public func run_ArrayAppendReserved(N: Int) {
public func run_ArrayAppendReserved(_ N: Int) {
for _ in 0..<N {
for _ in 0..<10 {
var nums = [Int]()

View File

@@ -17,7 +17,7 @@ class ArrayContainer {
arr = [Int] (repeating: 0, count: 100_000)
}
func runLoop(N: Int) {
func runLoop(_ N: Int) {
for _ in 0 ..< N {
for i in 0 ..< arr.count {
arr[i] = arr[i] + 1
@@ -32,7 +32,7 @@ func getArrayContainer() -> ArrayContainer {
}
@inline(never)
public func run_ArrayInClass(N: Int) {
public func run_ArrayInClass(_ N: Int) {
let a = getArrayContainer()
a.runLoop(N)
}

View File

@@ -21,7 +21,7 @@ func makeArray() -> [Int] {
}
@inline(never)
public func run_ArrayLiteral(N: Int) {
public func run_ArrayLiteral(_ N: Int) {
for _ in 1...10000*N {
makeArray()
}
@@ -34,7 +34,7 @@ func addLiteralArray() -> Int {
}
@inline(never)
public func run_ArrayValueProp(N: Int) {
public func run_ArrayValueProp(_ N: Int) {
var res = 123
for _ in 1...10000*N {
res += addLiteralArray()
@@ -75,7 +75,7 @@ func addLiteralArray4() -> Int {
}
@inline(never)
public func run_ArrayValueProp2(N: Int) {
public func run_ArrayValueProp2(_ N: Int) {
var res = 123
for _ in 1...10000*N {
res += addLiteralArray2()
@@ -85,7 +85,7 @@ public func run_ArrayValueProp2(N: Int) {
}
@inline(never)
public func run_ArrayValueProp3(N: Int) {
public func run_ArrayValueProp3(_ N: Int) {
var res = 123
for _ in 1...10000*N {
res += addLiteralArray3()
@@ -95,7 +95,7 @@ public func run_ArrayValueProp3(N: Int) {
}
@inline(never)
public func run_ArrayValueProp4(N: Int) {
public func run_ArrayValueProp4(_ N: Int) {
var res = 123
for _ in 1...10000*N {
res += addLiteralArray4()

View File

@@ -58,7 +58,7 @@ func genStructArray() {
}
@inline(never)
public func run_ArrayOfGenericPOD(N: Int) {
public func run_ArrayOfGenericPOD(_ N: Int) {
for _ in 0...N {
genEnumArray()
genIOUArray()

View File

@@ -86,7 +86,7 @@ func genRefStructArray() {
}
@inline(never)
public func run_ArrayOfGenericRef(N: Int) {
public func run_ArrayOfGenericRef(_ N: Int) {
for _ in 0...N {
genPODRefArray()
genCommonRefArray()

View File

@@ -53,7 +53,7 @@ func genStructArray() {
}
@inline(never)
public func run_ArrayOfPOD(N: Int) {
public func run_ArrayOfPOD(_ N: Int) {
for _ in 0...N {
genIntArray()
genEnumArray()

View File

@@ -97,7 +97,7 @@ func genRefStructArray() {
}
@inline(never)
public func run_ArrayOfRef(N: Int) {
public func run_ArrayOfRef(_ N: Int) {
for _ in 0...N {
genPODRefArray()
genCommonRefArray()

View File

@@ -14,13 +14,13 @@
import TestsUtils
@inline(never)
public func run_ArraySubscript(N: Int) {
public func run_ArraySubscript(_ N: Int) {
SRand()
let numArrays = 200*N
let numArrayElements = 100
func bound(x: Int) -> Int { return min(x, numArrayElements-1) }
func bound(_ x: Int) -> Int { return min(x, numArrayElements-1) }
var arrays = [[Int]](repeating: [], count: numArrays)
for i in 0..<numArrays {

View File

@@ -16,7 +16,7 @@
import Foundation
import TestsUtils
func countBitSet(num: Int) -> Int {
func countBitSet(_ num: Int) -> Int {
let bits = sizeof(Int) * 8
var cnt : Int = 0
var mask: Int = 1
@@ -30,7 +30,7 @@ func countBitSet(num: Int) -> Int {
}
@inline(never)
public func run_BitCount(N: Int) {
public func run_BitCount(_ N: Int) {
for _ in 1...100*N {
// Check some results.
CheckResults(countBitSet(1) == 1, "Incorrect results in BitCount.")

View File

@@ -17,7 +17,7 @@ import Foundation
import TestsUtils
// a naive O(n) implementation of byteswap.
func byteswap_n(a: UInt64) -> UInt64 {
func byteswap_n(_ a: UInt64) -> UInt64 {
return ((a & 0x00000000000000FF) << 56) |
((a & 0x000000000000FF00) << 40) |
((a & 0x0000000000FF0000) << 24) |
@@ -29,7 +29,7 @@ func byteswap_n(a: UInt64) -> UInt64 {
}
// a O(logn) implementation of byteswap.
func byteswap_logn(a: UInt64) -> UInt64 {
func byteswap_logn(_ a: UInt64) -> UInt64 {
var a = a
a = (a & 0x00000000FFFFFFFF) << 32 | (a & 0xFFFFFFFF00000000) >> 32
a = (a & 0x0000FFFF0000FFFF) << 16 | (a & 0xFFFF0000FFFF0000) >> 16
@@ -38,7 +38,7 @@ func byteswap_logn(a: UInt64) -> UInt64 {
}
@inline(never)
public func run_ByteSwap(N: Int) {
public func run_ByteSwap(_ N: Int) {
for _ in 1...100*N {
// Check some results.
CheckResults(byteswap_logn(byteswap_n(2457)) == 2457, "Incorrect results in ByteSwap.")

View File

@@ -14,7 +14,7 @@ import TestsUtils
import Foundation
@inline(never)
func my_atoi_impl(input : String) -> Int {
func my_atoi_impl(_ input : String) -> Int {
switch input {
case "0": return 0
case "1": return 1
@@ -31,7 +31,7 @@ func my_atoi_impl(input : String) -> Int {
}
@inline(never)
public func run_Calculator(N: Int) {
public func run_Calculator(_ N: Int) {
var c = 0
for _ in 1...N*5000 {
c += my_atoi_impl("10")

View File

@@ -10,21 +10,21 @@
//
//===----------------------------------------------------------------------===//
func sum(x:Int, y:Int) -> Int {
func sum(_ x:Int, y:Int) -> Int {
return x + y
}
@inline(never)
func benchCaptureProp<S : Sequence
>(
s:S, _ f:(S.Iterator.Element, S.Iterator.Element)->S.Iterator.Element) -> S.Iterator.Element {
_ s: S, _ f:(S.Iterator.Element, S.Iterator.Element)->S.Iterator.Element) -> S.Iterator.Element {
var it = s.makeIterator()
let initial = it.next()!
return IteratorSequence(it).reduce(initial, combine: f)
}
public func run_CaptureProp(N: Int) {
public func run_CaptureProp(_ N: Int) {
let a = 1...10_000
for _ in 1...100*N {
benchCaptureProp(a, sum)

View File

@@ -14,7 +14,7 @@
import TestsUtils
@inline(never)
public func run_Chars(N: Int) {
public func run_Chars(_ N: Int) {
// Permute some characters.
let alphabet: [Character] = [
"A", "B", "C", "D", "E", "F", "G",

View File

@@ -16,7 +16,7 @@ class Box {
}
@inline(never)
func sumArray(a: [Box]) -> Int {
func sumArray(_ a: [Box]) -> Int {
var s = 0
for i in 0..<a.count {
s += a[i].v
@@ -24,7 +24,7 @@ func sumArray(a: [Box]) -> Int {
return s
}
public func run_ClassArrayGetter(N: Int) {
public func run_ClassArrayGetter(_ N: Int) {
let aSize = 10_000
var a: [Box] = []
a.reserveCapacity(aSize)

View File

@@ -14,7 +14,7 @@
import TestsUtils
@inline(__always)
func debug(m:String) {}
func debug(_ m:String) {}
private var Count = 0
@@ -22,7 +22,7 @@ private var Count = 0
func bar() { Count += 1 }
@inline(never)
func runLoop(var1: Int, var2: Int) {
func runLoop(_ var1: Int, var2: Int) {
for _ in 0..<100_000 {
debug("Var1: \(var1) Var2: \(var2)")
bar()
@@ -30,7 +30,7 @@ func runLoop(var1: Int, var2: Int) {
}
@inline(never)
public func run_DeadArray(N: Int) {
public func run_DeadArray(_ N: Int) {
for _ in 1...N {
Count = 0
runLoop(0, var2: 0)

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_Dictionary2(N: Int) {
public func run_Dictionary2(_ N: Int) {
let size = 500
let ref_result = 199
var res = 0
@@ -57,7 +57,7 @@ func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
}
@inline(never)
public func run_Dictionary2OfObjects(N: Int) {
public func run_Dictionary2OfObjects(_ N: Int) {
let size = 500
let ref_result = 199
var res = 0

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_Dictionary3(N: Int) {
public func run_Dictionary3(_ N: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"
@@ -64,7 +64,7 @@ func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
}
@inline(never)
public func run_Dictionary3OfObjects(N: Int) {
public func run_Dictionary3OfObjects(_ N: Int) {
let size1 = 100
let reps = 20
let ref_result = "1 99 20 1980"

View File

@@ -52,7 +52,7 @@ class Stuff {
}
@inline(never)
public func run_DictionaryBridge(N: Int) {
public func run_DictionaryBridge(_ N: Int) {
for _ in 1...100*N {
_ = Stuff()
}

View File

@@ -20,7 +20,7 @@ func makeDictionary() -> [Int: Int] {
}
@inline(never)
public func run_DictionaryLiteral(N: Int) {
public func run_DictionaryLiteral(_ N: Int) {
for _ in 1...10000*N {
makeDictionary()
}

View File

@@ -15,7 +15,7 @@
import TestsUtils
@inline(never)
public func run_DictionaryRemove(N: Int) {
public func run_DictionaryRemove(_ N: Int) {
let size = 100
var dict = [Int: Int](minimumCapacity: size)
@@ -62,7 +62,7 @@ func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
}
@inline(never)
public func run_DictionaryRemoveOfObjects(N: Int) {
public func run_DictionaryRemoveOfObjects(_ N: Int) {
let size = 100
var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size)

View File

@@ -15,7 +15,7 @@
import TestsUtils
@inline(never)
public func run_DictionarySwap(N: Int) {
public func run_DictionarySwap(_ N: Int) {
let size = 100
var dict = [Int: Int](minimumCapacity: size)
@@ -40,7 +40,7 @@ public func run_DictionarySwap(N: Int) {
}
// Return true if correctly swapped, false otherwise
func swappedCorrectly(swapped: Bool, _ p25: Int, _ p75: Int) -> Bool {
func swappedCorrectly(_ swapped: Bool, _ p25: Int, _ p75: Int) -> Bool {
return swapped && (p25 == 75 && p75 == 25) ||
!swapped && (p25 == 25 && p75 == 75)
}
@@ -65,7 +65,7 @@ func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
}
@inline(never)
public func run_DictionarySwapOfObjects(N: Int) {
public func run_DictionarySwapOfObjects(_ N: Int) {
let size = 100
var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size)

View File

@@ -29,7 +29,7 @@ func doSomething() throws -> String {
}
@inline(never)
public func run_ErrorHandling(N: Int) {
public func run_ErrorHandling(_ N: Int) {
for _ in 1...5000*N {
do {
try doSomething()

View File

@@ -12,13 +12,13 @@
import TestsUtils
func fibonacci(n: Int) -> Int {
func fibonacci(_ n: Int) -> Int {
if (n < 2) { return 1 }
return fibonacci(n - 2) + fibonacci(n - 1)
}
@inline(never)
func Fibonacci(n: Int) -> Int {
func Fibonacci(_ n: Int) -> Int {
// This if prevents optimizer from computing return value of Fibonacci(32)
// at compile time.
if False() { return 0 }
@@ -28,7 +28,7 @@ func Fibonacci(n: Int) -> Int {
}
@inline(never)
public func run_Fibonacci(N: Int) {
public func run_Fibonacci(_ N: Int) {
let n = 32
let ref_result = 3524578
var result = 0

View File

@@ -16,7 +16,7 @@ import TestsUtils
class A
{
func f(a : Int) -> Int
func f(_ a: Int) -> Int
{
return a + 1
}
@@ -25,7 +25,7 @@ class A
var x = 0
var a = A()
@inline(never)
public func run_GlobalClass(N: Int) {
public func run_GlobalClass(_ N: Int) {
for _ in 0..<N
{
x = a.f(x)

View File

@@ -28,7 +28,7 @@ class TowersOfHanoi {
// Record all moves made.
var moves : [Move] = [Move]()
func solve(n: Int, start: String, auxiliary: String, end: String) {
func solve(_ n: Int, start: String, auxiliary: String, end: String) {
if (n == 1) {
moves.append(Move(from:start, to:end))
} else {
@@ -40,7 +40,7 @@ class TowersOfHanoi {
}
@inline(never)
public func run_Hanoi(N: Int) {
public func run_Hanoi(_ N: Int) {
for _ in 1...100*N {
let hanoi: TowersOfHanoi = TowersOfHanoi()
hanoi.solve(10, start: "A", auxiliary: "B", end: "C")

View File

@@ -25,7 +25,7 @@ class Hash {
}
/// \brief Add the bytes in \p Msg to the hash.
func update(Msg: String) {
func update(_ Msg: String) {
for c in Msg.unicodeScalars {
data[dataLength] = UInt8(ascii: c)
dataLength += 1
@@ -35,7 +35,7 @@ class Hash {
}
/// \brief Add the bytes in \p Msg to the hash.
func update(Msg: [UInt8]) {
func update(_ Msg: [UInt8]) {
for c in Msg {
data[dataLength] = c
dataLength += 1
@@ -52,7 +52,7 @@ class Hash {
return x
}
func digestFast(Res: inout [UInt8]) {
func digestFast(_ Res: inout [UInt8]) {
fillBlock()
hash()
// We use [UInt8] to avoid using String::append.
@@ -76,7 +76,7 @@ class Hash {
func hashState() -> String {
fatalError("Pure virtual")
}
func hashStateFast(Res: inout [UInt8]) {
func hashStateFast(_ Res: inout [UInt8]) {
fatalError("Pure virtual")
}
@@ -91,7 +91,7 @@ class Hash {
/// \brief Convert a 4-byte integer to a hex string.
final
func toHex(In: UInt32) -> String {
func toHex(_ In: UInt32) -> String {
var In = In
var Res = ""
for _ in 0..<8 {
@@ -102,7 +102,7 @@ class Hash {
}
final
func toHexFast(In: UInt32, _ Res: inout Array<UInt8>, _ Index : Int) {
func toHexFast(_ In: UInt32, _ Res: inout Array<UInt8>, _ Index : Int) {
var In = In
for i in 0..<4 {
// Convert one byte each iteration.
@@ -114,7 +114,7 @@ class Hash {
/// \brief Left-rotate \p x by \p c.
final
func rol(x: UInt32, _ c: UInt32) -> UInt32 {
func rol(_ x: UInt32, _ c: UInt32) -> UInt32 {
// TODO: use the &>> operator.
let a = UInt32(truncatingBitPattern: Int64(x) << Int64(c))
let b = UInt32(truncatingBitPattern: Int64(x) >> (32 - Int64(c)))
@@ -123,7 +123,7 @@ class Hash {
/// \brief Right-rotate \p x by \p c.
final
func ror(x: UInt32, _ c: UInt32) -> UInt32 {
func ror(_ x: UInt32, _ c: UInt32) -> UInt32 {
// TODO: use the &>> operator.
let a = UInt32(truncatingBitPattern: Int64(x) >> Int64(c))
let b = UInt32(truncatingBitPattern: Int64(x) << (32 - Int64(c)))
@@ -178,7 +178,7 @@ class MD5 : Hash {
dataLength = 0
}
func appendBytes(Val: Int, _ Message: inout Array<UInt8>, _ Offset : Int) {
func appendBytes(_ Val: Int, _ Message: inout Array<UInt8>, _ Offset : Int) {
Message[Offset] = UInt8(truncatingBitPattern: Val)
Message[Offset + 1] = UInt8(truncatingBitPattern: Val >> 8)
Message[Offset + 2] = UInt8(truncatingBitPattern: Val >> 16)
@@ -215,7 +215,7 @@ class MD5 : Hash {
dataLength += 8
}
func toUInt32(Message: Array<UInt8>, _ Offset: Int) -> UInt32 {
func toUInt32(_ Message: Array<UInt8>, _ Offset: Int) -> UInt32 {
let first = UInt32(Message[Offset + 0])
let second = UInt32(Message[Offset + 1]) << 8
let third = UInt32(Message[Offset + 2]) << 16
@@ -272,7 +272,7 @@ class MD5 : Hash {
h3 = d &+ h3
}
func reverseBytes(In: UInt32) -> UInt32 {
func reverseBytes(_ In: UInt32) -> UInt32 {
let B0 = (In >> 0 ) & 0xFF
let B1 = (In >> 8 ) & 0xFF
let B2 = (In >> 16) & 0xFF
@@ -290,7 +290,7 @@ class MD5 : Hash {
}
override
func hashStateFast(Res: inout [UInt8]) {
func hashStateFast(_ Res: inout [UInt8]) {
#if !NO_RANGE
var Idx : Int = 0
for h in [h0, h1, h2, h3] {
@@ -575,7 +575,7 @@ func == (lhs: [UInt8], rhs: [UInt8]) -> Bool {
}
@inline(never)
public func run_HashTest(N: Int) {
public func run_HashTest(_ N: Int) {
let TestMD5 = ["" : "d41d8cd98f00b204e9800998ecf8427e",
"The quick brown fox jumps over the lazy dog." : "e4d909c290d0fb1ca068ffaddf22cbd0",
"The quick brown fox jumps over the lazy cog." : "68aa5deab43e4df2b5e1f80190477fb0"]

View File

@@ -16,7 +16,7 @@ import TestsUtils
typealias rrggbb_t = UInt32
func output_sorted_sparse_rgb_histogram<S: Sequence where S.Iterator.Element == rrggbb_t>(samples: S, _ N: Int) {
func output_sorted_sparse_rgb_histogram<S: Sequence where S.Iterator.Element == rrggbb_t>(_ samples: S, _ N: Int) {
var histogram = Dictionary<rrggbb_t, Int>()
for _ in 1...50*N {
for sample in samples { // This part is really awful, I agree
@@ -109,6 +109,6 @@ let samples: [rrggbb_t] = [
]
@inline(never)
public func run_Histogram(N: Int) {
public func run_Histogram(_ N: Int) {
output_sorted_sparse_rgb_histogram(samples, N);
}

View File

@@ -24,7 +24,7 @@ class Integrate {
fun = f;
}
private func recEval(l:Double, fl:Double, r:Double, fr:Double, a:Double)->Double {
private func recEval(_ l:Double, fl:Double, r:Double, fr:Double, a:Double)->Double {
let h = (r - l) / 2
let hh = h / 2
let c = l + h
@@ -43,13 +43,13 @@ class Integrate {
}
@inline(never)
func computeArea(left:Double, right:Double)->Double {
func computeArea(_ left: Double, right:Double)->Double {
return recEval(left, fl:fun(left), r:right, fr:fun(right), a:0)
}
}
@inline(never)
public func run_Integrate(N: Int) {
public func run_Integrate(_ N: Int) {
let obj = Integrate(f: { x in (x*x + 1.0) * x});
let left = 0.0
let right = 10.0

View File

@@ -14,7 +14,7 @@
import TestsUtils
@inline(never)
public func run_Join(N: Int) {
public func run_Join(_ N: Int) {
var array: [String] = []
for x in 0..<1000 * N {
array.append(String(x))

View File

@@ -25,7 +25,7 @@ final class Node {
}
@inline(never)
public func run_LinkedList(N: Int) {
public func run_LinkedList(_ N: Int) {
let size = 100
var head = Node(n:nil, d:0)
for i in 0..<size {

View File

@@ -14,7 +14,7 @@ import TestsUtils
import Foundation
@inline(never)
public func run_MapReduce(N: Int) {
public func run_MapReduce(_ N: Int) {
var numbers = [Int](0..<1000)
var c = 0

View File

@@ -13,14 +13,14 @@
import TestsUtils
@inline(never)
func memset(a: inout [Int], _ c: Int) {
func memset(_ a: inout [Int], _ c: Int) {
for i in 0..<a.count {
a[i] = c
}
}
@inline(never)
public func run_Memset(N: Int) {
public func run_Memset(_ N: Int) {
var a = [Int](repeating: 0, count: 10_000)
for _ in 1...50*N {
memset(&a, 1)

View File

@@ -19,7 +19,7 @@ import Foundation
import TestsUtils
@inline(never)
public func run_NSDictionaryCastToSwift(N: Int) {
public func run_NSDictionaryCastToSwift(_ N: Int) {
let NSDict = NSDictionary()
var swiftDict = [String: NSObject]()
for _ in 1...10000*N {

View File

@@ -29,12 +29,12 @@ class G : K {
override func buzz() throws -> Int { return 0 }
}
func caller(x : P) throws {
func caller(_ x: P) throws {
try x.buzz()
}
@inline(never)
public func run_NSError(N: Int) {
public func run_NSError(_ N: Int) {
for _ in 1...N*1000 {
let k = K()
let g = G()

View File

@@ -14,7 +14,7 @@
import TestsUtils
import Foundation
public func run_NSStringConversion(N: Int) {
public func run_NSStringConversion(_ N: Int) {
let test:NSString = NSString(cString: "test", encoding: NSASCIIStringEncoding)!
for _ in 1...N * 10000 {
test as String

View File

@@ -24,7 +24,7 @@ class X<T : Comparable> {
}
}
public func run_NopDeinit(N: Int) {
public func run_NopDeinit(_ N: Int) {
for _ in 1...N {
var arr :[X<Int>] = []
let size = 500

View File

@@ -42,7 +42,7 @@ final class LinkedNode {
}
@inline(never)
func getInt(x: XX) -> Int {
func getInt(_ x: XX) -> Int {
return x.xx
}
@@ -57,7 +57,7 @@ func testSingleObject() -> Int {
}
@inline(never)
func addInts(t: TreeNode) -> Int {
func addInts(_ t: TreeNode) -> Int {
return t.left.xx + t.right.xx
}
@@ -72,7 +72,7 @@ func testTree() -> Int {
}
@inline(never)
func addAllInts(n: LinkedNode) -> Int {
func addAllInts(_ n: LinkedNode) -> Int {
var s = 0
var iter: LinkedNode? = n
while let iter2 = iter {
@@ -93,7 +93,7 @@ func testList() -> Int {
}
@inline(never)
func identity(x: Int) -> Int {
func identity(_ x: Int) -> Int {
return x
}
@@ -109,7 +109,7 @@ func testArray() -> Int {
}
@inline(never)
public func run_ObjectAllocation(N: Int) {
public func run_ObjectAllocation(_ N: Int) {
var SingleObjectResult = 0
var TreeResult = 0

View File

@@ -22,12 +22,12 @@ enum MyState : String {
}
@inline(never)
func check_state(state : MyState) -> Int {
func check_state(_ state : MyState) -> Int {
return state == .Opened ? 1 : 0
}
@inline(never)
public func run_OpenClose(N: Int) {
public func run_OpenClose(_ N: Int) {
var c = 0
for _ in 1...N*10000 {
c += check_state(MyState.Closed)

View File

@@ -59,7 +59,7 @@ func <(lhs: Record, rhs: Record) -> Bool {
}
@inline(never)
public func run_Phonebook(N: Int) {
public func run_Phonebook(_ N: Int) {
// The list of names in the phonebook.
var Names : [Record] = []
for first in words {

View File

@@ -244,7 +244,7 @@ public class F3 : B3 {
// Test the cost of polymorphic method invocation
// on a class without any subclasses
@inline(never)
func test(a:A, _ UPTO: Int) -> Int64 {
func test(_ a:A, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO {
cnt += a.run2()
@@ -255,7 +255,7 @@ func test(a:A, _ UPTO: Int) -> Int64 {
// Test the cost of polymorphic method invocation
// on a class with 1 subclass
@inline(never)
func test(a:A1, _ UPTO: Int) -> Int64 {
func test(_ a:A1, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO {
cnt += a.run2()
@@ -266,7 +266,7 @@ func test(a:A1, _ UPTO: Int) -> Int64 {
// Test the cost of polymorphic method invocation
// on a class with 2 subclasses
@inline(never)
func test(a:A2, _ UPTO: Int) -> Int64 {
func test(_ a:A2, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO {
cnt += a.run2()
@@ -278,7 +278,7 @@ func test(a:A2, _ UPTO: Int) -> Int64 {
// on a class with 2 subclasses on objects
// of different subclasses
@inline(never)
func test(a2_c2:A2, _ a2_d2:A2, _ UPTO: Int) -> Int64 {
func test(_ a2_c2:A2, _ a2_d2:A2, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO/2 {
cnt += a2_c2.run2()
@@ -291,7 +291,7 @@ func test(a2_c2:A2, _ a2_d2:A2, _ UPTO: Int) -> Int64 {
// on a class with 4 subclasses on objects
// of different subclasses
@inline(never)
func test(a3_c3: A3, _ a3_d3: A3, _ a3_e3: A3, _ a3_f3: A3, _ UPTO: Int) -> Int64 {
func test(_ a3_c3: A3, _ a3_d3: A3, _ a3_e3: A3, _ a3_f3: A3, _ UPTO: Int) -> Int64 {
var cnt : Int64 = 0
for _ in 0..<UPTO/4 {
cnt += a3_c3.run2()
@@ -305,7 +305,7 @@ func test(a3_c3: A3, _ a3_d3: A3, _ a3_e3: A3, _ a3_f3: A3, _ UPTO: Int) -> Int6
@inline(never)
public func run_PolymorphicCalls(N:Int) {
public func run_PolymorphicCalls(_ N:Int) {
let UPTO = 10000 * N
let a = A(b:B(x:1))

View File

@@ -16,7 +16,7 @@ let reps = 1
let arrayCount = 1024
@inline(never)
public func run_PopFrontArray(N: Int) {
public func run_PopFrontArray(_ N: Int) {
let orig = Array(repeating: 1, count: arrayCount)
var a = [Int]()
for _ in 1...20*N {
@@ -33,7 +33,7 @@ public func run_PopFrontArray(N: Int) {
}
@inline(never)
public func run_PopFrontUnsafePointer(N: Int) {
public func run_PopFrontUnsafePointer(_ N: Int) {
var orig = Array(repeating: 1, count: arrayCount)
let a = UnsafeMutablePointer<Int>(allocatingCapacity: arrayCount)
for _ in 1...100*N {

View File

@@ -21,7 +21,7 @@ let arrayCount = 1024
func _arrayReplace<B: _ArrayBufferProtocol, C: Collection
where C.Iterator.Element == B.Element, B.Index == Int
>(
target: inout B, _ subRange: Range<Int>, _ newValues: C
_ target: inout B, _ subRange: Range<Int>, _ newValues: C
) {
_precondition(
subRange.lowerBound >= 0,
@@ -46,7 +46,7 @@ func _arrayReplace<B: _ArrayBufferProtocol, C: Collection
@inline(never)
public func run_PopFrontArrayGeneric(N: Int) {
public func run_PopFrontArrayGeneric(_ N: Int) {
let orig = Array(repeating: 1, count: arrayCount)
var a = [Int]()
for _ in 1...20*N {

View File

@@ -37,7 +37,7 @@ class PriorityQueue {
}
// Insert element N to heap, maintaining the heap property.
func insert(n : EdgeCost) {
func insert(_ n: EdgeCost) {
let ind: Int = heap.count
heap.append(n)
graphIndexToHeapIndexMap[n.to] = heap.count - 1
@@ -46,7 +46,7 @@ class PriorityQueue {
// Insert element N if in's not in the heap, or update its cost if the new
// value is less than the existing one.
func insertOrUpdate(n : EdgeCost) {
func insertOrUpdate(_ n: EdgeCost) {
let id = n.to
let c = n.cost
if let ind = graphIndexToHeapIndexMap[id] {
@@ -64,7 +64,7 @@ class PriorityQueue {
// Restore heap property by moving element at index IND up.
// This is needed after insertion, and after decreasing an element's cost.
func bubbleUp(ind: Int) {
func bubbleUp(_ ind: Int) {
var ind = ind
let c = heap[ind].cost
while (ind != 0) {
@@ -93,7 +93,7 @@ class PriorityQueue {
// Restore heap property by moving element at index IND down.
// This is needed after removing an element, and after increasing an
// element's cost.
func bubbleDown(ind: Int) {
func bubbleDown(_ ind: Int) {
var ind = ind
let n = heap.count
while (ind < n) {
@@ -118,7 +118,7 @@ class PriorityQueue {
// Swaps elements I and J in the heap and correspondingly updates
// graphIndexToHeapIndexMap.
func Swap(i: Int, with j : Int) {
func Swap(_ i: Int, with j : Int) {
if (i == j) {
return
}
@@ -139,13 +139,13 @@ class PriorityQueue {
}
}
func getLeftChildIndex(index : Int) -> Int {
func getLeftChildIndex(_ index : Int) -> Int {
return index*2 + 1
}
func getRightChildIndex(index : Int) -> Int {
func getRightChildIndex(_ index : Int) -> Int {
return (index + 1)*2
}
func getParentIndex(childIndex : Int) -> Int {
func getParentIndex(_ childIndex : Int) -> Int {
return (childIndex - 1)/2
}
}
@@ -183,7 +183,7 @@ extension Edge : Hashable {
}
}
func Prims(graph : Array<GraphNode>, _ fun : (Int,Int)->Double) -> Array<Int?> {
func Prims(_ graph : Array<GraphNode>, _ fun : (Int,Int)->Double) -> Array<Int?> {
var treeEdges = Array<Int?>(repeating:nil, count:graph.count)
let queue = PriorityQueue(Num:graph.count)
@@ -214,7 +214,7 @@ func Prims(graph : Array<GraphNode>, _ fun : (Int,Int)->Double) -> Array<Int?> {
}
@inline(never)
public func run_Prims(N: Int) {
public func run_Prims(_ N: Int) {
for _ in 1...5*N {
let nodes : [Int] = [ 0, 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,

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_ProtocolDispatch(N: Int) {
public func run_ProtocolDispatch(_ N: Int) {
let x = someProtocolFactory()

View File

@@ -27,7 +27,7 @@ struct Game : Pingable {
}
@inline(never)
func use_protocol(val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
func use_protocol(_ val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
var t = game1.ping() + game1.pong()
if (val % 2 == 0) {
t += game1.pong() + game1.ping()
@@ -44,12 +44,12 @@ func use_protocol(val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
}
@inline(never)
func wrapper(val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
func wrapper(_ val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int {
return use_protocol(val, game1, game2)
}
@inline(never)
public func run_ProtocolDispatch2(N: Int) {
public func run_ProtocolDispatch2(_ N: Int) {
var c = 0
let g1 = Game()
let g2 = Game()

View File

@@ -24,7 +24,7 @@ struct RC4 {
}
mutating
func initialize(Key: [UInt8]) {
func initialize(_ Key: [UInt8]) {
for i in 0..<256 {
State[i] = UInt8(i)
}
@@ -39,7 +39,7 @@ struct RC4 {
}
mutating
func swapByIndex(x: Int, y: Int) {
func swapByIndex(_ x: Int, y: Int) {
let T1 : UInt8 = State[x]
let T2 : UInt8 = State[y]
State[x] = T2
@@ -55,7 +55,7 @@ struct RC4 {
}
mutating
func encrypt(Data: inout [UInt8]) {
func encrypt(_ Data: inout [UInt8]) {
let cnt = Data.count
for i in 0..<cnt {
Data[i] = Data[i] ^ next()
@@ -76,7 +76,7 @@ let RefResults : [UInt8] = [245, 62, 245, 202, 138, 120, 186, 107, 255, 189,
@inline(never)
public func run_RC4(N: Int) {
public func run_RC4(_ N: Int) {
let messageLen = 100
let iterations = 500
let Secret = "This is my secret message"

View File

@@ -19,7 +19,7 @@ import Foundation
import TestsUtils
@inline(never)
public func run_RGBHistogram(N: Int) {
public func run_RGBHistogram(_ N: Int) {
var histogram = [(key: rrggbb_t, value: Int)]()
for _ in 1...100*N {
histogram = createSortedSparseRGBHistogram(samples)
@@ -86,7 +86,7 @@ let samples: [rrggbb_t] = [
0x607F4D9F, 0x9733E55E, 0xA360439D, 0x1DB568FD, 0xB7A5C3A1, 0xBE84492D
]
func isCorrectHistogram(histogram: [(key: rrggbb_t, value: Int)]) -> Bool {
func isCorrectHistogram(_ histogram: [(key: rrggbb_t, value: Int)]) -> Bool {
return histogram.count == 157 &&
histogram[0].0 == 0x00808080 && histogram[0].1 == 54 &&
histogram[156].0 == 0x003B8D96 && histogram[156].1 == 1
@@ -94,7 +94,7 @@ func isCorrectHistogram(histogram: [(key: rrggbb_t, value: Int)]) -> Bool {
func createSortedSparseRGBHistogram
<S: Sequence where S.Iterator.Element == rrggbb_t>
(samples: S) -> [(key: rrggbb_t, value: Int)] {
(_ samples: S) -> [(key: rrggbb_t, value: Int)] {
var histogram = Dictionary<rrggbb_t, Int>()
for sample in samples {
@@ -130,7 +130,7 @@ func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
func isCorrectHistogramOfObjects(histogram: [(key: Box<rrggbb_t>, value: Box<Int>)]) -> Bool {
func isCorrectHistogramOfObjects(_ histogram: [(key: Box<rrggbb_t>, value: Box<Int>)]) -> Bool {
return histogram.count == 157 &&
histogram[0].0.value == 0x00808080 && histogram[0].1.value == 54 &&
histogram[156].0.value == 0x003B8D96 && histogram[156].1.value == 1
@@ -138,7 +138,7 @@ func isCorrectHistogramOfObjects(histogram: [(key: Box<rrggbb_t>, value: Box<Int
func createSortedSparseRGBHistogramOfObjects
<S: Sequence where S.Iterator.Element == rrggbb_t>
(samples: S) -> [(key: Box<rrggbb_t>, value: Box<Int>)] {
(_ samples: S) -> [(key: Box<rrggbb_t>, value: Box<Int>)] {
var histogram = Dictionary<Box<rrggbb_t>, Box<Int>>()
for sample in samples {
@@ -157,7 +157,7 @@ func createSortedSparseRGBHistogramOfObjects
}
@inline(never)
public func run_RGBHistogramOfObjects(N: Int) {
public func run_RGBHistogramOfObjects(_ N: Int) {
var histogram = [(key: Box<rrggbb_t>, value: Box<Int>)]()
for _ in 1...100*N {
histogram = createSortedSparseRGBHistogramOfObjects(samples)

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_RangeAssignment(scale: Int) {
public func run_RangeAssignment(_ scale: Int) {
let range: Range = 100..<200
var vector = [Double](repeating: 0.0 , count: 5000)
let alfa = 1.0

View File

@@ -27,7 +27,7 @@ class ArrayWrapper {
data = [Int](repeating: initialValue, count: count)
}
func compare(b: ArrayWrapper, _ iteration: Int, _ stopIteration: Int) -> Bool {
func compare(_ b: ArrayWrapper, _ iteration: Int, _ stopIteration: Int) -> Bool {
// We will never return true here by design. We want to test the full effect
// every time of retaining, releasing.
if iteration == stopIteration || data[iteration] == b.data[iteration] {
@@ -39,7 +39,7 @@ class ArrayWrapper {
}
@inline(never)
public func run_RecursiveOwnedParameter(N: Int) {
public func run_RecursiveOwnedParameter(_ N: Int) {
let numElts = 1_000
let a = ArrayWrapper(numElts, 0)

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_SetIsSubsetOf(N: Int) {
public func run_SetIsSubsetOf(_ N: Int) {
let size = 200
SRand()
@@ -38,11 +38,11 @@ public func run_SetIsSubsetOf(N: Int) {
}
@inline(never)
func sink(s: inout Set<Int>) {
func sink(_ s: inout Set<Int>) {
}
@inline(never)
public func run_SetExclusiveOr(N: Int) {
public func run_SetExclusiveOr(_ N: Int) {
let size = 400
SRand()
@@ -63,7 +63,7 @@ public func run_SetExclusiveOr(N: Int) {
}
@inline(never)
public func run_SetUnion(N: Int) {
public func run_SetUnion(_ N: Int) {
let size = 400
SRand()
@@ -84,7 +84,7 @@ public func run_SetUnion(N: Int) {
}
@inline(never)
public func run_SetIntersect(N: Int) {
public func run_SetIntersect(_ N: Int) {
let size = 400
SRand()
@@ -124,7 +124,7 @@ func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
}
@inline(never)
public func run_SetIsSubsetOf_OfObjects(N: Int) {
public func run_SetIsSubsetOf_OfObjects(_ N: Int) {
let size = 200
SRand()
@@ -149,11 +149,11 @@ public func run_SetIsSubsetOf_OfObjects(N: Int) {
}
@inline(never)
func sink(s: inout Set<Box<Int>>) {
func sink(_ s: inout Set<Box<Int>>) {
}
@inline(never)
public func run_SetExclusiveOr_OfObjects(N: Int) {
public func run_SetExclusiveOr_OfObjects(_ N: Int) {
let size = 400
SRand()
@@ -174,7 +174,7 @@ public func run_SetExclusiveOr_OfObjects(N: Int) {
}
@inline(never)
public func run_SetUnion_OfObjects(N: Int) {
public func run_SetUnion_OfObjects(_ N: Int) {
let size = 400
SRand()
@@ -195,7 +195,7 @@ public func run_SetUnion_OfObjects(N: Int) {
}
@inline(never)
public func run_SetIntersect_OfObjects(N: Int) {
public func run_SetIntersect_OfObjects(_ N: Int) {
let size = 400
SRand()

View File

@@ -14,14 +14,14 @@ import TestsUtils
import Foundation
@inline(never)
func filter_seven(input : Int) throws {
func filter_seven(_ input : Int) throws {
guard case 7 = input else {
throw NSError(domain: "AnDomain", code: 42, userInfo: nil)
}
}
@inline(never)
public func run_SevenBoom(N: Int) {
public func run_SevenBoom(_ N: Int) {
var c = 0
for i in 1...N*5000 {
do {

View File

@@ -23,7 +23,7 @@ struct Array2D {
}
@inline(never)
func workload_2DArrayTest(A: inout Array2D) {
func workload_2DArrayTest(_ A: inout Array2D) {
for _ in 0 ..< 10 {
for r in 0 ..< A.rows {
for c in 0 ..< A.cols {
@@ -34,7 +34,7 @@ func workload_2DArrayTest(A: inout Array2D) {
}
@inline(never)
public func run_Sim2DArray(N : Int) {
public func run_Sim2DArray(_ N: Int) {
for _ in 0 ..< N {
var A = Array2D(numRows:2048, numCols:32)
workload_2DArrayTest(&A)

View File

@@ -23,7 +23,7 @@ class Letter {
}
@inline(never)
public func run_SortLettersInPlace(N: Int) {
public func run_SortLettersInPlace(_ N: Int) {
for _ in 1...100*N {
var letters = [
Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"),

View File

@@ -1017,14 +1017,14 @@ var stringBenchmarkWords: [String] = [
@inline(never)
func benchSortStrings(words: [String]) {
func benchSortStrings(_ words: [String]) {
// Notice that we _copy_ the array of words before we sort it.
// Pass an explicit '<' predicate to benchmark reabstraction thunks.
var tempwords = words
tempwords.sort(isOrderedBefore: <)
}
public func run_SortStrings(N: Int) {
public func run_SortStrings(_ N: Int) {
for _ in 1...5*N {
benchSortStrings(stringBenchmarkWords)
}

View File

@@ -19,16 +19,16 @@ import TestsUtils
protocol StaticArrayProtocol {
associatedtype ElemTy
init(_ defaultValue : ElemTy)
func get(idx : Int) -> ElemTy
mutating func set(idx : Int,_ val : ElemTy)
func get(_ idx : Int) -> ElemTy
mutating func set(_ idx : Int,_ val : ElemTy)
func count() -> Int
}
struct A0<ElemTy> : StaticArrayProtocol {
init(_ defaultValue : ElemTy) { x = defaultValue }
var x : ElemTy
func get(idx : Int) -> ElemTy { if idx == 0 { return x } else { fatalError("oob"); } }
mutating func set(idx : Int,_ val : ElemTy) { if idx == 0 { x = val }}
func get(_ idx : Int) -> ElemTy { if idx == 0 { return x } else { fatalError("oob"); } }
mutating func set(_ idx : Int,_ val : ElemTy) { if idx == 0 { x = val }}
func count() -> Int { return 1}
}
@@ -36,8 +36,8 @@ struct A2X<T : StaticArrayProtocol> : StaticArrayProtocol {
init(_ defaultValue : T.ElemTy) { lower = T(defaultValue); upper = T(defaultValue) }
var lower : T
var upper : T
func get(idx : Int) -> T.ElemTy { let size = lower.count(); if idx < size { return lower.get(idx) } else { return upper.get(idx - size) }}
mutating func set(idx : Int,_ val : T.ElemTy) {let size = lower.count(); if idx < size { return lower.set(idx, val) } else { return upper.set(idx - size, val) }}
func get(_ idx: Int) -> T.ElemTy { let size = lower.count(); if idx < size { return lower.get(idx) } else { return upper.get(idx - size) }}
mutating func set(_ idx: Int,_ val : T.ElemTy) {let size = lower.count(); if idx < size { return lower.set(idx, val) } else { return upper.set(idx - size, val) }}
func count() -> Int { return upper.count() + lower.count() }
}
@@ -46,8 +46,8 @@ struct StaticArray<
> : StaticArrayProtocol, RandomAccessCollection, MutableCollection {
init(_ defaultValue : T.ElemTy) { values = T(defaultValue) }
var values : T
func get(idx : Int) -> T.ElemTy { return values.get(idx) }
mutating func set(idx : Int,_ val : T.ElemTy) { return values.set(idx, val) }
func get(_ idx: Int) -> T.ElemTy { return values.get(idx) }
mutating func set(_ idx: Int,_ val : T.ElemTy) { return values.set(idx, val) }
func count() -> Int { return values.count() }
typealias Index = Int
@@ -81,11 +81,11 @@ typealias SA128Int = StaticArray<A2X<A2X<A2X<A2X<A2X<A2X<A0<Int>>>>>>>>
// Make sure the optimizer does not optimize the compute away.
@inline(never)
public func sink(value: Int) { if False() { print(value) }}
public func sink(_ value: Int) { if False() { print(value) }}
@inline(never)
public func run_StaticArray(N: Int) {
public func run_StaticArray(_ N: Int) {
for _ in 1...N {
var staticArray = SA128Int(0)

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_StrComplexWalk(N: Int) {
public func run_StrComplexWalk(_ N: Int) {
var s = "निरन्तरान्धकारिता-दिगन्तर-कन्दलदमन्द-सुधारस-बिन्दु-सान्द्रतर-घनाघन-वृन्द-सन्देहकर-स्यन्दमान-मकरन्द-बिन्दु-बन्धुरतर-माकन्द-तरु-कुल-तल्प-कल्प-मृदुल-सिकता-जाल-जटिल-मूल-तल-मरुवक-मिलदलघु-लघु-लय-कलित-रमणीय-पानीय-शालिका-बालिका-करार-विन्द-गलन्तिका-गलदेला-लवङ्ग-पाटल-घनसार-कस्तूरिकातिसौरभ-मेदुर-लघुतर-मधुर-शीतलतर-सलिलधारा-निराकरिष्णु-तदीय-विमल-विलोचन-मयूख-रेखापसारित-पिपासायास-पथिक-लोकान्"
let ref_result = 379
for _ in 1...2000*N {

View File

@@ -15,7 +15,7 @@
import TestsUtils
@inline(never)
public func run_StrToInt(N: Int) {
public func run_StrToInt(_ N: Int) {
// 64 numbers from -500_000 to 500_000 generated randomly
let input = ["-237392", "293715", "126809", "333779", "-362824", "144198",
"-394973", "-163669", "-7236", "376965", "-400783", "-118670",
@@ -29,7 +29,7 @@ public func run_StrToInt(N: Int) {
"-316727", "483808", "300149", "-405877", "-98938", "283685",
"-247856", "-46975", "346060", "160085",]
let ref_result = 517492
func DoOneIter(arr: [String]) -> Int {
func DoOneIter(_ arr: [String]) -> Int {
var r = 0
for n in arr {
r += Int(n)!

View File

@@ -22,7 +22,7 @@ func buildString() -> String {
}
@inline(never)
public func run_StringBuilder(N: Int) {
public func run_StringBuilder(_ N: Int) {
for _ in 1...5000*N {
buildString()
}

View File

@@ -19,7 +19,7 @@ class RefTypePrintable : CustomStringConvertible {
}
@inline(never)
public func run_StringInterpolation(N: Int) {
public func run_StringInterpolation(_ N: Int) {
let reps = 100
let refResult = reps
let anInt: Int64 = 0x1234567812345678

View File

@@ -10,7 +10,7 @@
//
//===----------------------------------------------------------------------===//
public func run_StringWithCString(N: Int) {
public func run_StringWithCString(_ N: Int) {
let str = String(repeating: "x" as UnicodeScalar, count: 100 * (1 << 16))
for _ in 0 ..< N {
str.withCString { _ in }

View File

@@ -22,14 +22,14 @@ import TestsUtils
var count: Int = 0
@inline(never) func countChars(s: String) {
@inline(never) func countChars(_ s: String) {
for _ in s.unicodeScalars {
count += 1
}
}
@inline(never)
public func run_StringWalk(N: Int) {
public func run_StringWalk(_ N: Int) {
let s = "siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig"
for _ in 1...50000*N {

View File

@@ -14,7 +14,7 @@
import TestsUtils
@inline(never)
public func run_SuperChars(N: Int) {
public func run_SuperChars(_ N: Int) {
// Permute some characters.
let alphabet: [Character] = [
"A", "B", "C", "D", "E", "F", "G",

View File

@@ -52,7 +52,7 @@ let array = [
]
@inline(never)
public func run_TwoSum(N: Int) {
public func run_TwoSum(_ N: Int) {
var i1: Int?
var i2: Int?
var Dict: Dictionary<Int, Int> = [:]

View File

@@ -27,15 +27,15 @@ protocol Pingable {}
struct Some1<T> {
init() {}
func foo(x: T) {}
func foo(_ x: T) {}
}
struct Some0<T> {
init() {}
func foo(x: T) {}
func foo(_ x: T) {}
}
@inline(never)
func flood<T>(x : T) {
func flood<T>(_ x: T) {
Some1<Some1<Some1<Some1<T>>>>() is Pingable
Some1<Some1<Some1<Some0<T>>>>() is Pingable
Some1<Some1<Some0<Some1<T>>>>() is Pingable
@@ -55,7 +55,7 @@ func flood<T>(x : T) {
}
@inline(never)
func flood3<T>(x : T) {
func flood3<T>(_ x: T) {
flood(Some1<Some1<Some1<Some1<T>>>>())
flood(Some1<Some1<Some1<Some0<T>>>>())
flood(Some1<Some1<Some0<Some1<T>>>>())
@@ -75,7 +75,7 @@ func flood3<T>(x : T) {
}
@inline(never)
func flood2<T>(x : T) {
func flood2<T>(_ x: T) {
flood3(Some1<Some1<Some1<Some1<T>>>>())
flood3(Some1<Some1<Some1<Some0<T>>>>())
flood3(Some1<Some1<Some0<Some1<T>>>>())
@@ -95,7 +95,7 @@ func flood2<T>(x : T) {
}
@inline(never)
public func run_TypeFlood(N: Int) {
public func run_TypeFlood(_ N: Int) {
for _ in 1...N {
flood3(Some1<Some1<Some1<Int>>>())

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_UTF8Decode(N: Int) {
public func run_UTF8Decode(_ N: Int) {
// 1-byte sequences
// This test case is the longest as it's the most performance sensitive.
let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."
@@ -27,7 +27,7 @@ public func run_UTF8Decode(N: Int) {
let strings = [ ascii, russian, japanese, emoji ].map { Array($0.utf8) }
func isEmpty(result: UnicodeDecodingResult) -> Bool {
func isEmpty(_ result: UnicodeDecodingResult) -> Bool {
switch result {
case .emptyInput:
return true

View File

@@ -13,10 +13,10 @@
import TestsUtils
import Darwin
func IsPowerOfTwo(x: Int) -> Bool { return (x & (x - 1)) == 0 }
func IsPowerOfTwo(_ x: Int) -> Bool { return (x & (x - 1)) == 0 }
//Fast Walsh Hadamard Transform
func WalshTransform(data: inout [Double]) {
func WalshTransform(_ data: inout [Double]) {
assert(IsPowerOfTwo(data.count), "Not a power of two")
var temp = [Double](repeating: 0, count: data.count)
var ret = WalshImpl(&data, &temp, 0, data.count)
@@ -25,18 +25,18 @@ func WalshTransform(data: inout [Double]) {
}
}
func Scale(data: inout [Double], _ scalar : Double) {
func Scale(_ data: inout [Double], _ scalar : Double) {
for i in 0..<data.count {
data[i] = data[i] * scalar
}
}
func InverseWalshTransform(data: inout [Double]) {
func InverseWalshTransform(_ data: inout [Double]) {
WalshTransform(&data)
Scale(&data, Double(1)/Double(data.count))
}
func WalshImpl(data: inout [Double], _ temp: inout [Double], _ start: Int, _ size: Int) -> [Double] {
func WalshImpl(_ data: inout [Double], _ temp: inout [Double], _ start: Int, _ size: Int) -> [Double] {
if (size == 1) { return data }
let stride = size/2
@@ -65,7 +65,7 @@ func checkCorrectness() {
}
@inline(never)
public func run_Walsh(N : Int) {
public func run_Walsh(_ N: Int) {
checkCorrectness()
// Generate data.

View File

@@ -13,7 +13,7 @@
import TestsUtils
@inline(never)
public func run_XorLoop(N: Int) {
public func run_XorLoop(_ N: Int) {
for _ in 1...5*N {
let size = 100000
let ref_result = 47813324

View File

@@ -14,12 +14,12 @@ import TestsUtils
import Foundation
@inline(never)
public func forcedCast<NS, T>(ns: NS) -> T {
public func forcedCast<NS, T>(_ ns: NS) -> T {
return ns as! T
}
@inline(never)
public func conditionalCast<NS, T>(ns: NS) -> T? {
public func conditionalCast<NS, T>(_ ns: NS) -> T? {
return ns as? T
}
@@ -46,7 +46,7 @@ func testObjectiveCBridgeFromNSString() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSString(N: Int) {
public func run_ObjectiveCBridgeFromNSString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSString()
}
@@ -65,7 +65,7 @@ func testObjectiveCBridgeFromNSStringForced() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSStringForced(N: Int) {
public func run_ObjectiveCBridgeFromNSStringForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSStringForced()
}
@@ -84,7 +84,7 @@ func testObjectiveCBridgeToNSString() {
}
@inline(never)
public func run_ObjectiveCBridgeToNSString(N: Int) {
public func run_ObjectiveCBridgeToNSString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeToNSString()
}
@@ -123,7 +123,7 @@ func testObjectiveCBridgeFromNSArrayAnyObject() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObject(N: Int) {
public func run_ObjectiveCBridgeFromNSArrayAnyObject(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSArrayAnyObject()
}
@@ -142,7 +142,7 @@ func testObjectiveCBridgeFromNSArrayAnyObjectForced() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObjectForced(N: Int) {
public func run_ObjectiveCBridgeFromNSArrayAnyObjectForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSArrayAnyObjectForced()
}
@@ -162,7 +162,7 @@ func testObjectiveCBridgeToNSArray() {
}
@inline(never)
public func run_ObjectiveCBridgeToNSArray(N: Int) {
public func run_ObjectiveCBridgeToNSArray(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeToNSArray()
}
@@ -182,7 +182,7 @@ func testObjectiveCBridgeFromNSArrayAnyObjectToString() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObjectToString(N: Int) {
public func run_ObjectiveCBridgeFromNSArrayAnyObjectToString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSArrayAnyObjectToString()
}
@@ -201,7 +201,7 @@ func testObjectiveCBridgeFromNSArrayAnyObjectToStringForced() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced(N: Int) {
public func run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSArrayAnyObjectToStringForced()
}
@@ -250,7 +250,7 @@ func testObjectiveCBridgeFromNSDictionaryAnyObject() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObject(N: Int) {
public func run_ObjectiveCBridgeFromNSDictionaryAnyObject(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSDictionaryAnyObject()
}
@@ -271,7 +271,7 @@ func testObjectiveCBridgeFromNSDictionaryAnyObjectForced() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced(N: Int) {
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSDictionaryAnyObjectForced()
}
@@ -292,7 +292,7 @@ func testObjectiveCBridgeToNSDictionary() {
}
@inline(never)
public func run_ObjectiveCBridgeToNSDictionary(N: Int) {
public func run_ObjectiveCBridgeToNSDictionary(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeToNSDictionary()
}
@@ -314,7 +314,7 @@ func testObjectiveCBridgeFromNSDictionaryAnyObjectToString() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString(N: Int) {
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSDictionaryAnyObjectToString()
}
@@ -336,7 +336,7 @@ func testObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced(N: Int) {
public func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced()
}
@@ -386,7 +386,7 @@ func testObjectiveCBridgeFromNSSetAnyObject() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObject(N: Int) {
public func run_ObjectiveCBridgeFromNSSetAnyObject(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSSetAnyObject()
}
@@ -407,7 +407,7 @@ func testObjectiveCBridgeFromNSSetAnyObjectForced() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObjectForced(N: Int) {
public func run_ObjectiveCBridgeFromNSSetAnyObjectForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSSetAnyObjectForced()
}
@@ -428,7 +428,7 @@ func testObjectiveCBridgeToNSSet() {
}
@inline(never)
public func run_ObjectiveCBridgeToNSSet(N: Int) {
public func run_ObjectiveCBridgeToNSSet(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeToNSSet()
}
@@ -450,7 +450,7 @@ func testObjectiveCBridgeFromNSSetAnyObjectToString() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObjectToString(N: Int) {
public func run_ObjectiveCBridgeFromNSSetAnyObjectToString(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSSetAnyObjectToString()
}
@@ -472,7 +472,7 @@ func testObjectiveCBridgeFromNSSetAnyObjectToStringForced() {
}
@inline(never)
public func run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced(N: Int) {
public func run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced(_ N: Int) {
for _ in 0 ..< N {
testObjectiveCBridgeFromNSSetAnyObjectToStringForced()
}

View File

@@ -25,7 +25,7 @@ func testObjectiveCBridgeStubFromNSString() {
}
@inline(never)
public func run_ObjectiveCBridgeStubFromNSString(N: Int) {
public func run_ObjectiveCBridgeStubFromNSString(_ N: Int) {
autoreleasepool {
for _ in 0 ..< N {
testObjectiveCBridgeStubFromNSString()
@@ -44,7 +44,7 @@ func testObjectiveCBridgeStubToNSString() {
}
@inline(never)
public func run_ObjectiveCBridgeStubToNSString(N: Int) {
public func run_ObjectiveCBridgeStubToNSString(_ N: Int) {
autoreleasepool {
for _ in 0 ..< N {
testObjectiveCBridgeStubToNSString()
@@ -64,7 +64,7 @@ func testObjectiveCBridgeStubFromArrayOfNSString() {
}
@inline(never)
public func run_ObjectiveCBridgeStubFromArrayOfNSString(N: Int) {
public func run_ObjectiveCBridgeStubFromArrayOfNSString(_ N: Int) {
autoreleasepool {
for _ in 0 ..< N {
testObjectiveCBridgeStubFromArrayOfNSString()
@@ -83,7 +83,7 @@ func testObjectiveCBridgeStubToArrayOfNSString() {
}
@inline(never)
public func run_ObjectiveCBridgeStubToArrayOfNSString(N: Int) {
public func run_ObjectiveCBridgeStubToArrayOfNSString(_ N: Int) {
autoreleasepool {
for _ in 0 ..< N {
testObjectiveCBridgeStubToArrayOfNSString()

View File

@@ -3,7 +3,7 @@ protocol Proto {
}
@inline(never)
func testStackAllocation(p: Proto) -> Int {
func testStackAllocation(_ p: Proto) -> Int {
var a = [p, p, p]
var b = 0
a.withUnsafeMutableBufferPointer {
@@ -23,7 +23,7 @@ class Foo : Proto {
}
@inline(never)
func work(f: Foo) -> Int {
func work(_ f: Foo) -> Int {
var r = 0
for _ in 0..<100_000 {
r += testStackAllocation(f)
@@ -32,13 +32,13 @@ func work(f: Foo) -> Int {
}
@inline(never)
func hole(use: Int, _ N: Int) {
func hole(_ use: Int, _ N: Int) {
if (N == 0) {
print("use: \(use)")
}
}
public func run_StackPromo(N: Int) {
public func run_StackPromo(_ N: Int) {
let foo = Foo()
var r = 0
for i in 0..<N {

View File

@@ -35,7 +35,7 @@ public struct Arguments {
///
/// with opt-name and opt-value not containing any '=' signs. Any
/// other option passed in is assumed to be a positional argument.
public func parseArgs(validOptions: [String]? = nil)
public func parseArgs(_ validOptions: [String]? = nil)
-> Arguments? {
let progName = Process.arguments[0]
var positionalArgs = [String]()

View File

@@ -182,7 +182,7 @@ struct TestConfig {
}
}
func internalMeanSD(inputs: [UInt64]) -> (UInt64, UInt64) {
func internalMeanSD(_ inputs: [UInt64]) -> (UInt64, UInt64) {
// If we are empty, return 0, 0.
if inputs.isEmpty {
return (0, 0)
@@ -211,7 +211,7 @@ func internalMeanSD(inputs: [UInt64]) -> (UInt64, UInt64) {
return (mean, UInt64(sqrt(Double(sum2)/(Double(inputs.count) - 1))))
}
func internalMedian(inputs: [UInt64]) -> UInt64 {
func internalMedian(_ inputs: [UInt64]) -> UInt64 {
return inputs.sorted()[inputs.count / 2]
}
@@ -229,7 +229,7 @@ class SampleRunner {
init() {
mach_timebase_info(&info)
}
func run(name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 {
func run(_ name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 {
// Start the timer.
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
var str = name
@@ -250,7 +250,7 @@ class SampleRunner {
}
/// Invoke the benchmark entry point and return the run time in milliseconds.
func runBench(name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResults {
func runBench(_ name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResults {
var samples = [UInt64](repeating: 0, count: c.numSamples)
@@ -296,7 +296,7 @@ func runBench(name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResult
mean: mean, sd: sd, median: internalMedian(samples))
}
func printRunInfo(c: TestConfig) {
func printRunInfo(_ c: TestConfig) {
if c.verbose {
print("--- CONFIG ---")
print("NumSamples: \(c.numSamples)")
@@ -318,7 +318,7 @@ func printRunInfo(c: TestConfig) {
}
}
func runBenchmarks(c: TestConfig) {
func runBenchmarks(_ c: TestConfig) {
let units = "us"
print("#\(c.delim)TEST\(c.delim)SAMPLES\(c.delim)MIN(\(units))\(c.delim)MAX(\(units))\(c.delim)MEAN(\(units))\(c.delim)SD(\(units))\(c.delim)MEDIAN(\(units))")
var SumBenchResults = BenchResults()

View File

@@ -45,7 +45,7 @@ public func Random() -> Int64 {
return lfsrRandomGenerator.randInt()
}
public func CheckResults(res: Bool, _ message: String = "") {
public func CheckResults(_ res: Bool, _ message: String = "") {
if res {
return
}

View File

@@ -87,7 +87,7 @@ Variables, functions and typealiases should have names that start with an
underscore::
var _value: Int
func _bridgeSomethingToAnything(something: AnyObject) -> AnyObject
func _bridgeSomethingToAnything(_ something: AnyObject) -> AnyObject
typealias _InternalTypealias = HeapBuffer<Int, Int>
To apply the rule to an initializer, one of its label arguments *or*

View File

@@ -18,7 +18,7 @@ translation of the type of that function will be correctly callable
from C. For example, this wouldn't be guaranteed to work::
// In Swift:
func foo(x: Int, y: Double) -> MyClass { ... }
func foo(_ x: Int, y: Double) -> MyClass { ... }
// In Objective-C:
extern id _TF4main3fooFTSiSd_CS_7MyClass(intptr_t x, double y);
@@ -596,7 +596,7 @@ indirectly.
All of these cases except mutating instance methods on value types can
be partially applied to create a function closure whose type is the
formal type of the method. That is, if class `A` has a method
declared `func foo(x: Int) -> Double`, then `A.foo` yields a function
declared `func foo(_ x: Int) -> Double`, then `A.foo` yields a function
of type `(Int) -> Double`. Assuming that we continue to feel that
this is a useful language feature, it's worth considered how we could
support it efficiently. The expenses associated with a partial
@@ -641,13 +641,13 @@ extra return values. Considerations:
// foo() expects its argument to follow the conventions of a
// function that's capable of throwing.
func foo(fn: () throws -> ()) throwsIf(fn)
func foo(_ fn: () throws -> ()) throwsIf(fn)
// Here we're passing foo() a function that can't throw; this is
// allowed by the subtyping rules of the language. We'd like to be
// able to do this without having to introduce a thunk that maps
// between the conventions.
func bar(fn: () -> ()) {
func bar(_ fn: () -> ()) {
foo(fn)
}

View File

@@ -148,7 +148,7 @@ grammar for function types and implicit ``()`` result types, e.g.::
// Takes a 'callback' function that can throw.
// 'fred' itself can also throw.
func fred(callback: (UInt8) throws -> ()) throws {
func fred(_ callback: (UInt8) throws -> ()) throws {
// These are distinct types.
let a : () -> () -> ()
@@ -159,7 +159,7 @@ grammar for function types and implicit ``()`` result types, e.g.::
For curried functions, ``throws`` only applies to the innermost
function. This function has type ``(Int) -> (Int) throws -> Int``::
func jerry(i: Int)(j: Int) throws -> Int {
func jerry(_ i: Int)(j: Int) throws -> Int {
``throws`` is tracked as part of the type system: a function value
must also declare whether it can throw. Functions that cannot throw
@@ -167,7 +167,7 @@ are a subtype of functions that can, so you can use a function that
can't throw anywhere you could use a function that can::
func rachel() -> Int { return 12 }
func donna(generator: () throws -> Int) -> Int { ... }
func donna(_ generator: () throws -> Int) -> Int { ... }
donna(rachel)
@@ -190,8 +190,8 @@ override a throwing method or satisfy a throwing protocol requirement.
It is valuable to be able to overload higher-order functions based on
whether an argument function throws, so this is allowed::
func foo(callback: () throws -> Bool) {
func foo(callback: () -> Bool) {
func foo(_ callback: () throws -> Bool) {
func foo(_ callback: () -> Bool) {
``rethrows``
~~~~~~~~~~~~
@@ -200,7 +200,7 @@ Functions which take a throwing function argument (including as an
autoclosure) can be marked as ``rethrows``::
extension Array {
func map<U>(fn: ElementType throws -> U) rethrows -> [U]
func map<U>(_ fn: ElementType throws -> U) rethrows -> [U]
}
It is an error if a function declared ``rethrows`` does not include a
@@ -507,7 +507,7 @@ like this one from ``NSAttributedString``::
would be imported as::
func dataFromRange(range: NSRange,
func dataFromRange(_ range: NSRange,
documentAttributes dict: NSDictionary) throws -> NSData
There are a number of cases to consider, but we expect that most can
@@ -637,7 +637,7 @@ can be done in a fairly simple way: a function can declare that it
throws if any of a set of named arguments do. As an example (using
strawman syntax)::
func map<T,U>(array: [T], fn: T -> U) throwsIf(fn) -> [U] {
func map<T,U>(_ array: [T], fn: T -> U) throwsIf(fn) -> [U] {
...
}

View File

@@ -1370,7 +1370,7 @@ declaration or type::
}
// 'throws' appears in a consistent position in function types.
func fred(callback: (UInt8) throws -> ()) throws {
func fred(_ callback: (UInt8) throws -> ()) throws {
while true {
let code = try stream.readByte()
if code == OPER_CLOSE { return }
@@ -1381,7 +1381,7 @@ declaration or type::
// It only applies to the innermost function for curried functions;
// this function has type:
// (Int) -> (Int) throws -> Int
func jerry(i: Int)(j: Int) throws -> Int {
func jerry(_ i: Int)(j: Int) throws -> Int {
// It's not an error to use 'throws' on a function that can't throw.
return i + j
}
@@ -1458,7 +1458,7 @@ done in a fairly simple way: a function can declare that it throws if
any of a set of named arguments do. As an example (using strawman
syntax)::
func map<T,U>(array: [T], fn: T throws -> U) throwsIf(fn) -> [U] {
func map<T,U>(_ array: [T], fn: T throws -> U) throwsIf(fn) -> [U] {
...
}
@@ -1908,7 +1908,7 @@ this one from ``NSAttributedString``::
would be imported as::
func dataFromRange(range: NSRange,
func dataFromRange(_ range: NSRange,
documentAttributes dict: NSDictionary) throws -> NSData
However, applying this rule haphazardly causes problems for

View File

@@ -156,7 +156,7 @@ Multiple inheritance is permitted, allowing us to form a directed acyclic graph
of protocols::
protocol PersistentDocument : VersionedDocument, Serializable {
func saveToFile(filename : path)
func saveToFile(_ filename : path)
}
.. @example.prepend('struct path {} ; protocol Serializable {}')
@@ -173,7 +173,7 @@ operations. For example, let's try to write a Comparable protocol that could be
used to search for a generic find() operation::
protocol Comparable {
func isEqual(other : ???) -> Bool
func isEqual(_ other : ???) -> Bool
}
Our options for filling in ??? are currently very poor. We could use the syntax
@@ -216,7 +216,7 @@ allows one to refer to the eventual type of 'self' (which we call
Comparable protocol in a natural way::
protocol Comparable {
func isEqual(other : Self) -> Bool
func isEqual(_ other : Self) -> Bool
}
By expressing Comparable in this way, we know that if we have two objects of
@@ -242,8 +242,8 @@ us to cleanly describe a protocol for collections::
protocol Collection {
typealias Element
func forEach(callback : (value : Element) -> Void)
func add(value : Element)
func forEach(_ callback : (value : Element) -> Void)
func add(_ value : Element)
}
It is important here that a generic function that refers to a given type T,
@@ -330,8 +330,8 @@ type::
struct EmployeeList : Collection { // EmployeeList is a collection
typealias Element = T
func forEach(callback : (value : Element) -> Void) { /* Implement this */ }
func add(value : Element) { /* Implement this */ }
func forEach(_ callback : (value : Element) -> Void) { /* Implement this */ }
func add(_ value : Element) { /* Implement this */ }
}
This explicit protocol conformance declaration forces the compiler to check that
@@ -367,8 +367,8 @@ extensions, e.g.,::
extension String : Collection {
typealias Element = char
func forEach(callback : (value : Element) -> Void) { /* use existing String routines to enumerate characters */ }
func add(value : Element) { self += value /* append character */ }
func forEach(_ callback : (value : Element) -> Void) { /* use existing String routines to enumerate characters */ }
func add(_ value : Element) { self += value /* append character */ }
}
Once an extension is defined, the extension now conforms to the Collection
@@ -525,7 +525,7 @@ in Swift. For example, one could define a generic linked list as::
This list works on any type T. One could then add a generic function that
inserts at the beginning of the list::
func insertAtBeginning<T>(list : List<T>, value : T) {
func insertAtBeginning<T>(_ list : List<T>, value : T) {
list.First = ListNode<T>(value, list.First)
}
@@ -539,7 +539,7 @@ conform. Within the body of the generic type or function, any of the functions
or types described by the constraints are available. For example, let's
implement a find() operation on lists::
func find<T : Comparable>(list : List<T>, value : T) -> Int {
func find<T : Comparable>(_ list : List<T>, value : T) -> Int {
var index = 0
var current
for (current = list.First; current is Node; current = current.Next) {
@@ -559,11 +559,11 @@ ordered collection::
protocol OrderedCollection : Collection {
func size() -> Int
func getAt(index : Int) -> Element // Element is an associated type
func getAt(_ index : Int) -> Element // Element is an associated type
}
func find<C : OrderedCollection where C.Element : Comparable>(
collection : C, value : C.Element) -> Int
_ collection : C, value : C.Element) -> Int
{
for index in 0...collection.size() {
if (collection.getAt(index) == value) { // okay: we know that C.Element is Comparable
@@ -579,7 +579,7 @@ OrderedCollection>) are just sugar for a where clause. For example, the
above find() signature is equivalent to::
func find<C where C : OrderedCollection, C.Element : Comparable>(
collection : C, value : C.Element) -> Int
_ collection : C, value : C.Element) -> Int
Note that find<C> is shorthand for (and equivalent to) find<C : Any>, since
every type conforms to the Any protocol composition.
@@ -626,7 +626,7 @@ Comparable::
Naturally, one any generic operation on a SortedDictionary<K,V> would also require
that K be Comparable, e.g.,::
func forEachKey<Key : Comparable, Value>(c : SortedDictionary<Key, Value>,
func forEachKey<Key : Comparable, Value>(_ c : SortedDictionary<Key, Value>,
f : (Key) -> Void) { /* ... */ }
However, explicitly requiring that Key conform to Comparable is redundant: one
@@ -636,7 +636,7 @@ itself could not be formed. Constraint inference infers these additional
constraints within a generic function from the parameter and return types of the
function, simplifying the specification of forEachKey::
func forEachKey<Key, Value>(c : SortedDictionary<Key, Value>,
func forEachKey<Key, Value>(_ c : SortedDictionary<Key, Value>,
f : (Key) -> Void) { /* ... */ }
Type Parameter Deduction
@@ -651,7 +651,7 @@ generic function::
Since Swift already has top-down type inference (as well as the C++-like
bottom-up inference), we can also deduce type arguments from the result type::
func cast<T, U>(value : T) -> U { ... }
func cast<T, U>(_ value : T) -> U { ... }
var x : Any
var y : Int = cast(x) // deduces T = Any, U = Int
@@ -680,7 +680,7 @@ language (generic functions can be "virtual").
The translation model is fairly simple. Consider the generic find() we
implemented for lists, above::
func find<T : Comparable>(list : List<T>, value : T) -> Int {
func find<T : Comparable>(_ list : List<T>, value : T) -> Int {
var index = 0
var current = list.First
while current is ListNode<T> { // now I'm just making stuff up
@@ -724,7 +724,7 @@ type parameters.::
struct S<T> {
var x: T
@_specialize(Int, Float)
mutating func exchangeSecond<U>(u: U, _ t: T) -> (U, T) {
mutating func exchangeSecond<U>(_ u: U, _ t: T) -> (U, T) {
x = t
return (u, x)
}
@@ -772,7 +772,7 @@ consider a binary search algorithm::
func binarySearch<
C : EnumerableCollection where C.Element : Comparable
>(collection : C, value : C.Element)
>(_ collection : C, value : C.Element)
-> C.EnumeratorType
{
// We can perform log(N) comparisons, but EnumerableCollection
@@ -788,7 +788,7 @@ consider a binary search algorithm::
C : EnumerableCollection
where C.Element : Comparable,
C.EnumeratorType: RandomAccessEnumerator
>(collection : C, value : C.Element)
>(_ collection : C, value : C.Element)
-> C.EnumeratorType
{
// We can perform log(N) comparisons and log(N) range splits,
@@ -808,7 +808,7 @@ minimal requirements::
func doSomethingWithSearch<
C : EnumerableCollection where C.Element : Ordered
>(
collection : C, value : C.Element
_ collection : C, value : C.Element
) -> C.EnumeratorType
{
binarySearch(collection, value)

View File

@@ -85,11 +85,11 @@ getElement instruction::
return getElement(index)
}
@_semantics("array.check_subscript") func checkSubscript(index: Int) {
@_semantics("array.check_subscript") func checkSubscript(_ index: Int) {
...
}
@_semantics("array.get_element") func getElement(index: Int) -> Element {
@_semantics("array.get_element") func getElement(_ index: Int) -> Element {
return _buffer[index]
}

View File

@@ -355,7 +355,7 @@ example using methods::
}
extension Point2D {
@inlineable public func distanceTo(other: Point2D) -> Double {
@inlineable public func distanceTo(_ other: Point2D) -> Double {
let deltaX = self.x - other.x
let deltaY = self.y - other.y
return sqrt(deltaX*deltaX + deltaY*deltaY)
@@ -1618,7 +1618,7 @@ Recompiling changes a protocol's implementation
// Library, version 1
protocol MagicType {}
protocol Wearable {}
func use<T: MagicType>(item: T) {}
func use<T: MagicType>(_ item: T) {}
::
@@ -1639,7 +1639,7 @@ Recompiling changes a protocol's implementation
func equip() { print("You put it on.") }
}
func use<T: MagicType>(item: T) { item.equip() }
func use<T: MagicType>(_ item: T) { item.equip() }
Before the client is recompiled, the implementation of ``equip()`` used for
``Amulet`` instances can only be the default implementation, i.e. the one that

View File

@@ -55,7 +55,7 @@ Once a module has been imported, its declarations are available for use within
the current source file. These declarations can be referred to by name, or
by `qualifying <qualified name>` them with the name of the module::
func playChess(blackPlayer : Chess.Player, whitePlayer : Chess.Player) {
func playChess(_ blackPlayer : Chess.Player, whitePlayer : Chess.Player) {
var board = Board() // refers to Chess.Board
}

View File

@@ -252,7 +252,7 @@ unless the method is attributed with ``mutating``:
.. parsed-literal::
func f(x: Int, y: inout Int) {
func f(_ x: Int, y: inout Int) {
y = x // ok, y is an inout parameter
x = y // **Error:** function parameter 'x' is immutable
}

View File

@@ -345,7 +345,7 @@ performed at runtime, with the actual subclass being determined via
some external file that describes the user interface. The actual
instantiation of the object would use a type value::
func createView(viewClass: View.Type, frame: Rect) -> View {
func createView(_ viewClass: View.Type, frame: Rect) -> View {
return viewClass(frame: frame) // error: 'init frame:' is not 'required'
}
@@ -361,7 +361,7 @@ particular initializer, use the ``required`` attribute as follows::
}
}
func createView(viewClass: View.Type, frame: Rect) -> View {
func createView(_ viewClass: View.Type, frame: Rect) -> View {
return viewClass(frame: frame) // okay
}
@@ -413,7 +413,7 @@ declaring conformance to the protocol will also have the initializer,
so they too will conform to the protocol. This allows one to construct
objects given type values of protocol type::
func createAnyDefInit(typeVal: DefaultInitializable.Type) -> DefaultInitializable {
func createAnyDefInit(_ typeVal: DefaultInitializable.Type) -> DefaultInitializable {
return typeVal()
}
@@ -456,7 +456,7 @@ return an object with the same dynamic type as ``self``. One of the
primary uses of the ``Self`` return type is for factory methods::
extension View {
class func createView(frame: Rect) -> Self {
class func createView(_ frame: Rect) -> Self {
return self(frame: frame)
}
}
@@ -482,12 +482,12 @@ allow chaining of method calls by returning ``Self`` from each method,
as in the builder pattern::
class DialogBuilder {
func setTitle(title: String) -> Self {
func setTitle(_ title: String) -> Self {
// set the title
return self;
}
func setBounds(frame: Rect) -> Self {
func setBounds(_ frame: Rect) -> Self {
// set the bounds
return self;
}

View File

@@ -89,7 +89,7 @@ in the following code snippet, ``a.aProperty``, ``a.doSomething()`` and
override func doSomething() { ... }
}
func usingAnA(a: A) {
func usingAnA(_ a: A) {
a.doSomething()
a.aProperty = ...
}
@@ -124,12 +124,12 @@ in the following ``C.array1`` and ``D.array1`` will be accessed directly
var array2: [Int] // 'array2' *can* be overridden by a computed property.
}
func usingC(c: C) {
func usingC(_ c: C) {
c.array1[i] = ... // Can directly access C.array without going through dynamic dispatch.
c.doSomething() = ... // Can directly call C.doSomething without going through virtual dispatch.
}
func usingD(d: D) {
func usingD(_ d: D) {
d.array1[i] = ... // Can directly access D.array1 without going through dynamic dispatch.
d.array2[i] = ... // Will access D.array2 through dynamic dispatch.
}
@@ -156,13 +156,13 @@ do not have any overriding declarations in the same file:
private var myPrivateVar : Int
}
func usingE(e: E) {
func usingE(_ e: E) {
e.doSomething() // There is no sub class in the file that declares this class.
// The compiler can remove virtual calls to doSomething()
// and directly call A's doSomething method.
}
func usingF(f: F) -> Int {
func usingF(_ f: F) -> Int {
return f.myPrivateVar
}
@@ -239,7 +239,7 @@ end of the callee. This means that if one writes a function like the following:
::
func append_one(a: [Int]) -> [Int] {
func append_one(_ a: [Int]) -> [Int] {
a.append(1)
return a
}
@@ -313,11 +313,11 @@ generics. Some more examples of generics:
::
class MyStack<T> {
func push(element: T) { ... }
func push(_ element: T) { ... }
func pop() -> T { ... }
}
func myAlgorithm(a: [T], length: Int) { ... }
func myAlgorithm(_ a: [T], length: Int) { ... }
// The compiler can specialize code of MyStack[Int]
var stackOfInts: MyStack[Int]

View File

@@ -398,7 +398,7 @@ work.
The current Swift approximation is::
func length(list : List) : Int {
func length(_ list : List) : Int {
switch list {
case .nil: return 0
case .cons(_,var tail): return 1 + length(tail)
@@ -408,7 +408,7 @@ The current Swift approximation is::
That's quite a bit more syntax, but it's mostly the extra braces from the
function body. We could remove those with something like this::
func length(list : List) : Int = switch list {
func length(_ list : List) : Int = switch list {
case .nil: return 0
case .cons(_,var tail): return 1 + length(tail)
}

View File

@@ -152,7 +152,7 @@ Here is an example of a ``.sil`` file::
}
// Declare a Swift function. The body is ignored by SIL.
func taxicabNorm(a:Point) -> Double {
func taxicabNorm(_ a:Point) -> Double {
return a.x + a.y
}
@@ -660,7 +660,7 @@ types. Function types are transformed in order to encode additional attributes:
- The **fully uncurried representation** of the function type, with
all of the curried argument clauses flattened into a single argument
clause. For instance, a curried function ``func foo(x:A)(y:B) -> C``
clause. For instance, a curried function ``func foo(_ x:A)(y:B) -> C``
might be emitted as a function of type ``((y:B), (x:A)) -> C``. The
exact representation depends on the function's `calling
convention`_, which determines the exact ordering of currying
@@ -872,7 +872,7 @@ Methods and curried function definitions in Swift also have multiple
partial application level. For a curried function declaration::
// Module example
func foo(x:A)(y:B)(z:C) -> D
func foo(_ x:A)(y:B)(z:C) -> D
The declaration references and types for the different uncurry levels are as
follows::
@@ -1269,14 +1269,14 @@ Tuples in the input type of the function are recursively destructured into
separate arguments, both in the entry point basic block of the callee, and
in the ``apply`` instructions used by callers::
func foo(x:Int, y:Int)
func foo(_ x:Int, y:Int)
sil @foo : $(x:Int, y:Int) -> () {
entry(%x : $Int, %y : $Int):
...
}
func bar(x:Int, y:(Int, Int))
func bar(_ x:Int, y:(Int, Int))
sil @bar : $(x:Int, y:(Int, Int)) -> () {
entry(%x : $Int, %y0 : $Int, %y1 : $Int):
@@ -1301,7 +1301,7 @@ in the ``apply`` instructions used by callers::
Calling a function with trivial value types as inputs and outputs
simply passes the arguments by value. This Swift function::
func foo(x:Int, y:Float) -> UnicodeScalar
func foo(_ x:Int, y:Float) -> UnicodeScalar
foo(x, y)
@@ -1326,7 +1326,7 @@ same way. This Swift function::
class A {}
func bar(x:A) -> (Int, A) { ... }
func bar(_ x:A) -> (Int, A) { ... }
bar(x)
@@ -1355,7 +1355,7 @@ returning. This Swift function::
@API struct A {}
func bas(x:A, y:Int) -> A { return x }
func bas(_ x:A, y:Int) -> A { return x }
var z = bas(x, y)
// ... use z ...
@@ -1381,7 +1381,7 @@ individually according to the above convention. This Swift function::
@API struct A {}
func zim(x:Int, y:A, (z:Int, w:(A, Int)))
func zim(_ x:Int, y:A, (z:Int, w:(A, Int)))
zim(x, y, (z, w))
@@ -1405,7 +1405,7 @@ Variadic Arguments
Variadic arguments and tuple elements are packaged into an array and passed as
a single array argument. This Swift function::
func zang(x:Int, (y:Int, z:Int...), v:Int, w:Int...)
func zang(_ x:Int, (y:Int, z:Int...), v:Int, w:Int...)
zang(x, (y, z0, z1), v, w0, w1, w2)
@@ -1424,7 +1424,7 @@ each "uncurry level" of the function. When a function is uncurried, its
outermost argument clauses are combined into a tuple in right-to-left order.
For the following declaration::
func curried(x:A)(y:B)(z:C)(w:D) -> Int {}
func curried(_ x:A)(y:B)(z:C)(w:D) -> Int {}
The types of the SIL entry points are as follows::
@@ -1447,7 +1447,7 @@ getter prior to calling the function and to write back to the property
on return by loading from the buffer and invoking the setter with the final
value. This Swift function::
func inout(x: inout Int) {
func inout(_ x: inout Int) {
x = 1
}
@@ -1470,7 +1470,7 @@ as the inner argument clause(s). When uncurried, the "self" argument is thus
passed last::
struct Foo {
func method(x:Int) -> Int {}
func method(_ x:Int) -> Int {}
}
sil @Foo_method_1 : $((x : Int), @inout Foo) -> Int { ... }
@@ -2833,7 +2833,7 @@ to register arguments. This should be fixed.
This instruction is used to implement both curry thunks and closures. A
curried function in Swift::
func foo(a:A)(b:B)(c:C)(d:D) -> E { /* body of foo */ }
func foo(_ a:A)(b:B)(c:C)(d:D) -> E { /* body of foo */ }
emits curry thunks in SIL as follows (retains and releases omitted for
clarity)::
@@ -2869,8 +2869,8 @@ clarity)::
A local function in Swift that captures context, such as ``bar`` in the
following example::
func foo(x:Int) -> Int {
func bar(y:Int) -> Int {
func foo(_ x:Int) -> Int {
func bar(_ y:Int) -> Int {
return x + y
}
return bar(1)

View File

@@ -156,7 +156,7 @@ end. For example::
// Return an array containing the elements of `source`, with
// `separator` interposed between each consecutive pair.
func array<S: SequenceType>(
source: S,
_ source: S,
withSeparator separator: S.Iterator.Element
) -> [S.Iterator.Element] {
var result: [S.Iterator.Element] = []
@@ -309,7 +309,7 @@ range of elements, denoted by two indices, by elements from a collection with a
mutating func replaceSubrange<
C: CollectionType where C.Iterator.Element == Self.Iterator.Element
>(
subRange: Range<Index>, with newElements: C
_ subRange: Range<Index>, with newElements: C
)
}

View File

@@ -167,7 +167,7 @@ library, but are compatible with the Cocoa guidelines.
/// mutable contiguous storage.
///
/// Complexity: O(\`count\`)
mutating func reserveCapacity(**minimumCapacity**: Int)
mutating func reserveCapacity(_ **minimumCapacity**: Int)
* Type parameter names of generic types describe the role of the
parameter, e.g.
@@ -198,9 +198,9 @@ Acceptable Short or Non-Descriptive Names
the resulting construct is supposed to act like a language extension
and is likely to have side-effects::
func map<U>(transformation: T->U) -> [U] // not this one
func map<U>(_ transformation: T->U) -> [U] // not this one
func forEach<S: SequenceType>(body: (S.Iterator.Element) -> ())
func forEach<S: SequenceType>(_ body: (S.Iterator.Element) -> ())
Prefixes and Suffixes
---------------------
@@ -221,8 +221,8 @@ Prefixes and Suffixes
.. parsed-literal::
extension Set {
func union(other: Set) -> Set
mutating func union\ **InPlace**\ (other: Set)
func union(_ other: Set) -> Set
mutating func union\ **InPlace**\ (_ other: Set)
}
* `with` is used as a prefix to denote a function that executes a

View File

@@ -89,7 +89,7 @@ For example::
// Public API that uses CVaListPointer, so CVarArgType has to be public, too.
public func withVaList<R>(
args: [CVarArgType],
_ args: [CVarArgType],
@noescape invoke body: (CVaListPointer) -> R
) -> R
@@ -101,7 +101,7 @@ We can't make ``map()``, ``filter()``, etc. all return ``Self``:
- ``map()`` takes a function ``(T) -> U`` and therefore can't return Self
literally. The required language feature for making ``map()`` return
something like ``Self`` in generic code (higher-kinded types) doesn't exist
in Swift. You can't write a method like ``func map(f: (T) -> U) -> Self<U>``
in Swift. You can't write a method like ``func map(_ f: (T) -> U) -> Self<U>``
today.
- There are lots of sequences that don't have an appropriate form for the
@@ -118,7 +118,7 @@ We can't make ``map()``, ``filter()``, etc. all return ``Self``:
func countFlattenedElements<
S : SequenceType where S.Generator.Element == Set<Double>
>(sequence: S) -> Int {
>(_ sequence: S) -> Int {
return sequence.map { $0.count }.reduce(0) { $0 + $1 }
}

View File

@@ -202,7 +202,7 @@ passes you a string *you own it*. Nobody can change a string value
.. parsed-literal::
|swift| class Cave {
// Utter something in the cave
func say(msg: String) -> String {
func say(_ msg: String) -> String {
:look1:`msg.addEcho()`\ :aside:`Modifying a parameter is safe because the callee sees a copy of the argument`
self.lastSound = msg
:look1:`return self.lastSound`\ :aside:`Returning a stored value is safe because the caller sees a copy of the value`
@@ -907,8 +907,8 @@ Searching
:Swift:
.. parsed-literal::
func **startsWith**\ (prefix: String)
func **endsWith**\ (suffix: String)
func **startsWith**\ (_ prefix: String)
func **endsWith**\ (_ suffix: String)
----
@@ -918,7 +918,7 @@ Searching
:Swift:
.. parsed-literal::
func **find**\ (sought: String) -> Range<String.IndexType>
func **find**\ (_ sought: String) -> Range<String.IndexType>
.. Note:: Most other languages provide something like
``s1.indexOf(s2)``, which returns only the starting index of
@@ -940,7 +940,7 @@ Searching
:Swift:
.. parsed-literal::
func **find**\ (match: (Character) -> Bool) -> Range<String.IndexType>
func **find**\ (_ match: (Character) -> Bool) -> Range<String.IndexType>
.. Admonition:: Usage Example
@@ -982,7 +982,7 @@ Building
.. parsed-literal::
func **+** (lhs: String, rhs: String) -> String
func [infix,assignment] **+=** (lhs: [inout] String, rhs: String)
func **append**\ (suffix: String)
func **append**\ (_ suffix: String)
Dynamic Formatting
@@ -1021,8 +1021,8 @@ Splitting
:Swift:
.. parsed-literal::
func split(maxSplit: Int = Int.max()) -> [String]
func split(separator: Character, maxSplit: Int = Int.max()) -> [String]
func split(_ maxSplit: Int = Int.max()) -> [String]
func split(_ separator: Character, maxSplit: Int = Int.max()) -> [String]
The semantics of these functions were taken from Python, which seems
to be a fairly good representative of what modern languages are
@@ -1037,7 +1037,7 @@ Splitting
func **split**\ <Seq: Sliceable, IsSeparator: Predicate
where IsSeparator.Arguments == Seq.Element
>(seq: Seq, isSeparator: IsSeparator, maxSplit: Int = Int.max(),
>(_ seq: Seq, isSeparator: IsSeparator, maxSplit: Int = Int.max(),
allowEmptySlices: Bool = false ) -> [Seq]
Splitting
@@ -1049,7 +1049,7 @@ Splitting
:Swift:
.. parsed-literal::
func **commonPrefix**\ (other: String) -> String
func **commonPrefix**\ (_ other: String) -> String
Upper/Lowercase
~~~~~~~~~~~~~~~

View File

@@ -115,13 +115,13 @@ into which we can stream text: [#character1]_
::
protocol OutputStream {
func append(text: String)
func append(_ text: String)
}
Every ``String`` can be used as an ``OutputStream`` directly::
extension String : OutputStream {
func append(text: String)
func append(_ text: String)
}
Debug Printing
@@ -201,7 +201,7 @@ representation before writing an object to a stream, we provide a
naturally::
protocol Streamable : CustomStringConvertible {
func writeTo<T: OutputStream>(target: [inout] T)
func writeTo<T: OutputStream>(_ target: [inout] T)
// You'll never want to reimplement this
func format() -> PrintRepresentation {
@@ -224,7 +224,7 @@ adds surrounding quotes and escapes special characters::
struct EscapedStringRepresentation : Streamable {
var _value: String
func writeTo<T: OutputStream>(target: [inout] T) {
func writeTo<T: OutputStream>(_ target: [inout] T) {
target.append("\"")
for c in _value {
target.append(c.escape())
@@ -237,7 +237,7 @@ Besides modeling ``OutputStream``, ``String`` also conforms to
``Streamable``::
extension String : Streamable {
func writeTo<T: OutputStream>(target: [inout] T) {
func writeTo<T: OutputStream>(_ target: [inout] T) {
target.append(self) // Append yourself to the stream
}
@@ -265,7 +265,7 @@ complicated ``format(…)`` might be written::
constructor(x: Int)
func toInt() -> Int
func format(radix: Int = 10, fill: String = " ", width: Int = 0)
func format(_ radix: Int = 10, fill: String = " ", width: Int = 0)
-> RadixFormat<This> {
return RadixFormat(this, radix: radix, fill: fill, width: width)
@@ -275,13 +275,13 @@ complicated ``format(…)`` might be written::
struct RadixFormat<T: CustomStringConvertibleInteger> : Streamable {
var value: T, radix = 10, fill = " ", width = 0
func writeTo<S: OutputStream>(target: [inout] S) {
func writeTo<S: OutputStream>(_ target: [inout] S) {
_writeSigned(value, &target)
}
// Write the given positive value to stream
func _writePositive<T:CustomStringConvertibleInteger, S: OutputStream>(
value: T, stream: [inout] S
_ value: T, stream: [inout] S
) -> Int {
if value == 0 { return 0 }
var radix: T = T.fromInt(self.radix)
@@ -294,7 +294,7 @@ complicated ``format(…)`` might be written::
}
func _writeSigned<T:CustomStringConvertibleInteger, S: OutputStream>(
value: T, target: [inout] S
_ value: T, target: [inout] S
) {
var width = 0
var result = ""
@@ -342,7 +342,7 @@ adapter that transforms its input to upper case before writing it to
an underlying stream::
struct UpperStream<UnderlyingStream:OutputStream> : OutputStream {
func append(x: String) { base.append(x.toUpper()) }
func append(_ x: String) { base.append(x.toUpper()) }
var base: UnderlyingStream
}
@@ -354,7 +354,7 @@ processed and written to the underlying stream:
.. parsed-literal::
struct TrimStream<UnderlyingStream:OutputStream> : OutputStream {
func append(x: String) { ... }
func append(_ x: String) { ... }
**func close() { ... }**
var base: UnderlyingStream
var bufferedWhitespace: String
@@ -372,7 +372,7 @@ For every conceivable ``OutputStream`` adaptor there's a corresponding
struct UpperStreamable<UnderlyingStreamable:Streamable> {
var base: UnderlyingStreamable
func writeTo<T: OutputStream>(target: [inout] T) {
func writeTo<T: OutputStream>(_ target: [inout] T) {
var adaptedStream = UpperStream(target)
self.base.writeTo(&adaptedStream)
target = adaptedStream.base
@@ -431,7 +431,7 @@ the underlying stream, which can then be "written back":
struct AdaptedStreamable<T:Streamable> {
...
func writeTo<Target: OutputStream>(target: [inout] Target) {
func writeTo<Target: OutputStream>(_ target: [inout] Target) {
// create the stream that transforms the representation
var adaptedTarget = adapt(target, adapter);
// write the Base object to the target stream

View File

@@ -22,11 +22,11 @@ parametric polymorphism. Swift makes extensive use of type inference,
allowing one to omit the types of many variables and expressions. For
example::
func round(x: Double) -> Int { /* ... */ }
func round(_ x: Double) -> Int { /* ... */ }
var pi: Double = 3.14159
var three = round(pi) // 'three' has type 'Int'
func identity<T>(x: T) -> T { return x }
func identity<T>(_ x: T) -> T { return x }
var eFloat: Float = -identity(2.71828) // numeric literal gets type 'Float'
Swift's type inference allows type information to flow in two
@@ -336,8 +336,8 @@ Overloading is the process of giving multiple, different definitions
to the same name. For example, we might overload a ``negate`` function
to work on both ``Int`` and ``Double`` types, e.g.::
func negate(x: Int) -> Int { return -x }
func negate(x: Double) -> Double { return -x }
func negate(_ x: Int) -> Int { return -x }
func negate(_ x: Double) -> Double { return -x }
Given that there are two definitions of ``negate``, what is the type
of the declaration reference expression ``negate``? If one selects the
@@ -730,7 +730,7 @@ checking problem::
func [conversion] __conversion () -> Int { /* ... */ }
}
func f(i : Int, s : String) { }
func f(_ i : Int, s : String) { }
var x : X
f(10.5, x)
@@ -836,7 +836,7 @@ consider a slight modification to our example, so that the argument to
``f`` is provided by another call, we get a different result
entirely::
func f(i : Int, s : String) { }
func f(_ i : Int, s : String) { }
func g() -> (f : Float, x : X) { }
f(g())

View File

@@ -277,14 +277,14 @@
var a4 = func {}
<i>// Really simple function</i>
func c(arg : Int) -&gt; Int { return arg+4 }
func c(_ arg : Int) -&gt; Int { return arg+4 }
<i>// Simple operators.</i>
func [infix_left=190] + (lhs : Int, rhs : Int) -&gt; Int
func [infix_left=160] == (lhs : Int, rhs : Int) -&gt; Bool
<i>// Curried function with multiple return values:</i>
func d(a : Int) (b : Int) -&gt; (res1 : Int, res2 : Int) {
func d(_ a : Int) (b : Int) -&gt; (res1 : Int, res2 : Int) {
return (a,b)
}
@@ -295,7 +295,7 @@
static func bankaccount() -> bankaccount {
// Custom 'constructor' logic goes here.
}
func deposit(arg : Int) {
func deposit(_ arg : Int) {
amount = amount + arg
}
@@ -320,7 +320,7 @@
case LeadPipe
}
func accuseSuspect(suspect:PersonOfInterest)
func accuseSuspect(_ suspect:PersonOfInterest)
inRoom(room:Room)
withWeapon(weapon:Weapon) {
print("It was \(suspect) in the \(room) with the \(weapon)")
@@ -393,7 +393,7 @@
case Two(Int, Int)
}
func f1(searchpolicy : DataSearchFlags) <i>// DataSearchFlags is a valid type name</i>
func f1(_ searchpolicy : DataSearchFlags) <i>// DataSearchFlags is a valid type name</i>
func test1() {
f1(DataSearchFlags.None) <i>// Use of constructor with qualified identifier</i>
f1(.None) <i>// Use of constructor with context sensitive type inference</i>
@@ -408,7 +408,7 @@
case Two(Int, Int)
}
func f2(a : SomeMoreInts)
func f2(_ a : SomeMoreInts)
func test2() {
<i>// Constructors for enum element can be used in the obvious way.</i>
@@ -872,7 +872,7 @@
<i>// Definition of an 'assert' function. Assertions and logging routines</i>
<i>// often want to conditionally evaluate their argument.</i>
func assert(condition : @autoclosure () -> Bool)
func assert(_ condition : @autoclosure () -> Bool)
<i>// Definition of the || operator - it captures its right hand side as</i>
<i>// an autoclosure so it can short-circuit evaluate it.</i>
@@ -1063,7 +1063,7 @@
var o = (1, 2, 3) <i>// Type = (Int, Int, Int)</i>
<i>// Function argument and result is a tuple type.</i>
func foo(x : Int, y : Int) -&gt; (val : Int, err : Int)
func foo(_ x : Int, y : Int) -&gt; (val : Int, err : Int)
<i>// enum and struct declarations with tuple values.</i>
struct S {
@@ -1387,7 +1387,7 @@ ill-formed if the type does not conform to the protocol.</p>
func bumpVersion()
}
func print(doc : Document) { <i>/* ... */</i> }
func print(_ doc : Document) { <i>/* ... */</i> }
var myDocument : VersionedDocument;
print(myDocument) <i>// okay: a VersionedDocument is a Document</i>
@@ -1728,7 +1728,7 @@ ill-formed if the type does not conform to the protocol.</p>
instantiates the default argument.</p>
<pre class="example">
func log(message:String,
func log(_ message:String,
file:String = __FILE__,
line:Int = __LINE__) {
print("\(file):\(line): \(message)")
@@ -1762,7 +1762,7 @@ ill-formed if the type does not conform to the protocol.</p>
<i>// A generic struct.</i>
struct Dict&lt;K,V&gt; {
init() {}
static func fromKeysAndValues(keys:K[], values:T[]) -&gt; Dict&lt;K,V&gt; {}
static func fromKeysAndValues(_ keys:K[], values:T[]) -&gt; Dict&lt;K,V&gt; {}
}
<i>// Construct an instance of the generic struct.</i>
@@ -1815,7 +1815,7 @@ ill-formed if the type does not conform to the protocol.</p>
can also be corrected by adding or removing parentheses.
<pre class="example">
func foo(x:Bool, y:Bool)
func foo(_ x:Bool, y:Bool)
var a,b,c,d,e : Int
foo(a &lt; b, c &gt; (d + e)) // ERROR: Misparses as (a&lt;b,c&gt;)(d + e)
@@ -1891,7 +1891,7 @@ ill-formed if the type does not conform to the protocol.</p>
<pre class="example">
<i>// Takes a closure that it calls to determine an ordering relation.</i>
func magic(val : Int, predicate : (a : Int, b : Int) -> Bool)
func magic(_ val : Int, predicate : (a : Int, b : Int) -> Bool)
func f() {
<i>// Compare one way. Closure is inferred to return Bool and take two ints</i>
@@ -1960,7 +1960,7 @@ ill-formed if the type does not conform to the protocol.</p>
<pre class="example">
enum Direction { case Up, Down }
func search(val : Int, direction : Direction)
func search(_ val : Int, direction : Direction)
func f() {
search(42, .Up)
@@ -2008,7 +2008,7 @@ ill-formed if the type does not conform to the protocol.</p>
var g = (4, y : 5, 6) <i>// Type = (Int, y : Int, Int)</i>
<i>// Named arguments to functions.</i>
func foo(a : Int, b : Int)
func foo(_ a : Int, b : Int)
foo(b = 4, a = 1)
</pre>
@@ -2157,7 +2157,7 @@ ill-formed if the type does not conform to the protocol.</p>
<a href="#expr-call">expr-call</a>, if functions meant to be used
with trailing closures are written as curried functions, e.g.,
<pre>
func map<T, U>(array : T[])(fn : (T) -> U) -> U[] { ... }
func map<T, U>(_ array : T[])(fn : (T) -> U) -> U[] { ... }
</pre>
There are two problems with this (admittedly simpler) design.
First, functions imported from C, C++, and Objective-C won't ever
@@ -2290,7 +2290,7 @@ func map<T, U>(array : T[])(fn : (T) -> U) -> U[] { ... }
<pre class="example">
<i>// A function with some statements.</i>
func fib(v : Int) -&gt; Int {
func fib(_ v : Int) -&gt; Int {
if v &lt; 2 {
return v
}

View File

@@ -1348,7 +1348,7 @@ otherwise empty cases in switch statements.
::
func classifyPoint(point: (Int, Int)) {
func classifyPoint(_ point: (Int, Int)) {
switch point {
case (0, 0):
print("origin")

View File

@@ -30,7 +30,7 @@ below).
This means that if you write code like this (optionally we could require an
attribute to make it clear that the value is actor local)::
func foo(a : int) -> int { print(a) return 0 }
func foo(_ a : int) -> int { print(a) return 0 }
var x = foo(1)
var y = foo(2)

View File

@@ -34,7 +34,7 @@ Being "great for Cocoa" means this must work and be efficient::
var a = [cocoaObject1, cocoaObject2]
someCocoaObject.takesAnNSArray(a)
func processViews(views: [AnyObject]) { ... }
func processViews(_ views: [AnyObject]) { ... }
var b = someNSWindow.views // views is an NSArray
processViews(b)

Some files were not shown because too many files have changed in this diff Show More