repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jeesmon/varamozhi-ios | refs/heads/master | varamozhi/DefaultKeyboard.swift | gpl-2.0 | 1 | //
// DefaultKeyboard.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/10/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
func defaultKeyboard() -> Keyboard {
let defaultKeyboard = Keyboard()
for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 0)
}
//+20141212 starting ipad
let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
if isPad {
let backspace = Key(.backspace)
defaultKeyboard.addKey(backspace, row: 0, page: 0)
}
for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 0)
}
let returnKey = Key(.return)
returnKey.uppercaseKeyCap = "return"
returnKey.uppercaseOutput = "\n"
returnKey.lowercaseOutput = "\n"
if isPad {
defaultKeyboard.addKey(returnKey, row: 1, page: 0)
}
let keyModel = Key(.shift)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
for key in ["Z", "X", "C", "V", "B", "N", "M"] {
let keyModel = Key(.character)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
}
if isPad {
let m1 = Key(.specialCharacter)
m1.uppercaseKeyCap = "!\n,"
m1.uppercaseOutput = "!"
m1.lowercaseOutput = ","
defaultKeyboard.addKey(m1, row: 2, page: 0)
let m2 = Key(.specialCharacter)
m2.uppercaseKeyCap = "?\n."
m2.uppercaseOutput = "?"
m2.lowercaseOutput = "."
defaultKeyboard.addKey(m2, row: 2, page: 0)
let keyModel = Key(.shift)
defaultKeyboard.addKey(keyModel, row: 2, page: 0)
}else{
let backspace = Key(.backspace)
defaultKeyboard.addKey(backspace, row: 2, page: 0)
}
let keyModeChangeNumbers = Key(.modeChange)
keyModeChangeNumbers.uppercaseKeyCap = "123"
keyModeChangeNumbers.toMode = 1
defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 0)
let keyboardChange = Key(.keyboardChange)
defaultKeyboard.addKey(keyboardChange, row: 3, page: 0)
//let settings = Key(.Settings)
//defaultKeyboard.addKey(settings, row: 3, page: 0)
let tildeModel = Key(.specialCharacter)
tildeModel.setLetter("~")
defaultKeyboard.addKey(tildeModel, row: 3, page: 0)
let space = Key(.space)
space.uppercaseKeyCap = "space"
space.uppercaseOutput = " "
space.lowercaseOutput = " "
defaultKeyboard.addKey(space, row: 3, page: 0)
let usModel = Key(.specialCharacter)
usModel.setLetter("_")
defaultKeyboard.addKey(usModel, row: 3, page: 0)
if isPad {
defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 3, page: 0)
let dismiss = Key(.dismiss)
defaultKeyboard.addKey(dismiss, row: 3, page: 0)
}else{
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 0)
}
for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 1)
}
if isPad {
defaultKeyboard.addKey(Key(.backspace), row: 0, page: 1)
}
let cl = Locale.current
let symbol: NSString? = (cl as NSLocale).object(forKey: NSLocale.Key.currencySymbol) as? NSString
var c = "₹"
if symbol != nil {
c = symbol! as String
}
for key in ["-", "/", ":", ";", "(", ")", c, "&", "@"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 1)
}
if isPad {
defaultKeyboard.addKey(Key(returnKey), row: 1, page: 1)
}else{
let keyModel = Key(.specialCharacter)
keyModel.setLetter("\"")
defaultKeyboard.addKey(keyModel, row: 1, page: 1)
}
let keyModeChangeSpecialCharacters = Key(.modeChange)
keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters.toMode = 2
defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 2, page: 1)
for key in [".", ",", "?", "!", "'"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 1)
}
if isPad {
let keyModel = Key(.specialCharacter)
keyModel.setLetter("\"")
defaultKeyboard.addKey(keyModel, row: 2, page: 1)
let keyModeChangeSpecialCharacters2 = Key(.modeChange)
keyModeChangeSpecialCharacters2.uppercaseKeyCap = "#+="
keyModeChangeSpecialCharacters2.toMode = 2
defaultKeyboard.addKey(keyModeChangeSpecialCharacters2, row: 2, page: 1)
}else{
defaultKeyboard.addKey(Key(.backspace), row: 2, page: 1)
}
let keyModeChangeLetters = Key(.modeChange)
keyModeChangeLetters.uppercaseKeyCap = "ABC"
keyModeChangeLetters.toMode = 0
defaultKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 1)
//defaultKeyboard.addKey(Key(settings), row: 3, page: 1)
defaultKeyboard.addKey(Key(space), row: 3, page: 1)
if isPad {
defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 1)
let dismiss = Key(.dismiss)
defaultKeyboard.addKey(dismiss, row: 3, page: 1)
}else{
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 1)
}
for key in ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 0, page: 2)
}
if isPad {
defaultKeyboard.addKey(Key(.backspace), row: 0, page: 2)
}
var d = "£"
if c == "₹" {
c = "$"
}else if c == "$" {
c = "₹"
}else{
d = "$"
c = "₹"
}
for key in ["_", "\\", "|", "~", "<", ">", c, d, "€"] {// ¥
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 1, page: 2)
}
if isPad {
defaultKeyboard.addKey(Key(returnKey), row: 1, page: 2)
}else{
let keyModel = Key(.specialCharacter)
keyModel.setLetter("•")
defaultKeyboard.addKey(keyModel, row: 1, page: 2)
}
defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2)
for key in [".", ",", "?", "!", "'"] {
let keyModel = Key(.specialCharacter)
keyModel.setLetter(key)
defaultKeyboard.addKey(keyModel, row: 2, page: 2)
}
if isPad {
let keyModel = Key(.specialCharacter)
keyModel.setLetter("\"")
defaultKeyboard.addKey(keyModel, row: 2, page: 2)
defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2)
}else{
defaultKeyboard.addKey(Key(.backspace), row: 2, page: 2)
}
defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2)
defaultKeyboard.addKey(Key(keyboardChange), row: 3, page: 2)
//defaultKeyboard.addKey(Key(settings), row: 3, page: 2)
defaultKeyboard.addKey(Key(space), row: 3, page: 2)
if isPad {
defaultKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2)
let dismiss = Key(.dismiss)
defaultKeyboard.addKey(dismiss, row: 3, page: 2)
}else{
defaultKeyboard.addKey(Key(returnKey), row: 3, page: 2)
}
return defaultKeyboard
}
| 05d2d1dc130bbb8a65a9e30476ef4813 | 27.785714 | 101 | 0.569479 | false | false | false | false |
kellanburket/Passenger | refs/heads/master | Pod/Classes/Extensions/String.swift | mit | 1 | //
// Functions.swift
// Pods
//
// Created by Kellan Cummings on 6/10/15.
//
//
import Foundation
import Wildcard
import CommonCrypto
internal let MIMEBase64Encoding: [Character] = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"+", "/"
]
internal let WhitelistedPercentEncodingCharacters: [UnicodeScalar] = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
".", "-", "_", "~"
]
internal extension String {
internal func sign(algorithm: HMACAlgorithm, key: String) -> String? {
if let data = self.dataUsingEncoding(NSUTF8StringEncoding) {
return data.sign(algorithm, key: key)
}
return nil
}
internal var base64Encoded: String {
var encoded: String = ""
var base: UInt64 = 0
var i: UInt64 = 0
var padding: String = ""
for character in self.unicodeScalars {
if i < 3 {
base = base << 8 | UInt64(character)
++i
} else {
for i = 3; i > 0; --i {
let bitmask: UInt64 = 0b111111 << (i * 6)
encoded.append(
MIMEBase64Encoding[Int((bitmask & base) >> (i * 6))]
)
}
encoded.append(
MIMEBase64Encoding[Int(0b111111 & base)]
)
base = UInt64(character)
i = 1
}
}
let remainder = Int(3 - i)
for var j = 0; j < remainder; ++j {
padding += "="
base <<= 2
}
let iterations: UInt64 = (remainder == 2) ? 1 : 2
for var k: UInt64 = iterations ; k > 0; --k {
let bitmask: UInt64 = 0b111111 << (k * 6)
encoded.append(
MIMEBase64Encoding[Int((bitmask & base) >> (k * 6))]
)
}
encoded.append(
MIMEBase64Encoding[Int(0b111111 & base)]
)
return encoded + padding
}
internal var urlEncoded: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
}
internal func percentEncode(ignore: [UnicodeScalar] = [UnicodeScalar]()) -> String {
var output = ""
for char in self.unicodeScalars {
if contains(WhitelistedPercentEncodingCharacters, char) || contains(ignore, char) {
output.append(char)
} else {
output += String(format: "%%%02X", UInt64(char))
}
}
return output
}
internal func encode(encoding: UInt = NSUTF8StringEncoding, allowLossyConversion: Bool = true) -> NSData? {
return self.dataUsingEncoding(encoding, allowLossyConversion: allowLossyConversion)
}
}
| 2a061cfb4c3844a636259e479619bcde | 30.66055 | 133 | 0.44277 | false | false | false | false |
mmrmmlrr/HandyText | refs/heads/master | Demo/HandyTextExample/HandyTextExample/ApplicationStyles.swift | mit | 1 | //
// ApplicationStyles.swift
// TextStyleExample
//
// Created by Aleksey on 04.07.16.
// Copyright © 2016 Aleksey Chernish. All rights reserved.
//
import UIKit
extension TextStyle {
static var plainText: TextStyle {
return TextStyle(font: .helvetica).withSize(12)
}
static var url: TextStyle {
return plainText.withForegroundColor(.blue).italic().withUnderline(.single)
}
static var header: TextStyle {
return plainText.withSizeMultiplied(by: 1.4).withForegroundColor(.orange).uppercase().bold()
}
static var button: TextStyle {
let shadow = NSShadow()
shadow.shadowOffset = CGSize(width: 1.0, height: 1.0)
shadow.shadowBlurRadius = 1.0
shadow.shadowColor = UIColor.lightGray
return header.withForegroundColor(.black).withShadow(shadow)
}
}
extension TagScheme {
static var `default`: TagScheme {
let scheme = TagScheme()
scheme.forTag("b") { $0.bold() }
scheme.forTag("i") { $0.italic().withUnderline(.single) }
scheme.forTag("u") { $0.uppercase() }
return scheme
}
}
| 841cdfc0e5e1466a429ac17a148ef634 | 21.893617 | 96 | 0.674721 | false | false | false | false |
AmberWhiteSky/Monkey | refs/heads/master | BugHub for Mac/BugHub/Carthage/Checkouts/Mantle/Carthage/Checkouts/Quick/Externals/Nimble/Nimble/Matchers/BeGreaterThanOrEqualTo.swift | apache-2.0 | 77 | import Foundation
public func beGreaterThanOrEqualTo<T: Comparable>(expectedValue: T?) -> MatcherFunc<T> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = actualExpression.evaluate()
return actualValue >= expectedValue
}
}
public func beGreaterThanOrEqualTo<T: NMBComparable>(expectedValue: T?) -> MatcherFunc<T> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than or equal to <\(stringify(expectedValue))>"
let actualValue = actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) != NSComparisonResult.OrderedAscending
return matches
}
}
public func >=<T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
public func >=<T: NMBComparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThanOrEqualTo(rhs))
}
extension NMBObjCMatcher {
public class func beGreaterThanOrEqualToMatcher(expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher { actualBlock, failureMessage, location in
let block = ({ actualBlock() as NMBComparable? })
let expr = Expression(expression: block, location: location)
return beGreaterThanOrEqualTo(expected).matches(expr, failureMessage: failureMessage)
}
}
}
| 98d63e12868cf603e9cfd8f93b20cb5e | 40.611111 | 122 | 0.712283 | false | false | false | false |
yinhaofrancis/YHAlertView | refs/heads/master | YHKit/YHAlertButton.swift | mit | 1 | //
// YHAlertButton.swift
// YHAlertView
//
// Created by hao yin on 2017/5/28.
// Copyright © 2017年 yyk. All rights reserved.
//
import UIKit
// MARK: - call back action
public typealias YHActionCallBack = ()->Void
public enum YHButtonStyle{
case title(title:String,action:YHActionCallBack?,style:YHViewStyle<UIButton>?)
case image(image:UIImage,action:YHActionCallBack?,style:YHViewStyle<UIButton>?)
}
class holdAction:NSObject{
func callblock(){
block?()
}
var block:(()->Void)?
}
extension UIButton{
public convenience init(action:YHButtonStyle){
self.init(frame: CGRect.zero)
let s = "\(Date().timeIntervalSince1970)-\(arc4random())"
switch action {
case let .title(title: t, action: call,style:st):
self.setTitle(t, for: .normal)
st?(self)
if let c = call{
self.addTarget(key: s, call: c, event: .touchUpInside)
}
case let .image(image: img, action: call,style:st):
self.setImage(img, for: .normal)
st?(self)
if let c = call{
self.addTarget(key: s, call: c, event: .touchUpInside)
}
}
}
}
extension UIControl {
private struct obj{
static var dic:[String:holdAction] = [:]
}
var mapAction:[String:holdAction]{
get{
return (objc_getAssociatedObject(self, &obj.dic) as? [String : holdAction]) ?? [:]
}
set{
objc_setAssociatedObject(self, &obj.dic, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func addTarget(key:String,call:@escaping ()->Void,event:UIControlEvents){
let hold = holdAction()
self.mapAction[key] = hold
hold.block = call
self.addTarget(hold, action: #selector(hold.callblock), for: event)
}
}
| 04a455151ff5e36e63dd342dd2429aef | 26.101449 | 98 | 0.590909 | false | false | false | false |
shahmishal/swift | refs/heads/master | stdlib/public/core/UnsafeRawPointer.swift | apache-2.0 | 2 | //===--- UnsafeRawPointer.swift -------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A raw pointer for accessing
/// untyped data.
///
/// The `UnsafeRawPointer` type provides no automated memory management, no type safety,
/// and no alignment guarantees. You are responsible for handling the life
/// cycle of any memory you work with through unsafe pointers, to avoid leaks
/// or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafeRawPointer` type to access and
/// manage raw bytes in memory, whether or not that memory has been bound to a
/// specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafeRawPointer` instance can be in one of several
/// states. Many pointer operations must only be applied to pointers with
/// memory in a specific state---you must keep track of the state of the
/// memory you are working with and understand the changes to that state that
/// different operations perform. Memory can be untyped and uninitialized,
/// bound to a type and uninitialized, or bound to a type and initialized to a
/// value. Finally, memory that was allocated previously may have been
/// deallocated, leaving existing pointers referencing unallocated memory.
///
/// Raw, Uninitialized Memory
/// -------------------------
///
/// Raw memory that has just been allocated is in an *uninitialized, untyped*
/// state. Uninitialized memory must be initialized with values of a type
/// before it can be used with any typed operations.
///
/// To bind uninitialized memory to a type without initializing it, use the
/// `bindMemory(to:count:)` method. This method returns a typed pointer
/// for further typed access to the memory.
///
/// Typed Memory
/// ------------
///
/// Memory that has been bound to a type, whether it is initialized or
/// uninitialized, is typically accessed using typed pointers---instances of
/// `UnsafePointer` and `UnsafeMutablePointer`. Initialization, assignment,
/// and deinitialization can be performed using `UnsafeMutablePointer`
/// methods.
///
/// Memory that has been bound to a type can be rebound to a different type
/// only after it has been deinitialized or if the bound type is a *trivial
/// type*. Deinitializing typed memory does not unbind that memory's type. The
/// deinitialized memory can be reinitialized with values of the same type,
/// bound to a new type, or deallocated.
///
/// - Note: A trivial type can be copied bit for bit with no indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references or other forms of indirection are
/// trivial, as are imported C structs and enumerations.
///
/// When reading from memory as raw
/// bytes when that memory is bound to a type, you must ensure that you
/// satisfy any alignment requirements.
///
/// Raw Pointer Arithmetic
/// ======================
///
/// Pointer arithmetic with raw pointers is performed at the byte level. When
/// you add to or subtract from a raw pointer, the result is a new raw pointer
/// offset by that number of bytes. The following example allocates four bytes
/// of memory and stores `0xFF` in all four bytes:
///
/// let bytesPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 4)
/// bytesPointer.storeBytes(of: 0xFFFF_FFFF, as: UInt32.self)
///
/// // Load a value from the memory referenced by 'bytesPointer'
/// let x = bytesPointer.load(as: UInt8.self) // 255
///
/// // Load a value from the last two allocated bytes
/// let offsetPointer = bytesPointer + 2
/// let y = offsetPointer.load(as: UInt16.self) // 65535
///
/// The code above stores the value `0xFFFF_FFFF` into the four newly allocated
/// bytes, and then loads the first byte as a `UInt8` instance and the third
/// and fourth bytes as a `UInt16` instance.
///
/// Always remember to deallocate any memory that you allocate yourself.
///
/// bytesPointer.deallocate()
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafeRawPointer` parameter, you can pass
/// an instance of that specific pointer type, pass an instance of a
/// compatible pointer type, or use Swift's implicit bridging to pass a
/// compatible pointer.
///
/// For example, the `print(address:as:)` function in the following code sample
/// takes an `UnsafeRawPointer` instance as its first parameter:
///
/// func print<T>(address p: UnsafeRawPointer, as type: T.Type) {
/// let value = p.load(as: type)
/// print(value)
/// }
///
/// As is typical in Swift, you can call the `print(address:as:)` function with
/// an `UnsafeRawPointer` instance. This example passes `rawPointer` as the initial
/// parameter.
///
/// // 'rawPointer' points to memory initialized with `Int` values.
/// let rawPointer: UnsafeRawPointer = ...
/// print(address: rawPointer, as: Int.self)
/// // Prints "42"
///
/// Because typed pointers can be implicitly cast to raw pointers when passed
/// as a parameter, you can also call `print(address:as:)` with any mutable or
/// immutable typed pointer instance.
///
/// let intPointer: UnsafePointer<Int> = ...
/// print(address: intPointer, as: Int.self)
/// // Prints "42"
///
/// let mutableIntPointer = UnsafeMutablePointer(mutating: intPointer)
/// print(address: mutableIntPointer, as: Int.self)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. Use inout syntax to implicitly
/// create a pointer to an instance of any type. The following example uses
/// implicit bridging to pass a pointer to `value` when calling
/// `print(address:as:)`:
///
/// var value: Int = 23
/// print(address: &value, as: Int.self)
/// // Prints "23"
///
/// An immutable pointer to the elements of an array is implicitly created when
/// you pass the array as an argument. This example uses implicit bridging to
/// pass a pointer to the elements of `numbers` when calling
/// `print(address:as:)`.
///
/// let numbers = [5, 10, 15, 20]
/// print(address: numbers, as: Int.self)
/// // Prints "5"
///
/// You can also use inout syntax to pass a mutable pointer to the elements of
/// an array. Because `print(address:as:)` requires an immutable pointer,
/// although this is syntactically valid, it isn't necessary.
///
/// var mutableNumbers = numbers
/// print(address: &mutableNumbers, as: Int.self)
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafeRawPointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafeRawPointer(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen
public struct UnsafeRawPointer: _Pointer {
public typealias Pointee = UInt8
/// The underlying raw pointer.
/// Implements conformance to the public protocol `_Pointer`.
public let _rawValue: Builtin.RawPointer
/// Creates a new raw pointer from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(_ other: UnsafePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: UnsafePointer<T>?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Creates a new raw pointer from the given mutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The mutable raw pointer to convert.
@_transparent
public init(_ other: UnsafeMutableRawPointer) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given mutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The mutable raw pointer to convert. If `other` is
/// `nil`, the result is `nil`.
@_transparent
public init?(_ other: UnsafeMutableRawPointer?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(_ other: UnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: UnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Deallocates the previously allocated memory block referenced by this pointer.
///
/// The memory to be deallocated must be uninitialized or initialized to a
/// trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Binds the memory to the specified type and returns a typed pointer to the
/// bound memory.
///
/// Use the `bindMemory(to:capacity:)` method to bind the memory referenced
/// by this pointer to the type `T`. The memory must be uninitialized or
/// initialized to a type that is layout compatible with `T`. If the memory
/// is uninitialized, it is still uninitialized after being bound to `T`.
///
/// In this example, 100 bytes of raw memory are allocated for the pointer
/// `bytesPointer`, and then the first four bytes are bound to the `Int8`
/// type.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// bytes: 100,
/// alignedTo: MemoryLayout<Int8>.alignment)
/// let int8Pointer = bytesPointer.bindMemory(to: Int8.self, capacity: count)
///
/// After calling `bindMemory(to:capacity:)`, the first four bytes of the
/// memory referenced by `bytesPointer` are bound to the `Int8` type, though
/// they remain uninitialized. The remainder of the allocated region is
/// unbound raw memory. All 100 bytes of memory must eventually be
/// deallocated.
///
/// - Warning: A memory location may only be bound to one type at a time. The
/// behavior of accessing memory as a type unrelated to its bound type is
/// undefined.
///
/// - Parameters:
/// - type: The type `T` to bind the memory to.
/// - count: The amount of memory to bind to type `T`, counted as instances
/// of `T`.
/// - Returns: A typed pointer to the newly bound memory. The memory in this
/// region is bound to `T`, but has not been modified in any other way.
/// The number of bytes in this region is
/// `count * MemoryLayout<T>.stride`.
@_transparent
@discardableResult
public func bindMemory<T>(
to type: T.Type, capacity count: Int
) -> UnsafePointer<T> {
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
return UnsafePointer<T>(_rawValue)
}
/// Returns a typed pointer to the memory referenced by this pointer,
/// assuming that the memory is already bound to the specified type.
///
/// Use this method when you have a raw pointer to memory that has *already*
/// been bound to the specified type. The memory starting at this pointer
/// must be bound to the type `T`. Accessing memory through the returned
/// pointer is undefined if the memory has not been bound to `T`. To bind
/// memory to `T`, use `bindMemory(to:capacity:)` instead of this method.
///
/// - Parameter to: The type `T` that the memory has already been bound to.
/// - Returns: A typed pointer to the same memory as this raw pointer.
@_transparent
public func assumingMemoryBound<T>(to: T.Type) -> UnsafePointer<T> {
return UnsafePointer<T>(_rawValue)
}
/// Returns a new instance of the given type, constructed from the raw memory
/// at the specified offset.
///
/// The memory at this pointer plus `offset` must be properly aligned for
/// accessing `T` and initialized to `T` or another type that is layout
/// compatible with `T`.
///
/// - Parameters:
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of the instance to create.
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance is memory-managed and unassociated
/// with the value in the memory referenced by this pointer.
@inlinable
public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
"load from misaligned raw pointer")
return Builtin.loadRaw((self + offset)._rawValue)
}
}
extension UnsafeRawPointer: Strideable {
// custom version for raw pointers
@_transparent
public func advanced(by n: Int) -> UnsafeRawPointer {
return UnsafeRawPointer(Builtin.gepRaw_Word(_rawValue, n._builtinWordValue))
}
}
/// A raw pointer for accessing and manipulating
/// untyped data.
///
/// The `UnsafeMutableRawPointer` type provides no automated memory management, no type safety,
/// and no alignment guarantees. You are responsible for handling the life
/// cycle of any memory you work with through unsafe pointers, to avoid leaks
/// or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafeMutableRawPointer` type to access and
/// manage raw bytes in memory, whether or not that memory has been bound to a
/// specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafeMutableRawPointer` instance can be in one of several
/// states. Many pointer operations must only be applied to pointers with
/// memory in a specific state---you must keep track of the state of the
/// memory you are working with and understand the changes to that state that
/// different operations perform. Memory can be untyped and uninitialized,
/// bound to a type and uninitialized, or bound to a type and initialized to a
/// value. Finally, memory that was allocated previously may have been
/// deallocated, leaving existing pointers referencing unallocated memory.
///
/// Raw, Uninitialized Memory
/// -------------------------
///
/// Raw memory that has just been allocated is in an *uninitialized, untyped*
/// state. Uninitialized memory must be initialized with values of a type
/// before it can be used with any typed operations.
///
/// You can use methods like `initializeMemory(as:from:)` and
/// `moveInitializeMemory(as:from:count:)` to bind raw memory to a type and
/// initialize it with a value or series of values. To bind uninitialized
/// memory to a type without initializing it, use the `bindMemory(to:count:)`
/// method. These methods all return typed pointers for further typed access
/// to the memory.
///
/// Typed Memory
/// ------------
///
/// Memory that has been bound to a type, whether it is initialized or
/// uninitialized, is typically accessed using typed pointers---instances of
/// `UnsafePointer` and `UnsafeMutablePointer`. Initialization, assignment,
/// and deinitialization can be performed using `UnsafeMutablePointer`
/// methods.
///
/// Memory that has been bound to a type can be rebound to a different type
/// only after it has been deinitialized or if the bound type is a *trivial
/// type*. Deinitializing typed memory does not unbind that memory's type. The
/// deinitialized memory can be reinitialized with values of the same type,
/// bound to a new type, or deallocated.
///
/// - Note: A trivial type can be copied bit for bit with no indirection or
/// reference-counting operations. Generally, native Swift types that do not
/// contain strong or weak references or other forms of indirection are
/// trivial, as are imported C structs and enumerations.
///
/// When reading from or writing to memory as raw
/// bytes when that memory is bound to a type, you must ensure that you
/// satisfy any alignment requirements.
/// Writing to typed memory as raw bytes must only be performed when the bound
/// type is a trivial type.
///
/// Raw Pointer Arithmetic
/// ======================
///
/// Pointer arithmetic with raw pointers is performed at the byte level. When
/// you add to or subtract from a raw pointer, the result is a new raw pointer
/// offset by that number of bytes. The following example allocates four bytes
/// of memory and stores `0xFF` in all four bytes:
///
/// let bytesPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
/// bytesPointer.storeBytes(of: 0xFFFF_FFFF, as: UInt32.self)
///
/// // Load a value from the memory referenced by 'bytesPointer'
/// let x = bytesPointer.load(as: UInt8.self) // 255
///
/// // Load a value from the last two allocated bytes
/// let offsetPointer = bytesPointer + 2
/// let y = offsetPointer.load(as: UInt16.self) // 65535
///
/// The code above stores the value `0xFFFF_FFFF` into the four newly allocated
/// bytes, and then loads the first byte as a `UInt8` instance and the third
/// and fourth bytes as a `UInt16` instance.
///
/// Always remember to deallocate any memory that you allocate yourself.
///
/// bytesPointer.deallocate()
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafeMutableRawPointer` parameter, you can pass
/// an instance of that specific pointer type, pass an instance of a
/// compatible pointer type, or use Swift's implicit bridging to pass a
/// compatible pointer.
///
/// For example, the `print(address:as:)` function in the following code sample
/// takes an `UnsafeMutableRawPointer` instance as its first parameter:
///
/// func print<T>(address p: UnsafeMutableRawPointer, as type: T.Type) {
/// let value = p.load(as: type)
/// print(value)
/// }
///
/// As is typical in Swift, you can call the `print(address:as:)` function with
/// an `UnsafeMutableRawPointer` instance. This example passes `rawPointer` as the initial
/// parameter.
///
/// // 'rawPointer' points to memory initialized with `Int` values.
/// let rawPointer: UnsafeMutableRawPointer = ...
/// print(address: rawPointer, as: Int.self)
/// // Prints "42"
///
/// Because typed pointers can be implicitly cast to raw pointers when passed
/// as a parameter, you can also call `print(address:as:)` with any mutable
/// typed pointer instance.
///
/// let intPointer: UnsafeMutablePointer<Int> = ...
/// print(address: intPointer, as: Int.self)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. Use inout syntax to implicitly
/// create a pointer to an instance of any type. The following example uses
/// implicit bridging to pass a pointer to `value` when calling
/// `print(address:as:)`:
///
/// var value: Int = 23
/// print(address: &value, as: Int.self)
/// // Prints "23"
///
/// A mutable pointer to the elements of an array is implicitly created when
/// you pass the array using inout syntax. This example uses implicit bridging
/// to pass a pointer to the elements of `numbers` when calling
/// `print(address:as:)`.
///
/// var numbers = [5, 10, 15, 20]
/// print(address: &numbers, as: Int.self)
/// // Prints "5"
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafeMutableRawPointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafeMutableRawPointer(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@frozen
public struct UnsafeMutableRawPointer: _Pointer {
public typealias Pointee = UInt8
/// The underlying raw pointer.
/// Implements conformance to the public protocol `_Pointer`.
public let _rawValue: Builtin.RawPointer
/// Creates a new raw pointer from a builtin raw pointer.
@_transparent
public init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(_ other: UnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: UnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Creates a new mutable raw pointer from the given immutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The immutable raw pointer to convert.
@_transparent
public init(mutating other: UnsafeRawPointer) {
_rawValue = other._rawValue
}
/// Creates a new mutable raw pointer from the given immutable raw pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeMutableRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The immutable raw pointer to convert. If `other` is
/// `nil`, the result is `nil`.
@_transparent
public init?(mutating other: UnsafeRawPointer?) {
guard let unwrapped = other else { return nil }
_rawValue = unwrapped._rawValue
}
/// Allocates uninitialized memory with the specified size and alignment.
///
/// You are in charge of managing the allocated memory. Be sure to deallocate
/// any memory that you manually allocate.
///
/// The allocated memory is not bound to any specific type and must be bound
/// before performing any typed operations. If you are using the memory for
/// a specific type, allocate memory using the
/// `UnsafeMutablePointer.allocate(capacity:)` static method instead.
///
/// - Parameters:
/// - byteCount: The number of bytes to allocate. `byteCount` must not be negative.
/// - alignment: The alignment of the new region of allocated memory, in
/// bytes.
/// - Returns: A pointer to a newly allocated region of memory. The memory is
/// allocated, but not initialized.
@inlinable
public static func allocate(
byteCount: Int, alignment: Int
) -> UnsafeMutableRawPointer {
// For any alignment <= _minAllocationAlignment, force alignment = 0.
// This forces the runtime's "aligned" allocation path so that
// deallocation does not require the original alignment.
//
// The runtime guarantees:
//
// align == 0 || align > _minAllocationAlignment:
// Runtime uses "aligned allocation".
//
// 0 < align <= _minAllocationAlignment:
// Runtime may use either malloc or "aligned allocation".
var alignment = alignment
if alignment <= _minAllocationAlignment() {
alignment = 0
}
return UnsafeMutableRawPointer(Builtin.allocRaw(
byteCount._builtinWordValue, alignment._builtinWordValue))
}
/// Deallocates the previously allocated memory block referenced by this pointer.
///
/// The memory to be deallocated must be uninitialized or initialized to a
/// trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Binds the memory to the specified type and returns a typed pointer to the
/// bound memory.
///
/// Use the `bindMemory(to:capacity:)` method to bind the memory referenced
/// by this pointer to the type `T`. The memory must be uninitialized or
/// initialized to a type that is layout compatible with `T`. If the memory
/// is uninitialized, it is still uninitialized after being bound to `T`.
///
/// In this example, 100 bytes of raw memory are allocated for the pointer
/// `bytesPointer`, and then the first four bytes are bound to the `Int8`
/// type.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// bytes: 100,
/// alignedTo: MemoryLayout<Int8>.alignment)
/// let int8Pointer = bytesPointer.bindMemory(to: Int8.self, capacity: count)
///
/// After calling `bindMemory(to:capacity:)`, the first four bytes of the
/// memory referenced by `bytesPointer` are bound to the `Int8` type, though
/// they remain uninitialized. The remainder of the allocated region is
/// unbound raw memory. All 100 bytes of memory must eventually be
/// deallocated.
///
/// - Warning: A memory location may only be bound to one type at a time. The
/// behavior of accessing memory as a type unrelated to its bound type is
/// undefined.
///
/// - Parameters:
/// - type: The type `T` to bind the memory to.
/// - count: The amount of memory to bind to type `T`, counted as instances
/// of `T`.
/// - Returns: A typed pointer to the newly bound memory. The memory in this
/// region is bound to `T`, but has not been modified in any other way.
/// The number of bytes in this region is
/// `count * MemoryLayout<T>.stride`.
@_transparent
@discardableResult
public func bindMemory<T>(
to type: T.Type, capacity count: Int
) -> UnsafeMutablePointer<T> {
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
return UnsafeMutablePointer<T>(_rawValue)
}
/// Returns a typed pointer to the memory referenced by this pointer,
/// assuming that the memory is already bound to the specified type.
///
/// Use this method when you have a raw pointer to memory that has *already*
/// been bound to the specified type. The memory starting at this pointer
/// must be bound to the type `T`. Accessing memory through the returned
/// pointer is undefined if the memory has not been bound to `T`. To bind
/// memory to `T`, use `bindMemory(to:capacity:)` instead of this method.
///
/// - Parameter to: The type `T` that the memory has already been bound to.
/// - Returns: A typed pointer to the same memory as this raw pointer.
@_transparent
public func assumingMemoryBound<T>(to: T.Type) -> UnsafeMutablePointer<T> {
return UnsafeMutablePointer<T>(_rawValue)
}
/// Initializes the memory referenced by this pointer with the given value,
/// binds the memory to the value's type, and returns a typed pointer to the
/// initialized memory.
///
/// The memory referenced by this pointer must be uninitialized or
/// initialized to a trivial type, and must be properly aligned for
/// accessing `T`.
///
/// The following example allocates enough raw memory to hold four instances
/// of `Int8`, and then uses the `initializeMemory(as:repeating:count:)` method
/// to initialize the allocated memory.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// byteCount: count * MemoryLayout<Int8>.stride,
/// alignment: MemoryLayout<Int8>.alignment)
/// let int8Pointer = myBytes.initializeMemory(
/// as: Int8.self, repeating: 0, count: count)
///
/// // After using 'int8Pointer':
/// int8Pointer.deallocate()
///
/// After calling this method on a raw pointer `p`, the region starting at
/// `self` and continuing up to `p + count * MemoryLayout<T>.stride` is bound
/// to type `T` and initialized. If `T` is a nontrivial type, you must
/// eventually deinitialize or move from the values in this region to avoid leaks.
///
/// - Parameters:
/// - type: The type to bind this memory to.
/// - repeatedValue: The instance to copy into memory.
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@inlinable
@discardableResult
public func initializeMemory<T>(
as type: T.Type, repeating repeatedValue: T, count: Int
) -> UnsafeMutablePointer<T> {
_debugPrecondition(count >= 0,
"UnsafeMutableRawPointer.initializeMemory: negative count")
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
var nextPtr = self
for _ in 0..<count {
Builtin.initialize(repeatedValue, nextPtr._rawValue)
nextPtr += MemoryLayout<T>.stride
}
return UnsafeMutablePointer(_rawValue)
}
/// Initializes the memory referenced by this pointer with the values
/// starting at the given pointer, binds the memory to the values' type, and
/// returns a typed pointer to the initialized memory.
///
/// The memory referenced by this pointer must be uninitialized or
/// initialized to a trivial type, and must be properly aligned for
/// accessing `T`.
///
/// The following example allocates enough raw memory to hold four instances
/// of `Int8`, and then uses the `initializeMemory(as:from:count:)` method
/// to initialize the allocated memory.
///
/// let count = 4
/// let bytesPointer = UnsafeMutableRawPointer.allocate(
/// bytes: count * MemoryLayout<Int8>.stride,
/// alignedTo: MemoryLayout<Int8>.alignment)
/// let values: [Int8] = [1, 2, 3, 4]
/// let int8Pointer = values.withUnsafeBufferPointer { buffer in
/// return bytesPointer.initializeMemory(as: Int8.self,
/// from: buffer.baseAddress!,
/// count: buffer.count)
/// }
/// // int8Pointer.pointee == 1
/// // (int8Pointer + 3).pointee == 4
///
/// // After using 'int8Pointer':
/// int8Pointer.deallocate(count)
///
/// After calling this method on a raw pointer `p`, the region starting at
/// `p` and continuing up to `p + count * MemoryLayout<T>.stride` is bound
/// to type `T` and initialized. If `T` is a nontrivial type, you must
/// eventually deinitialize or move from the values in this region to avoid
/// leaks. The instances in the region `source..<(source + count)` are
/// unaffected.
///
/// - Parameters:
/// - type: The type to bind this memory to.
/// - source: A pointer to the values to copy. The memory in the region
/// `source..<(source + count)` must be initialized to type `T` and must
/// not overlap the destination region.
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@inlinable
@discardableResult
public func initializeMemory<T>(
as type: T.Type, from source: UnsafePointer<T>, count: Int
) -> UnsafeMutablePointer<T> {
_debugPrecondition(
count >= 0,
"UnsafeMutableRawPointer.initializeMemory with negative count")
_debugPrecondition(
(UnsafeRawPointer(self + count * MemoryLayout<T>.stride)
<= UnsafeRawPointer(source))
|| UnsafeRawPointer(source + count) <= UnsafeRawPointer(self),
"UnsafeMutableRawPointer.initializeMemory overlapping range")
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
Builtin.copyArray(
T.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self.assumingMemoryBound(to: T.self) + i).initialize(to: source[i])
// }
return UnsafeMutablePointer(_rawValue)
}
/// Initializes the memory referenced by this pointer with the values
/// starting at the given pointer, binds the memory to the values' type,
/// deinitializes the source memory, and returns a typed pointer to the
/// newly initialized memory.
///
/// The memory referenced by this pointer must be uninitialized or
/// initialized to a trivial type, and must be properly aligned for
/// accessing `T`.
///
/// The memory in the region `source..<(source + count)` may overlap with the
/// destination region. The `moveInitializeMemory(as:from:count:)` method
/// automatically performs a forward or backward copy of all instances from
/// the source region to their destination.
///
/// After calling this method on a raw pointer `p`, the region starting at
/// `p` and continuing up to `p + count * MemoryLayout<T>.stride` is bound
/// to type `T` and initialized. If `T` is a nontrivial type, you must
/// eventually deinitialize or move from the values in this region to avoid
/// leaks. Any memory in the region `source..<(source + count)` that does
/// not overlap with the destination region is returned to an uninitialized
/// state.
///
/// - Parameters:
/// - type: The type to bind this memory to.
/// - source: A pointer to the values to copy. The memory in the region
/// `source..<(source + count)` must be initialized to type `T`.
/// - count: The number of copies of `value` to copy into memory. `count`
/// must not be negative.
/// - Returns: A typed pointer to the memory referenced by this raw pointer.
@inlinable
@discardableResult
public func moveInitializeMemory<T>(
as type: T.Type, from source: UnsafeMutablePointer<T>, count: Int
) -> UnsafeMutablePointer<T> {
_debugPrecondition(
count >= 0,
"UnsafeMutableRawPointer.moveInitializeMemory with negative count")
Builtin.bindMemory(_rawValue, count._builtinWordValue, type)
if self < UnsafeMutableRawPointer(source)
|| self >= UnsafeMutableRawPointer(source + count) {
// initialize forward from a disjoint or following overlapping range.
Builtin.takeArrayFrontToBack(
T.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self.assumingMemoryBound(to: T.self) + i)
// .initialize(to: (source + i).move())
// }
}
else {
// initialize backward from a non-following overlapping range.
Builtin.takeArrayBackToFront(
T.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// var src = source + count
// var dst = self.assumingMemoryBound(to: T.self) + count
// while dst != self {
// (--dst).initialize(to: (--src).move())
// }
}
return UnsafeMutablePointer(_rawValue)
}
/// Returns a new instance of the given type, constructed from the raw memory
/// at the specified offset.
///
/// The memory at this pointer plus `offset` must be properly aligned for
/// accessing `T` and initialized to `T` or another type that is layout
/// compatible with `T`.
///
/// - Parameters:
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of the instance to create.
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance is memory-managed and unassociated
/// with the value in the memory referenced by this pointer.
@inlinable
public func load<T>(fromByteOffset offset: Int = 0, as type: T.Type) -> T {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
"load from misaligned raw pointer")
return Builtin.loadRaw((self + offset)._rawValue)
}
/// Stores the given value's bytes into raw memory at the specified offset.
///
/// The type `T` to be stored must be a trivial type. The memory at this
/// pointer plus `offset` must be properly aligned for accessing `T`. The
/// memory must also be uninitialized, initialized to `T`, or initialized to
/// another trivial type that is layout compatible with `T`.
///
/// After calling `storeBytes(of:toByteOffset:as:)`, the memory is
/// initialized to the raw bytes of `value`. If the memory is bound to a
/// type `U` that is layout compatible with `T`, then it contains a value of
/// type `U`. Calling `storeBytes(of:toByteOffset:as:)` does not change the
/// bound type of the memory.
///
/// - Note: A trivial type can be copied with just a bit-for-bit copy without
/// any indirection or reference-counting operations. Generally, native
/// Swift types that do not contain strong or weak references or other
/// forms of indirection are trivial, as are imported C structs and enums.
///
/// If you need to store a copy of a nontrivial value into memory, or to
/// store a value into memory that contains a nontrivial value, you cannot
/// use the `storeBytes(of:toByteOffset:as:)` method. Instead, you must know
/// the type of value previously in memory and initialize or assign the
/// memory. For example, to replace a value stored in a raw pointer `p`,
/// where `U` is the current type and `T` is the new type, use a typed
/// pointer to access and deinitialize the current value before initializing
/// the memory with a new value.
///
/// let typedPointer = p.bindMemory(to: U.self, capacity: 1)
/// typedPointer.deinitialize(count: 1)
/// p.initializeMemory(as: T.self, to: newValue)
///
/// - Parameters:
/// - value: The value to store as raw bytes.
/// - offset: The offset from this pointer, in bytes. `offset` must be
/// nonnegative. The default is zero.
/// - type: The type of `value`.
@inlinable
public func storeBytes<T>(
of value: T, toByteOffset offset: Int = 0, as type: T.Type
) {
_debugPrecondition(0 == (UInt(bitPattern: self + offset)
& (UInt(MemoryLayout<T>.alignment) - 1)),
"storeBytes to misaligned raw pointer")
var temp = value
withUnsafeMutablePointer(to: &temp) { source in
let rawSrc = UnsafeMutableRawPointer(source)._rawValue
// FIXME: to be replaced by _memcpy when conversions are implemented.
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
(self + offset)._rawValue, rawSrc, UInt64(MemoryLayout<T>.size)._value,
/*volatile:*/ false._value)
}
}
/// Copies the specified number of bytes from the given raw pointer's memory
/// into this pointer's memory.
///
/// If the `byteCount` bytes of memory referenced by this pointer are bound to
/// a type `T`, then `T` must be a trivial type, this pointer and `source`
/// must be properly aligned for accessing `T`, and `byteCount` must be a
/// multiple of `MemoryLayout<T>.stride`.
///
/// After calling `copyMemory(from:byteCount:)`, the `byteCount` bytes of memory
/// referenced by this pointer are initialized to raw bytes. If the memory
/// is bound to type `T`, then it contains values of type `T`.
///
/// - Parameters:
/// - source: A pointer to the memory to copy bytes from. The memory in the
/// region `source..<(source + byteCount)` must be initialized to a trivial
/// type.
/// - byteCount: The number of bytes to copy. `byteCount` must not be negative.
@inlinable
public func copyMemory(from source: UnsafeRawPointer, byteCount: Int) {
_debugPrecondition(
byteCount >= 0, "UnsafeMutableRawPointer.copyMemory with negative count")
_memmove(dest: self, src: source, size: UInt(byteCount))
}
}
extension UnsafeMutableRawPointer: Strideable {
// custom version for raw pointers
@_transparent
public func advanced(by n: Int) -> UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(Builtin.gepRaw_Word(_rawValue, n._builtinWordValue))
}
}
extension OpaquePointer {
@_transparent
public init(_ from: UnsafeMutableRawPointer) {
self._rawValue = from._rawValue
}
@_transparent
public init?(_ from: UnsafeMutableRawPointer?) {
guard let unwrapped = from else { return nil }
self._rawValue = unwrapped._rawValue
}
@_transparent
public init(_ from: UnsafeRawPointer) {
self._rawValue = from._rawValue
}
@_transparent
public init?(_ from: UnsafeRawPointer?) {
guard let unwrapped = from else { return nil }
self._rawValue = unwrapped._rawValue
}
}
| 72c7a1eec1f0b972e5bf4a3096c634b3 | 42.408063 | 95 | 0.680016 | false | false | false | false |
mendesbarreto/IOS | refs/heads/master | UICollectionInUITableViewCell/UICollectionInUITableViewCell/NSDate.swift | mit | 1 | //
// NSDate.swift
// UICollectionInUITableViewCell
//
// Created by Douglas Barreto on 2/24/16.
// Copyright © 2016 CoderKingdom. All rights reserved.
//
import Foundation
// MARK Enums
public enum WeekDays: Int {
case Sunday = 1
case Monday = 2
case Tuesday = 3
case Wednesday = 4
case Thursday = 5
case Friday = 6
case Saturday = 7
}
// MARK Consts
let secondsPerDay:Double = 24 * 60 * 60 ;
let secondsPerWeek:Double = secondsPerDay * 7
let secondsPerMonth:Double = secondsPerWeek * 4
// MARK Extension
extension NSDate {
func nextDay() -> NSDate {
return self.dateByAddingTimeInterval(secondsPerDay)
}
func lastDay() -> NSDate {
return self.dateByAddingTimeInterval(-secondsPerDay)
}
func lastWeek() -> NSDate {
return self.dateByAddingTimeInterval(-secondsPerWeek)
}
func nextWeek() -> NSDate {
return self.dateByAddingTimeInterval(secondsPerWeek)
}
func forwardWeek( weeks:Int ) -> NSDate {
return self.forward(days: weeks * 7)
}
func backwardWeek( weeks:Int ) -> NSDate {
return self.backward(days: weeks * 7)
}
func forward( days days:Int ) -> NSDate {
return self.dateByAddingTimeInterval( NSTimeInterval( secondsPerDay * Double(days) ) )
}
func backward( days days:Int ) -> NSDate {
return self.dateByAddingTimeInterval( NSTimeInterval( -( secondsPerDay * Double(days) ) ) )
}
func beginOfMonth() -> NSDate {
let componet = self.createDateComponents()
componet.day -= componet.day - 1
return componet.date!
}
func endOfWeek() -> NSDate {
return self.forward(days: WeekDays.Saturday.rawValue - self.weekday().rawValue)
}
func beginOfWeek() -> NSDate {
return self.forward(days: WeekDays.Sunday.rawValue - self.weekday().rawValue)
}
func gotoMonday() ->NSDate {
return self.forward(days: WeekDays.Monday.rawValue - self.weekday().rawValue)
}
func weekday() -> WeekDays {
let weekDay = self.createDateComponents(components: NSCalendarUnit.Weekday ).weekday
return WeekDays(rawValue: weekDay)!
}
func day() -> Int {
return self.createDateComponents(components: NSCalendarUnit.Day ).day
}
func month() -> Int {
return self.createDateComponents(components: NSCalendarUnit.Month ).month
}
func year() -> Int {
return self.createDateComponents(components: NSCalendarUnit.Year ).year
}
func createDateComponents(components components: NSCalendarUnit? = nil, calendar:NSCalendar? = nil ) -> NSDateComponents {
let ca: NSCalendar
if let calTemp = calendar {
ca = calTemp
} else {
ca = NSCalendar.currentCalendar()
}
if let co = components {
return ca.components(co, fromDate: self)
}
return ca.components([
NSCalendarUnit.Weekday,
NSCalendarUnit.Day,
NSCalendarUnit.Calendar,
NSCalendarUnit.Month,
NSCalendarUnit.Year,
NSCalendarUnit.WeekOfYear,
NSCalendarUnit.Hour,
NSCalendarUnit.Minute,
NSCalendarUnit.Second,
NSCalendarUnit.Nanosecond], fromDate: self)
}
func isWeekDay( weekDay:WeekDays ) -> Bool {
return self.weekday() == weekDay
}
func weekDayName( localeIdentifier localeId:String? = nil ) -> String {
let dateFormatter = NSDateFormatter()
let locale: NSLocale
if let localeIdentifier: String = localeId {
locale = NSLocale(localeIdentifier: localeIdentifier)
} else {
if let preferred: String = NSLocale.preferredLanguages().first {
locale = NSLocale(localeIdentifier: preferred)
} else {
locale = NSLocale(localeIdentifier: "pt_br")
}
}
dateFormatter.dateFormat = "EEEE"
dateFormatter.locale = locale
return dateFormatter.stringFromDate(self)
}
func weekdayPrefix(length length:Int, localeIdentifier localeId:String? = nil ) -> String {
let weekDayName = self.weekDayName(localeIdentifier: localeId)
let usedLength: Int
let range: Range<String.Index>
if( length > weekDayName.characters.count ) {
usedLength = weekDayName.characters.count
} else {
usedLength = length
}
range = Range<String.Index>(start: weekDayName.startIndex, end: weekDayName.startIndex.advancedBy(usedLength))
return weekDayName.substringWithRange(range)
}
}
| 2b8c1cb8389cc90761223c75289eace6 | 23.975758 | 124 | 0.714147 | false | false | false | false |
rchatham/SwiftyAnimate | refs/heads/master | Tests/SwiftyAnimateTests/FinishAnimationTests.swift | mit | 1 | //
// FinishAnimationTests.swift
// SwiftyAnimate
//
// Created by Reid Chatham on 2/4/17.
// Copyright © 2017 Reid Chatham. All rights reserved.
//
import XCTest
@testable import SwiftyAnimate
class FinishAnimationTests: XCTestCase {
func test_EmptyAnimate_Finished() {
var finishedAnimation = false
let animation = Animate()
XCTAssertFalse(finishedAnimation)
animation.finish(duration: 0.5) {
finishedAnimation = true
}
XCTAssertTrue(finishedAnimation)
}
func test_EmptyAnimate_Finished_Animation() {
var finishedAnimation = false
let animation = Animate(duration: 0.5) {
finishedAnimation = true
}
XCTAssertFalse(finishedAnimation)
Animate().finish(animation: animation)
XCTAssertTrue(finishedAnimation)
}
func test_EmptyAnimate_Finished_Keyframe() {
var finishedAnimation = false
let animation = Animate()
XCTAssertFalse(finishedAnimation)
let keyframe = KeyframeAnimation(keyframes: [
Keyframe(duration: 1.0) {
finishedAnimation = true
}], options: [])
animation.finish(animation: keyframe)
XCTAssertTrue(finishedAnimation)
}
}
| 95060053c2db1368bf8bcebe10dcb495 | 22.145161 | 55 | 0.570035 | false | true | false | false |
wdkk/CAIM | refs/heads/master | Basic/answer/caim05_1effect_A/basic/DrawingViewController.swift | mit | 1 | //
// DrawingViewController.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
import UIKit
class DrawingViewController : CAIMViewController
{
// view_allを画面いっぱいのピクセル領域(screenPixelRect)の大きさで用意
var view_all:CAIMView = CAIMView(pixelFrame: CAIM.screenPixelRect)
// 画像データimg_allを画面のピクセルサイズ(screenPixelSize)に合わせて用意
var img_all:CAIMImage = CAIMImage(size: CAIM.screenPixelSize)
// パーティクル情報の構造体
struct Particle {
var cx:Int = 0
var cy:Int = 0
var radius:Int = 0
var color:CAIMColor = CAIMColor(R: 0.0, G: 0.0, B: 0.0, A: 1.0)
var step:Float = 0.0
}
// パーティクル群を保存しておく配列
var parts:[Particle] = [Particle]()
// 新しいパーティクル情報を作り、返す関数
func generateParticle() -> Particle {
let wid:Int = img_all.width
let hgt:Int = img_all.height
// 位置(cx,cy)、半径(radius)、色(color)を指定した範囲のランダム値で設定
var p = Particle()
p.cx = Int(arc4random()) % wid
p.cy = Int(arc4random()) % hgt
p.radius = Int(arc4random()) % 40 + 20
p.color = CAIMColor(
R: Float(arc4random() % 1000)/1000.0,
G: Float(arc4random() % 1000)/1000.0,
B: Float(arc4random() % 1000)/1000.0,
A: 1.0)
// 作成したパーティクル情報を返す
return p
}
// 準備
override func setup() {
// img_allを白で塗りつぶす
img_all.fillColor( CAIMColor.white )
// view_allの画像として、img_allを設定する
view_all.image = img_all
// view_allを画面に追加
self.view.addSubview( view_all )
// パーティクルを20個作成
for _ in 0 ..< 20 {
var p = generateParticle()
p.step = Float(arc4random() % 1000)/1000.0
parts.append(p)
}
}
// ポーリング
override func update() {
// 毎フレームごと、はじめにimg_allを白で塗りつぶす
img_all.fillColor( CAIMColor.white )
// parts内のパーティクル情報をすべてスキャンする
for i in 0 ..< parts.count {
// 1回処理をするごとにstepを0.01足す
parts[i].step += 0.01
// stepがマイナスの値の場合処理せず、次のパーティクルに移る
if(parts[i].step < 0.0) { continue }
// stepが1.0以上になったら、現在のパーティクル(parts[i])は処理を終えたものとする
// 次に、parts[i]はgenerateParticle()から新しいパーティクル情報を受け取り、新パーティクルとして再始動する
// parts[i]のstepを0.0に戻して初期化したのち、この処理は中断して次のパーティクルに移る
if(parts[i].step >= 1.0) {
parts[i] = generateParticle()
parts[i].step = 0.0
continue
}
// 不透明度(opacity)はstep=0.0~0.5の増加に合わせて最大まで濃くなり、0.5~1.0までに最小まで薄くなる
var opacity:Float = 0.0
if(parts[i].step < 0.5) { opacity = parts[i].step * 2.0 }
else { opacity = (1.0 - parts[i].step) * 2.0 }
// 半径は基本半径(parts[i].radius)にstepと係数2.0を掛け算する
let radius:Int = Int(Float(parts[i].radius) * parts[i].step * 2.0)
// パーティクル情報から求めた計算結果を用いてドームを描く
ImageToolBox.fillDomeFast(img_all, cx: parts[i].cx, cy: parts[i].cy,
radius: radius, color: parts[i].color, opacity: opacity)
}
// 画像が更新されている可能性があるので、view_allを再描画して結果を表示
view_all.redraw()
}
}
| 9bf6b759e4ba586f77c360ac3a938db5 | 30.155963 | 80 | 0.555948 | false | false | false | false |
pmlbrito/cookiecutter-ios-template | refs/heads/master | {{ cookiecutter.project_name | replace(' ', '') }}/app/{{ cookiecutter.project_name | replace(' ', '') }}/Presentation/Splash/Injection/SplashModuleInjector.swift | mit | 1 | //
// SplashModuleInjector.swift
// {{ cookiecutter.project_name | replace(' ', '') }}
//
// Created by {{ cookiecutter.lead_dev }} on 01/06/2017.
// Copyright © 2017 {{ cookiecutter.company_name }}. All rights reserved.
//
import Foundation
import Swinject
class SplashModuleInjector: ModuleInjectionProtocol {
static let container = Container()
func setup() {
resolver.register(SplashViewController.self) { r in
let controller = SplashViewController()
let defaultsManager = UserDefaultsManagerInjector().resolver.resolve(UserDefaultsManager.self)
let process = r.resolve(SplashProcessProtocol.self, argument: defaultsManager)
let interactor = r.resolve(SplashInteractorProtocol.self, argument: process)
controller.presenter = r.resolve(SplashPresenterProtocol.self, argument: interactor) as? BasePresenter
return controller
}
resolver.register(SplashPresenterProtocol.self) { (_, interactor: SplashInteractorProtocol?) in
SplashPresenter(interactor: interactor)
}
resolver.register(SplashInteractorProtocol.self) { (_, process: SplashProcessProtocol?) in
SplashInteractor(process: process)
}
resolver.register(SplashProcessProtocol.self) { (_, userDefaults: UserDefaultsManager?) in
SplashProcess(userDefaults: userDefaults)
}
}
}
extension SplashModuleInjector {
var resolver: Container { return SplashModuleInjector.container }
}
| ae5a5b59f55b30b4ffc4a2bec0455144 | 33.909091 | 114 | 0.693359 | false | false | false | false |
IvanKalaica/GitHubSearch | refs/heads/master | GitHubSearch/GitHubSearch/Model/Service/GitHub/DefaultOAuthService.swift | mit | 1 | //
// DefaultOAuthService.swift
// GitHubSearch
//
// Created by Ivan Kalaica on 23/09/2017.
// Copyright © 2017 Kalaica. All rights reserved.
//
import Foundation
import Alamofire
import OAuth2
import RxSwift
struct DefaultOAuthService: OAuthService {
private let oAuth2CodeGrant: OAuth2CodeGrant
init() {
self.oAuth2CodeGrant = OAuth2CodeGrant(settings: [
"client_id": GitHubOAuth.clientId,
"client_secret": GitHubOAuth.clientSecret,
"authorize_uri": GitHubOAuth.authorizeUri,
"token_uri": GitHubOAuth.tokenUri,
"redirect_uris": GitHubOAuth.redirectUris,
"scope": GitHubOAuth.scope,
"secret_in_body": GitHubOAuth.secretInBody,
"keychain": GitHubOAuth.keychain,
] as OAuth2JSON)
let sessionManager = SessionManager.default
let retrier = OAuth2RetryHandler(oauth2: self.oAuth2CodeGrant)
sessionManager.adapter = retrier
sessionManager.retrier = retrier
}
func authorize() -> Observable<Void> {
return Observable.create { observer in
self.oAuth2CodeGrant.authorize() { authParameters, error in
guard let sError = error else {
print("Authorized! Access token is in `oauth2.accessToken`")
print("Authorized! Additional parameters: \(String(describing: authParameters))")
observer.onNext()
observer.onCompleted()
return
}
print("Authorization was canceled or went wrong: \(String(describing: sError))")
observer.onError(sError)
}
return Disposables.create()
}
}
func logout() {
self.oAuth2CodeGrant.forgetTokens()
let storage = HTTPCookieStorage.shared
storage.cookies?.forEach() { storage.deleteCookie($0) }
}
func handleRedirectURL(_ url: URL) {
self.oAuth2CodeGrant.handleRedirectURL(url)
}
}
| d0cfc3f24598c7e40f26f808785966f9 | 33.233333 | 101 | 0.609542 | false | false | false | false |
KrishMunot/swift | refs/heads/master | stdlib/public/SDK/ObjectiveC/ObjectiveC.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported
import ObjectiveC
//===----------------------------------------------------------------------===//
// Objective-C Primitive Types
//===----------------------------------------------------------------------===//
public typealias Boolean = Swift.Boolean
/// The Objective-C BOOL type.
///
/// On 64-bit iOS, the Objective-C BOOL type is a typedef of C/C++
/// bool. Elsewhere, it is "signed char". The Clang importer imports it as
/// ObjCBool.
@_fixed_layout
public struct ObjCBool : Boolean, BooleanLiteralConvertible {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
var _value: Int8
init(_ value: Int8) {
self._value = value
}
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
#else
// Everywhere else it is C/C++'s "Bool"
var _value : Bool
public init(_ value: Bool) {
self._value = value
}
#endif
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
return _value != 0
#else
return _value
#endif
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension ObjCBool : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension ObjCBool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool {
return ObjCBool(x)
}
@warn_unused_result
public // COMPILER_INTRINSIC
func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool {
return Bool(x)
}
/// The Objective-C SEL type.
///
/// The Objective-C SEL type is typically an opaque pointer. Swift
/// treats it as a distinct struct type, with operations to
/// convert between C strings and selectors.
///
/// The compiler has special knowledge of this type.
@_fixed_layout
public struct Selector : StringLiteralConvertible, NilLiteralConvertible {
var ptr : OpaquePointer
/// Create a selector from a string.
public init(_ str : String) {
ptr = str.withCString { sel_registerName($0).ptr }
}
/// Create an instance initialized to `value`.
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
/// Construct a selector from `value`.
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
// FIXME: Fast-path this in the compiler, so we don't end up with
// the sel_registerName call at compile time.
/// Create an instance initialized to `value`.
public init(stringLiteral value: String) {
self = sel_registerName(value)
}
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
ptr = nil
}
}
@warn_unused_result
public func ==(lhs: Selector, rhs: Selector) -> Bool {
return sel_isEqual(lhs, rhs)
}
extension Selector : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return ptr.hashValue
}
}
extension Selector : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
let name = sel_getName(self)
if name == nil {
return "<NULL>"
}
return String(cString: name)
}
}
extension String {
/// Construct the C string representation of an Objective-C selector.
public init(_sel: Selector) {
// FIXME: This misses the ASCII optimization.
self = String(cString: sel_getName(_sel))
}
}
extension Selector : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: String(_sel: self))
}
}
//===----------------------------------------------------------------------===//
// NSZone
//===----------------------------------------------------------------------===//
@_fixed_layout
public struct NSZone : NilLiteralConvertible {
var pointer : OpaquePointer
public init() { pointer = nil }
/// Create an instance initialized with `nil`.
@_transparent
public init(nilLiteral: ()) {
pointer = nil
}
}
// Note: NSZone becomes Zone in Swift 3.
typealias Zone = NSZone
//===----------------------------------------------------------------------===//
// FIXME: @autoreleasepool substitute
//===----------------------------------------------------------------------===//
@warn_unused_result
@_silgen_name("_swift_objc_autoreleasePoolPush")
func __pushAutoreleasePool() -> OpaquePointer
@_silgen_name("_swift_objc_autoreleasePoolPop")
func __popAutoreleasePool(_ pool: OpaquePointer)
public func autoreleasepool(@noescape _ code: () -> Void) {
let pool = __pushAutoreleasePool()
code()
__popAutoreleasePool(pool)
}
//===----------------------------------------------------------------------===//
// Mark YES and NO unavailable.
//===----------------------------------------------------------------------===//
@available(*, unavailable, message: "Use 'Bool' value 'true' instead")
public var YES: ObjCBool {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, message: "Use 'Bool' value 'false' instead")
public var NO: ObjCBool {
fatalError("can't retrieve unavailable property")
}
// FIXME: We can't make the fully-generic versions @_transparent due to
// rdar://problem/19418937, so here are some @_transparent overloads
// for ObjCBool
@_transparent
@warn_unused_result
public func && <T : Boolean>(
lhs: T, @autoclosure rhs: () -> ObjCBool
) -> Bool {
return lhs.boolValue ? rhs().boolValue : false
}
@_transparent
@warn_unused_result
public func || <T : Boolean>(
lhs: T, @autoclosure rhs: () -> ObjCBool
) -> Bool {
return lhs.boolValue ? true : rhs().boolValue
}
//===----------------------------------------------------------------------===//
// NSObject
//===----------------------------------------------------------------------===//
// NSObject implements Equatable's == as -[NSObject isEqual:]
// NSObject implements Hashable's hashValue() as -[NSObject hash]
// FIXME: what about NSObjectProtocol?
extension NSObject : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return hash
}
}
@warn_unused_result
public func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}
extension NSObject : CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs
public var _cVarArgEncoding: [Int] {
_autorelease(self)
return _encodeBitsAsWords(self)
}
}
| 82dd80e1e2d9ff3091f8d3e4f9b4dd9a | 26.967857 | 80 | 0.60069 | false | false | false | false |
becvert/cordova-plugin-zeroconf | refs/heads/master | src/ios/ZeroConf.swift | mit | 1 | import Foundation
@objc(ZeroConf) public class ZeroConf : CDVPlugin {
fileprivate var publishers: [String: Publisher]!
fileprivate var browsers: [String: Browser]!
override public func pluginInitialize() {
publishers = [:]
browsers = [:]
}
override public func onAppTerminate() {
for (_, publisher) in publishers {
publisher.destroy()
}
publishers.removeAll()
for (_, browser) in browsers {
browser.destroy();
}
browsers.removeAll()
}
@objc public func getHostname(_ command: CDVInvokedUrlCommand) {
let hostname = Hostname.get() as String
#if DEBUG
print("ZeroConf: hostname \(hostname)")
#endif
let pluginResult = CDVPluginResult(status:CDVCommandStatus_OK, messageAs: hostname)
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
@objc public func register(_ command: CDVInvokedUrlCommand) {
let type = command.argument(at: 0) as! String
let domain = command.argument(at: 1) as! String
let name = command.argument(at: 2) as! String
let port = command.argument(at: 3) as! Int
#if DEBUG
print("ZeroConf: register \(name + "." + type + domain)")
#endif
var txtRecord: [String: Data]?
if let dict = command.arguments[4] as? [String: String] {
txtRecord = [:]
for (key, value) in dict {
txtRecord?[key] = value.data(using: String.Encoding.utf8)
}
}
let publisher = Publisher(withDomain: domain, withType: type, withName: name, withPort: port, withTxtRecord: txtRecord, withCallbackId: command.callbackId)
publisher.commandDelegate = commandDelegate
publisher.register()
publishers[name + "." + type + domain] = publisher
}
@objc public func unregister(_ command: CDVInvokedUrlCommand) {
let type = command.argument(at: 0) as! String
let domain = command.argument(at: 1) as! String
let name = command.argument(at: 2) as! String
#if DEBUG
print("ZeroConf: unregister \(name + "." + type + domain)")
#endif
if let publisher = publishers[name + "." + type + domain] {
publisher.unregister();
publishers.removeValue(forKey: name + "." + type + domain)
}
}
@objc public func stop(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("ZeroConf: stop")
#endif
for (_, publisher) in publishers {
publisher.unregister()
}
publishers.removeAll()
let pluginResult = CDVPluginResult(status:CDVCommandStatus_OK)
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
@objc public func watch(_ command: CDVInvokedUrlCommand) {
let type = command.argument(at: 0) as! String
let domain = command.argument(at: 1) as! String
#if DEBUG
print("ZeroConf: watch \(type + domain)")
#endif
let browser = Browser(withDomain: domain, withType: type, withCallbackId: command.callbackId)
browser.commandDelegate = commandDelegate
browser.watch()
browsers[type + domain] = browser
}
@objc public func unwatch(_ command: CDVInvokedUrlCommand) {
let type = command.argument(at: 0) as! String
let domain = command.argument(at: 1) as! String
#if DEBUG
print("ZeroConf: unwatch \(type + domain)")
#endif
if let browser = browsers[type + domain] {
browser.unwatch();
browsers.removeValue(forKey: type + domain)
}
}
@objc public func close(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("ZeroConf: close")
#endif
for (_, browser) in browsers {
browser.unwatch()
}
browsers.removeAll()
let pluginResult = CDVPluginResult(status:CDVCommandStatus_OK)
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
@objc public func reInit(_ command: CDVInvokedUrlCommand) {
#if DEBUG
print("ZeroConf: reInit")
#endif
// Terminate
for (_, publisher) in publishers {
publisher.destroy()
}
publishers.removeAll()
for (_, browser) in browsers {
browser.destroy();
}
browsers.removeAll()
// init
publishers = [:]
browsers = [:]
let pluginResult = CDVPluginResult(status:CDVCommandStatus_OK)
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
internal class Publisher: NSObject, NetServiceDelegate {
var nsp: NetService?
var domain: String
var type: String
var name: String
var port: Int
var txtRecord: [String: Data]?
var callbackId: String
var commandDelegate: CDVCommandDelegate?
init (withDomain domain: String, withType type: String, withName name: String, withPort port: Int, withTxtRecord txtRecord: [String: Data]?, withCallbackId callbackId: String) {
self.domain = domain
self.type = type
self.name = name
self.port = port
self.txtRecord = txtRecord
self.callbackId = callbackId
}
func register() {
// Netservice
let service = NetService(domain: domain, type: type , name: name, port: Int32(port))
nsp = service
service.delegate = self
if let record = txtRecord {
if record.count > 0 {
service.setTXTRecord(NetService.data(fromTXTRecord: record))
}
}
commandDelegate?.run(inBackground: {
service.publish()
})
}
func unregister() {
if let service = nsp {
service.stop()
}
}
func destroy() {
if let service = nsp {
service.stop()
}
}
@objc func netServiceDidPublish(_ netService: NetService) {
#if DEBUG
print("ZeroConf: netService:didPublish:\(netService)")
#endif
let service = ZeroConf.jsonifyService(netService)
let message: NSDictionary = NSDictionary(objects: ["registered", service], forKeys: ["action" as NSCopying, "service" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (message as! [AnyHashable: Any]))
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netService(_ netService: NetService, didNotPublish errorDict: [String : NSNumber]) {
#if DEBUG
print("ZeroConf: netService:didNotPublish:\(netService) \(errorDict)")
#endif
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceDidStop(_ netService: NetService) {
nsp = nil
commandDelegate = nil
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
}
internal class Browser: NSObject, NetServiceDelegate, NetServiceBrowserDelegate {
var nsb: NetServiceBrowser?
var domain: String
var type: String
var callbackId: String
var services: [String: NetService] = [:]
var commandDelegate: CDVCommandDelegate?
init (withDomain domain: String, withType type: String, withCallbackId callbackId: String) {
self.domain = domain
self.type = type
self.callbackId = callbackId
}
func watch() {
// Net service browser
let browser = NetServiceBrowser()
nsb = browser
browser.delegate = self
commandDelegate?.run(inBackground: {
browser.searchForServices(ofType: self.type, inDomain: self.domain)
})
let pluginResult = CDVPluginResult(status: CDVCommandStatus_NO_RESULT)
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
func unwatch() {
if let service = nsb {
service.stop()
}
}
func destroy() {
if let service = nsb {
service.stop()
}
}
@objc func netServiceBrowser(_ browser: NetServiceBrowser, didNotSearch errorDict: [String : NSNumber]) {
#if DEBUG
print("ZeroConf: netServiceBrowser:didNotSearch:\(netService) \(errorDict)")
#endif
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser,
didFind netService: NetService,
moreComing moreServicesComing: Bool) {
#if DEBUG
print("ZeroConf: netServiceBrowser:didFindService:\(netService)")
#endif
netService.delegate = self
netService.resolve(withTimeout: 5000)
services[netService.name] = netService // keep strong reference to catch didResolveAddress
let service = ZeroConf.jsonifyService(netService)
let message: NSDictionary = NSDictionary(objects: ["added", service], forKeys: ["action" as NSCopying, "service" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (message as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceDidResolveAddress(_ netService: NetService) {
#if DEBUG
print("ZeroConf: netService:didResolveAddress:\(netService)")
#endif
let service = ZeroConf.jsonifyService(netService)
let message: NSDictionary = NSDictionary(objects: ["resolved", service], forKeys: ["action" as NSCopying, "service" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (message as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netService(_ netService: NetService, didNotResolve errorDict: [String : NSNumber]) {
#if DEBUG
print("ZeroConf: netService:didNotResolve:\(netService) \(errorDict)")
#endif
let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR)
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser,
didRemove netService: NetService,
moreComing moreServicesComing: Bool) {
#if DEBUG
print("ZeroConf: netServiceBrowser:didRemoveService:\(netService)")
#endif
services.removeValue(forKey: netService.name)
let service = ZeroConf.jsonifyService(netService)
let message: NSDictionary = NSDictionary(objects: ["removed", service], forKeys: ["action" as NSCopying, "service" as NSCopying])
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: (message as! [AnyHashable: Any]))
pluginResult?.setKeepCallbackAs(true)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
@objc func netServiceDidStop(_ netService: NetService) {
nsb = nil
services.removeAll()
commandDelegate = nil
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate?.send(pluginResult, callbackId: callbackId)
}
}
fileprivate static func jsonifyService(_ netService: NetService) -> NSDictionary {
var ipv4Addresses: [String] = []
var ipv6Addresses: [String] = []
for address in netService.addresses! {
if let family = extractFamily(address) {
if family == 4 {
if let addr = extractAddress(address) {
ipv4Addresses.append(addr)
}
} else if family == 6 {
if let addr = extractAddress(address) {
ipv6Addresses.append(addr)
}
}
}
}
if ipv6Addresses.count > 1 {
ipv6Addresses = Array(Set(ipv6Addresses))
}
var txtRecord: [String: String] = [:]
if let txtRecordData = netService.txtRecordData() {
txtRecord = dictionary(fromTXTRecord: txtRecordData)
}
var hostName:String = ""
if netService.hostName != nil {
hostName = netService.hostName!
}
let service: NSDictionary = NSDictionary(
objects: [netService.domain, netService.type, netService.name, netService.port, hostName, ipv4Addresses, ipv6Addresses, txtRecord],
forKeys: ["domain" as NSCopying, "type" as NSCopying, "name" as NSCopying, "port" as NSCopying, "hostname" as NSCopying, "ipv4Addresses" as NSCopying, "ipv6Addresses" as NSCopying, "txtRecord" as NSCopying])
return service
}
fileprivate static func extractFamily(_ addressBytes:Data) -> Int? {
let addr = (addressBytes as NSData).bytes.load(as: sockaddr.self)
if (addr.sa_family == sa_family_t(AF_INET)) {
return 4
}
else if (addr.sa_family == sa_family_t(AF_INET6)) {
return 6
}
else {
return nil
}
}
fileprivate static func extractAddress(_ addressBytes:Data) -> String? {
var addr = (addressBytes as NSData).bytes.load(as: sockaddr.self)
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname,
socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0) {
return String(cString: hostname)
}
return nil
}
fileprivate static func dictionary(fromTXTRecord txtData: Data) -> [String: String] {
var result = [String: String]()
var data = txtData
while !data.isEmpty {
// The first byte of each record is its length, so prefix that much data
let recordLength = Int(data.removeFirst())
guard data.count >= recordLength else { return [:] }
let recordData = data[..<(data.startIndex + recordLength)]
data = data.dropFirst(recordLength)
guard let record = String(bytes: recordData, encoding: .utf8) else { return [:] }
// The format of the entry is "key=value"
// (According to the reference implementation, = is optional if there is no value,
// and any equals signs after the first are part of the value.)
// `ommittingEmptySubsequences` is necessary otherwise an empty string will crash the next line
let keyValue = record.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
let key = String(keyValue[0])
// If there's no value, make the value the empty string
switch keyValue.count {
case 1:
result[key] = ""
case 2:
result[key] = String(keyValue[1])
default:
fatalError("ZeroConf: Malformed or unexpected TXTRecord keyValue")
}
}
return result
}
}
| 01cf8ce34ca39354b79113c9483336c3 | 33.871795 | 219 | 0.587255 | false | false | false | false |
Zig1375/SwiftClickHouse | refs/heads/master | Sources/SwiftClickHouse/Core/ClichHouseValue.swift | mit | 1 | import Foundation
public struct ClickHouseValue : CustomStringConvertible {
public let val_number : NSNumber?;
public let val_string : String?;
public let val_date : Date?;
public let val_array : [ClickHouseValue]?;
public let type : ClickHouseType;
public let isNull : Bool;
public init(type : ClickHouseType, number : NSNumber, isNull: Bool = false) {
self.type = type;
self.val_number = number;
self.val_string = nil;
self.val_date = nil;
self.val_array = nil;
self.isNull = isNull;
}
public init(type : ClickHouseType, string : String) {
self.type = type;
self.val_number = nil;
self.val_string = string;
self.val_date = nil;
self.val_array = nil;
self.isNull = false;
}
public init(type : ClickHouseType, date : Date) {
self.type = type;
self.val_number = nil;
self.val_string = nil;
self.val_date = date;
self.val_array = nil;
self.isNull = false;
}
public init(type : ClickHouseType, array : [ClickHouseValue]) {
self.type = type;
self.val_number = nil;
self.val_string = nil;
self.val_date = nil;
self.val_array = array;
self.isNull = false;
}
public init(type : ClickHouseType) {
self.type = type;
self.val_number = nil;
self.val_string = nil;
self.val_date = nil;
self.val_array = nil;
self.isNull = true;
}
public var int8 : Int8? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Int8 :
return self.val_number?.int8Value;
default :
return nil;
}
}
public var uint8 : UInt8? {
if self.isNull {
return nil;
}
switch (self.type) {
case .UInt8 :
return self.val_number?.uint8Value;
default :
return nil;
}
}
public var uint16 : UInt16? {
if self.isNull {
return nil;
}
switch (self.type) {
case .UInt8, .UInt16 :
return self.val_number?.uint16Value;
default :
return nil;
}
}
public var int16 : Int16? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Int8, .Int16 :
return self.val_number?.int16Value;
default :
return nil;
}
}
public var uint32 : UInt32? {
if self.isNull {
return nil;
}
switch (self.type) {
case .UInt8, .UInt16, .UInt32 :
return self.val_number?.uint32Value;
default :
return nil;
}
}
public var int32 : Int32? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Int8, .Int16, .Int32 :
return self.val_number?.int32Value;
default :
return nil;
}
}
public var uint64 : UInt64? {
if self.isNull {
return nil;
}
switch (self.type) {
case .UInt8, .UInt16, .UInt32, .UInt64 :
return self.val_number?.uint64Value;
default :
return nil;
}
}
public var int64 : Int64? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Int8, .Int16, .Int32, .Int64 :
return self.val_number?.int64Value;
default :
return nil;
}
}
public var float : Float? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Float32 :
if let n = self.val_number?.floatValue, !n.isNaN && !n.isInfinite {
return n;
} else {
return nil;
}
default :
return nil;
}
}
public var double : Double? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Float32 :
if let n = self.val_number?.floatValue, !n.isNaN && !n.isInfinite {
return Double(n);
} else {
return nil;
}
case .Float64 :
if let n = self.val_number?.doubleValue, !n.isNaN && !n.isInfinite {
return n;
} else {
return nil;
}
default :
return nil;
}
}
public var float32 : Float? {
return self.float;
}
public var float64 : Double? {
return self.double;
}
public var uint : UInt64? {
return self.uint64;
}
public var int : Int64? {
return self.int64;
}
public var date : Date? {
return self.val_date;
}
public var datetime : Date? {
return self.val_date;
}
public var enum8 : String {
return self.string;
}
public var enum16 : String {
return self.string;
}
public var string : String {
if (self.isNull) {
return "NIL";
}
switch (self.type) {
case .String, .FixedString :
return self.val_string!;
case .Int8, .Int16, .Int32, .Int64, .UInt8, .UInt16, .UInt32, .UInt64, .Float32, .Float64 :
return "\(self.val_number!)";
case let .Enum8(variants) :
let v : Int16 = self.val_number!.int16Value;
return variants[v] ?? "Unknown enum";
case let .Enum16(variants) :
let v : Int16 = self.val_number!.int16Value;
return variants[v] ?? "Unknown enum";
case .Date :
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.init(identifier: "en_GB")
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: self.val_date!);
case .DateTime :
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.init(identifier: "en_GB")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.string(from: self.val_date!);
case .Array :
var list = [String]();
for l in self.val_array! {
list.append(l.description);
}
return list.joined(separator: ", ");
default :
return "Unknown";
}
}
public var description : String {
switch (self.type) {
case .String, .FixedString, .Enum8, .Enum16, .Date, .DateTime :
return "'\(self.string)'";
case .Int8, .Int16, .Int32, .Int64, .UInt8, .UInt16, .UInt32, .UInt64, .Float32, .Float64 :
return self.string;
case .Array :
return "[\(self.string)]"
default :
return "Unknown";
}
}
} | 15b2bfe81a9f9cd0b0ebfff5659e2da9 | 23.748344 | 103 | 0.460591 | false | false | false | false |
sleekbyte/tailor | refs/heads/master | src/test/swift/com/sleekbyte/tailor/grammar/ClassesAndStructures.swift | mit | 1 | struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
let someResolution = Resolution()
let someVideoMode = VideoMode()
print("The width of someResolution is \(someResolution.width)")
print("The width of someVideoMode is \(someVideoMode.resolution.width)")
someVideoMode.resolution.width = 1280
print("The width of someVideoMode is now \(someVideoMode.resolution.width)")
let vga = Resolution(width: 640, height: 480)
enum CompassPoint {
case North, South, East, West
}
var currentDirection = CompassPoint.West
let rememberedDirection = currentDirection
currentDirection = .East
if rememberedDirection == .West {
print("The remembered direction is still .West")
}
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
if tenEighty === alsoTenEighty {
print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
}
"PROPERTIES"
class DataImporter {
/*
DataImporter is a class to import data from an external file.
The class is assumed to take a non-trivial amount of time to initialize.
*/
var fileName = "data.txt"
// the DataImporter class would provide data importing functionality here
}
class DataManager {
lazy var importer = DataImporter()
var data = [String]()
// the DataManager class would provide data management functionality here
}
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0, y: 0.0),
size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)
print("square.origin is now at (\(square.origin.x), \(square.origin.y))")
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
struct Cuboid {
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double {
return width * height * depth
}
}
let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
struct SomeStructure {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 1
}
}
enum SomeEnumeration {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 6
}
}
class SomeClass {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 27
}
class var overrideableComputedTypeProperty: Int {
return 107
}
}
struct AudioChannel {
static let thresholdLevel = 10
static var maxInputLevelForAllChannels = 0
var currentLevel: Int = 0 {
didSet {
if currentLevel > AudioChannel.thresholdLevel {
// cap the new audio level to the threshold level
currentLevel = AudioChannel.thresholdLevel
}
if currentLevel > AudioChannel.maxInputLevelForAllChannels {
// store this as the new overall maximum input level
AudioChannel.maxInputLevelForAllChannels = currentLevel
}
}
}
}
@objc final internal class World {
internal var exampleHooks: ExampleHooks {return configuration.exampleHooks }
internal var suiteHooks: SuiteHooks { return configuration.suiteHooks }
}
@objc internal final class World {
internal var exampleHooks: ExampleHooks {return configuration.exampleHooks }
internal var suiteHooks: SuiteHooks { return configuration.suiteHooks }
}
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
}
public subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
}
// declarationModifier before setterClause
nonmutating set {
if _fastPath(_isNative) {
_native[i] = newValue
}
else {
var refCopy = self
refCopy.replace(
subRange: i...i, with: 1, elementsOf: CollectionOfOne(newValue))
}
}
}
| 23f724f8e400258aa8ecb05299430659 | 26.865979 | 150 | 0.650018 | false | false | false | false |
JasonChen2015/Paradise-Lost | refs/heads/master | Paradise Lost/Classes/ViewControllers/Tool/PaintingVC.swift | mit | 3 | //
// PaintingVC.swift
// Paradise Lost
//
// Created by jason on 26/9/2017.
// Copyright © 2017 Jason Chen. All rights reserved.
//
import UIKit
class PaintingVC: UIViewController, PaintingViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var mainView: PaintingView!
var toolView: PaintingToolView!
var colorView: PaintingColorView!
/// flag of current picture whether has been saved
var isCurrentPicSave: Bool = true
// MARK: life cycle
override var prefersStatusBarHidden: Bool {
get {
return true
}
}
override var shouldAutorotate : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return .portrait
}
override func viewDidLoad() {
super.viewDidLoad()
let rect = UIScreen.main.bounds
let toolheigh = rect.height / 13
let colorheight = CGFloat(40)
mainView = PaintingView(frame: rect)
mainView.delegate = self
view.addSubview(mainView)
toolView = PaintingToolView(frame: CGRect(x: 0, y: (rect.height - toolheigh), width: rect.width, height: toolheigh))
toolView.delegate = self
view.addSubview(toolView)
colorView = PaintingColorView(frame: CGRect(x: 0, y: (rect.height - toolheigh - colorheight), width: rect.width, height: colorheight))
colorView.isHidden = true
view.addSubview(colorView)
}
// MARK: PaintingViewDelegate
func exit() {
self.dismiss(animated: false, completion: nil)
}
func savePic() {
savePicToPhotoLibrary(nil)
}
func getPic() {
if (mainView.hasImage && !isCurrentPicSave) {
AlertManager.showTipsWithContinue(self, message: LanguageManager.getToolString(forKey: "paint.getImage.message"), handler: savePicToPhotoLibrary, cHandler: nil)
}
getPicFromPhotoLibrary()
}
func changePenMode() {
if (toolView.currentMode == .pen) {
colorView.isHidden = false
} else {
colorView.isHidden = true
}
}
func changeResizeMode() {
colorView.isHidden = true
}
func changeTextMode() {
colorView.isHidden = true
}
// MARK: UIImagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
mainView.loadImage(rawImage: image)
isCurrentPicSave = false
} else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
mainView.loadImage(rawImage: image)
isCurrentPicSave = false
} else {
AlertManager.showTips(self, message: LanguageManager.getToolString(forKey: "paint.getImage.error"), handler: nil)
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
// MARK: private methods
fileprivate func getPicFromPhotoLibrary() {
let picker = UIImagePickerController()
picker.delegate = self
//picker.allowsEditing = true
picker.sourceType = .photoLibrary
self.present(picker, animated: true, completion: nil)
}
fileprivate func savePicToPhotoLibrary(_ alert: UIAlertAction?) {
if let image = mainView.getImage() {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(PaintingVC.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let _ = error {
// fail
AlertManager.showTips(self, message: LanguageManager.getToolString(forKey: "paint.saveImage.fail"), handler: nil)
} else {
// success
AlertManager.showTips(self, message: LanguageManager.getToolString(forKey: "paint.saveImage.success"), handler: nil)
isCurrentPicSave = true
}
}
}
| 649072251ab9321ada268656b617d75d | 31.328358 | 172 | 0.633887 | false | false | false | false |
alex-d-fox/iDoubtIt | refs/heads/master | iDoubtIt/Code/Preferences.swift | gpl-3.0 | 1 | //
// Preferences.swift
// iDoubtIt
//
// Created by Alexander Fox on 10/12/16.
//
//
import Foundation
import SpriteKit
var soundOn = Pref().Sound()
var isWacky = Pref().Wacky()
var difficulty = Pref().LevelDifficulty()
var background = Pref().BackgroundImage()
var cardCover = Pref().CardCover()
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let prefs = UserDefaults.standard
struct Pref {
func Sound() -> Bool {
if (prefs.object(forKey: "Sound") == nil) {
prefs.set(true, forKey: "Sound")
}
let soundOn = prefs.bool(forKey: "Sound")
return soundOn
}
func Wacky() -> Bool {
if (prefs.object(forKey: "Wacky") == nil) {
prefs.set(false, forKey: "Wacky")
}
let isWacky = prefs.bool(forKey: "Wacky")
return isWacky
}
func LevelDifficulty() -> Int {
if (prefs.object(forKey: "Difficulty") == nil) {
prefs.set(Difficulty.easy.rawValue, forKey: "Difficulty")
}
let difficulty = prefs.integer(forKey: "Difficulty")
return difficulty
}
func BackgroundImage() -> String {
if (prefs.object(forKey: "Background") == nil) {
prefs.setValue(Background.bg_blue.rawValue, forKey: "Background")
}
let background = prefs.string(forKey: "Background")!
return background
}
func CardCover() -> String {
if (prefs.object(forKey: "CardCover") == nil) {
prefs.setValue(cardBack.cardBack_blue4.rawValue, forKey: "CardCover")
}
let cardCover = prefs.string(forKey: "CardCover")!
return cardCover
}
func updateVars() {
soundOn = Sound()
isWacky = Wacky()
difficulty = LevelDifficulty()
background = BackgroundImage()
cardCover = CardCover()
}
}
| 57bef36d1ed692abc1bbd2816a06a045 | 25.888889 | 81 | 0.592975 | false | false | false | false |
yichizhang/SubjectiveCCastroControls_Swift | refs/heads/master | SCCastroControls/SCPlaybackItem.swift | mit | 1 | //
// SCPlaybackItem.swift
// SCCastroControls
//
// Created by Yichi on 4/03/2015.
// Copyright (c) 2015 Subjective-C. All rights reserved.
//
import Foundation
class SCPlaybackItem : NSObject {
var totalTime:NSTimeInterval = 0
var elapsedTime:NSTimeInterval {
set {
_elapsedTime = max(0, min(totalTime, newValue))
}
get {
return _elapsedTime
}
}
private var _elapsedTime:NSTimeInterval = 0
// MARK: Public methods
func stringForElapsedTime() -> String! {
return stringForHours(hoursComponentForTimeInterval(elapsedTime), minutes: minutesComponentForTimeInterval(elapsedTime), seconds: secondsComponentForTimeInterval(elapsedTime))
}
func stringForRemainingTime() -> String! {
let remainingTime = totalTime - elapsedTime
return "-" + stringForHours(hoursComponentForTimeInterval(remainingTime), minutes: minutesComponentForTimeInterval(remainingTime), seconds: secondsComponentForTimeInterval(remainingTime))
}
// MARK: Private methods
private func stringForHours(hours: UInt, minutes: UInt, seconds: UInt) -> String! {
var string:NSString!
if hours > 0 {
string = NSString(format: "%lu:%lu:%02lu", u_long(hours), u_long(minutes), CUnsignedLong(seconds) )
} else {
string = NSString(format: "%lu:%02lu", u_long(minutes), CUnsignedLong(seconds) )
}
return string
}
private func hoursComponentForTimeInterval(timeInterval: NSTimeInterval) -> UInt {
return UInt(timeInterval) / 60 / 60
}
private func minutesComponentForTimeInterval(timeInterval: NSTimeInterval) -> UInt {
return (UInt(timeInterval) / 60) % 60
}
private func secondsComponentForTimeInterval(timeInterval: NSTimeInterval) -> UInt {
return UInt(timeInterval) % 60
}
} | 23606c877738f9f99f57d17cb3e33bb3 | 29.553571 | 189 | 0.74152 | false | false | false | false |
NUKisZ/TestKitchen_1606 | refs/heads/master | TestKitchen/TestKitchen/classes/cookbook/foodMaterial/view/CBMaterialCell.swift | mit | 1 | //
// CBMaterialCell.swift
// TestKitchen
//
// Created by NUK on 16/8/24.
// Copyright © 2016年 NUK. All rights reserved.
//
import UIKit
class CBMaterialCell: UITableViewCell {
var model:CBMaterialTypeModel?{
didSet{
if model != nil {
showData()
}
}
}
func showData(){
//1.删除之前的视图
for oldSub in contentView.subviews{
oldSub.removeFromSuperview()
}
//2.添加子视图
//2.1标题
let titleLabel = UILabel.createLabel(model!.text, font: UIFont.systemFontOfSize(20), textAlignment: .Left, textColor: UIColor.blackColor())
titleLabel.frame = CGRectMake(20, 0, kScreenWidth-20*2, 40)
contentView.addSubview(titleLabel)
//横向间距
let spaceX:CGFloat = 10
//纵向间距
let spaceY:CGFloat = 10
let colNum = 5
//高度
let h:CGFloat = 40
let w = (kScreenWidth-spaceX * CGFloat(colNum+1))/CGFloat(colNum)
let offsetY:CGFloat = 40
//2.2图片
let imageFrame = CGRectMake(spaceX, offsetY, w*2+spaceX, h*2+spaceY)
let imageView = UIImageView(frame: imageFrame)
let url = NSURL(string: (model?.image)!)
imageView.kf_setImageWithURL(url, placeholderImage: dImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
contentView.addSubview(imageView)
//2.3循环创建按钮
if model?.data?.count > 0{
for i in 0..<(model?.data?.count)!{
var btnFrame = CGRectZero
if i < 6{
//前两行的按钮
let row = i / 3
let col = i % 3
btnFrame = CGRectMake(w*2+spaceX*3+CGFloat(col)*(w+spaceX), offsetY+CGFloat(row)*(h+spaceY), w, h)
}else{
//后面几行的按钮
//行和列
let row = (i-6)/5
let col = (i-6)%5
btnFrame = CGRectMake(CGFloat(col)*(w+spaceY)+spaceX, offsetY+2*(h+spaceY)+CGFloat(row)*(h+spaceY), w, h)
}
let btn = CBMaterialBtn.init(frame: btnFrame)
btn.model = model?.data![i]
contentView.addSubview(btn)
}
}
}
class func heigthWithModel(model:CBMaterialTypeModel)->CGFloat{
var h:CGFloat = 0
let offsetY:CGFloat = 40
let spaceY:CGFloat = 10
let btnH:CGFloat = 40
if model.data?.count > 0{
if model.data?.count < 6{
h = offsetY + (btnH+spaceY) * 2
}else{
h = offsetY + (btnH+spaceY) * 2
var rowNum = ((model.data?.count)! - 6)/5
if ((model.data?.count)! - 6) % 5 > 0{
rowNum += 1
}
h += CGFloat(rowNum) * (btnH + spaceY)
}
}
return h
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class CBMaterialBtn:UIControl{
private var titleLabel:UILabel?
//数据 的显示
var model:CBMaterialSubtypeModel?{
didSet{
titleLabel?.text = model?.text
}
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(white: 0.8, alpha: 1.0)
titleLabel = UILabel.createLabel(nil, font: UIFont.systemFontOfSize(17), textAlignment: NSTextAlignment.Center, textColor: UIColor.blackColor())
titleLabel?.frame = bounds
titleLabel?.adjustsFontSizeToFitWidth = true
addSubview(titleLabel!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| b771d8262ddc5556a7e0c9e935f53db4 | 27.520548 | 152 | 0.507685 | false | false | false | false |
MJHee/QRCode | refs/heads/master | QRCode/QRCode/WebViewController.swift | mit | 1 | //
// WebViewController.swift
// QRCode
//
// Created by MJHee on 2017/3/18.
// Copyright © 2017年 MJBaby. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {
var url : String?
override func viewDidLoad() {
super.viewDidLoad()
let str = url! as String
let path = URL(string: str)
let webView = WKWebView(frame: self.view.bounds)
webView.load(URLRequest(url: path!))
webView.navigationDelegate = self
self.view.addSubview(webView)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.title = webView.title
}
}
| ff92747f2e4e486942be90e8b6b5fb1f | 22.483871 | 77 | 0.625 | false | false | false | false |
LampshadeSoftware/TheWordGame | refs/heads/master | TheWordGame/TheWordGame/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// TheWordGame
//
// Created by Daniel McCrystal on 4/26/17.
// Copyright © 2017 Lampshade Software. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Save.loadSaveData()
// Save.resetData()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
Save.writeSaveData()
if #available(iOS 10.0, *) {
self.saveContext()
} else {
// Fallback on earlier versions
}
}
// MARK: - Core Data stack
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "TheWordGame")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
@available(iOS 10.0, *)
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved fucking error \(nserror), \(nserror.userInfo)")
}
}
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask(rawValue: UIInterfaceOrientationMask.portrait.rawValue)
}
}
| b77bc111d0074916d7f660854bfa06f5 | 46.878505 | 285 | 0.680851 | false | false | false | false |
wireapp/wire-ios | refs/heads/develop | Wire-iOS Tests/Mocks/MockSelfLegalHoldSubject.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
final class MockLegalHoldDataSource: NSObject {
var legalHoldRequest: LegalHoldRequest?
var needsToAcknowledgeLegalHoldStatus: Bool = false
}
extension MockUser: SelfLegalHoldSubject {
public var needsToAcknowledgeLegalHoldStatus: Bool {
return legalHoldDataSource.needsToAcknowledgeLegalHoldStatus
}
public var legalHoldStatus: UserLegalHoldStatus {
if isUnderLegalHold {
return .enabled
} else if let request = legalHoldDataSource.legalHoldRequest {
return .pending(request)
} else {
return .disabled
}
}
public func acknowledgeLegalHoldStatus() {
legalHoldDataSource.needsToAcknowledgeLegalHoldStatus = false
}
public func userDidAcceptLegalHoldRequest(_ request: LegalHoldRequest) {
legalHoldDataSource.legalHoldRequest = nil
isUnderLegalHold = true
}
public func userDidReceiveLegalHoldRequest(_ request: LegalHoldRequest) {
legalHoldDataSource.legalHoldRequest = request
}
public func legalHoldRequestWasCancelled() {
legalHoldDataSource.legalHoldRequest = nil
}
func requestLegalHold() {
let prekey = LegalHoldRequest.Prekey(id: 65535, key: Data(base64Encoded: "pQABARn//wKhAFggHsa0CszLXYLFcOzg8AA//E1+Dl1rDHQ5iuk44X0/PNYDoQChAFgg309rkhG6SglemG6kWae81P1HtQPx9lyb6wExTovhU4cE9g==")!)
legalHoldDataSource.legalHoldRequest = LegalHoldRequest(target: UUID(), requester: UUID(), clientIdentifier: "eca3c87cfe28be49", lastPrekey: prekey)
}
}
| 88853771174b602b2db6489fe70f190f | 34.169231 | 202 | 0.734471 | false | false | false | false |
1457792186/JWSwift | refs/heads/master | 熊猫TV/XMTV/Classes/Main/Controller/BaseAllLivingVC.swift | apache-2.0 | 2 | //
// BaseAllLivingVC.swift
// XMTV
//
// Created by Mac on 2017/1/18.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class BaseAllLivingVC: BaseVC {
var baseVM: BaseVM!
lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.sectionInset = UIEdgeInsets(top: kItemMargin, left: kItemMargin, bottom: 0, right: kItemMargin)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: NormalCellID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK: -
extension BaseAllLivingVC {
override func setupUI() {
contentView = collectionView
view.addSubview(collectionView)
super.setupUI()
}
}
// MARK: - loadData
extension BaseAllLivingVC {
func loadData() {}
}
// MARK: - UICollectionView代理数据源方法
extension BaseAllLivingVC : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if baseVM.anchorGroups.count > 0 {
return baseVM.anchorGroups[section].anchors.count
} else {
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NormalCellID, for: indexPath) as! CollectionNormalCell
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
}
extension BaseAllLivingVC : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// anchor.isVertical == 0 ? pushNormalRoomVc(anchor) : presentShowRoomVc(anchor)
}
// private func presentShowRoomVc(_ anchor : AnchorModel) {
// let showVc = ShowRoomVC()
// showVc.anchor = anchor
// present(showVc, animated: true, completion: nil)
// }
//
// private func pushNormalRoomVc(_ anchor : AnchorModel) {
// let normalVc = NormalRoomVC()
// normalVc.anchor = anchor
// navigationController?.pushViewController(normalVc, animated: true)
// }
}
| ce96a154881942654f68c259e8a6638b | 32.688889 | 129 | 0.666227 | false | false | false | false |
jiecao-fm/SwiftTheme | refs/heads/master | Demo/GlobalPicker.swift | mit | 1 | //
// GlobalPicker.swift
// Demo
//
// Created by Gesen on 16/3/1.
// Copyright © 2016年 Gesen. All rights reserved.
//
import SwiftTheme
enum GlobalPicker {
static let backgroundColor: ThemeColorPicker = ["#fff", "#fff", "#fff", "#292b38"]
static let textColor: ThemeColorPicker = ["#000", "#000", "#000", "#ECF0F1"]
static let barTextColors = ["#FFF", "#000", "#FFF", "#FFF"]
static let barTextColor = ThemeColorPicker.pickerWithColors(barTextColors)
static let barTintColor: ThemeColorPicker = ["#EB4F38", "#F4C600", "#56ABE4", "#01040D"]
}
| a853b263d53570ab797dad6fb145ae42 | 30.888889 | 92 | 0.651568 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Controller/UI/Product/views/SLVProductInfo3Cell.swift | mit | 1 | //
// SLVProductInfo3Cell.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 7..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
/*
판매자/스타일/하자/엑세사리/추천착샷/비슷한 상품/코멘트 타이틀 셀
*/
class SLVProductInfo3Cell: UITableViewCell {
@IBOutlet weak var mainTitleLabel: UILabel!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet weak var moreButton: UIButton!
var cellIndex = 0
override public func awakeFromNib() {
super.awakeFromNib()
}
//TODO: 추후 처리할 것 ....
@IBAction func touchMore(_ sender: Any) {
if cellIndex == 13 {//추천 착용 사진 더보기
}
else if cellIndex == 15 {//비슷한 상품
}
}
}
| acc53707cd9b124481fce613edca6ec5 | 19 | 55 | 0.589189 | false | false | false | false |
memexapp/memex-swift-sdk | refs/heads/master | Sources/DecimalNumberTransform.swift | mit | 1 |
import Foundation
import ObjectMapper
class DecimalNumberTransform: TransformType {
typealias Object = NSDecimalNumber
typealias JSON = Any
init() {}
func transformFromJSON(_ value: Any?) -> NSDecimalNumber? {
if let value = value {
let string = "\(value)"
return NSDecimalNumber(string: string)
}
return nil
}
func transformToJSON(_ value: NSDecimalNumber?) -> Any? {
if let value = value {
return value.stringValue as AnyObject?
}
return nil
}
}
| 4c858d6fe0c5c8afdc870ab38a78975b | 18.923077 | 61 | 0.65251 | false | false | false | false |
lantun/ThreeBall | refs/heads/master | ThreeBall/ViewController.swift | mit | 1 | //
// ViewController.swift
// ThreeBall
//
// Created by LanTun on 16/2/13.
// Copyright © 2016年 LanTun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var waittingView:UIView! // 动画view
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor(red: 0.96470588235294119, green: 0.36470588235294116, blue: 0.18823529411764706, alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playAction(sender: AnyObject) {
if (waittingView != nil){
waittingView.removeFromSuperview()
}
waittingView = UIView(frame: CGRectMake(0,0,200,200))
waittingView.center = self.view.center
waittingView.backgroundColor = UIColor.clearColor()
let repeatcount:Float = 6*20
let timeDuration:NSTimeInterval = 3.4
let s3:CGFloat = sqrt(3.0)
// 圆半径
let radius:CGFloat = 9
// 圆的距离
let distance: CGFloat = radius/5
// 六芒星阵的边长
let lineWidth:CGFloat = 2*radius
let path1 = UIBezierPath()
let center = CGPointMake(100, 100)
path1.moveToPoint(CGPointMake(center.x+lineWidth/2, center.y-s3*lineWidth/2))
// path1.addLineToPoint(CGPointMake(center.x, center.y-s3*lineWidth))2
// path1.addLineToPoint(CGPointMake(center.x-lineWidth/2, center.y-s3*lineWidth/2))3
// path1.addLineToPoint(CGPointMake(center.x-lineWidth*3/2, center.y-s3*lineWidth/2))4
// path1.addLineToPoint(CGPointMake(center.x-lineWidth, center.y))5
// path1.addLineToPoint(CGPointMake(center.x-lineWidth*3/2, center.y+s3*lineWidth/2))6
// path1.addLineToPoint(CGPointMake(center.x-lineWidth/2, center.y+s3*lineWidth/2))7
// path1.addLineToPoint(CGPointMake(center.x, center.y+s3*lineWidth))8
// path1.addLineToPoint(CGPointMake(center.x+lineWidth/2, center.y+s3*lineWidth/2))9
// path1.addLineToPoint(CGPointMake(center.x+lineWidth*3/2, center.y+s3*lineWidth/2))10
// path1.addLineToPoint(CGPointMake(center.x+lineWidth, center.y))11
// path1.addLineToPoint(CGPointMake(center.x+lineWidth*3/2, center.y-s3*lineWidth/2))12
path1.addCurveToPoint(CGPointMake(center.x-lineWidth/2, center.y-s3*lineWidth/2), controlPoint1: CGPointMake(center.x, center.y-s3*lineWidth), controlPoint2: CGPointMake(center.x, center.y-s3*lineWidth))
path1.addCurveToPoint(CGPointMake(center.x-lineWidth, center.y), controlPoint1: CGPointMake(center.x-lineWidth*3/2, center.y-s3*lineWidth/2), controlPoint2: CGPointMake(center.x-lineWidth*3/2, center.y-s3*lineWidth/2))
path1.addCurveToPoint(CGPointMake(center.x-lineWidth/2, center.y+s3*lineWidth/2), controlPoint1: CGPointMake(center.x-lineWidth*3/2, center.y+s3*lineWidth/2), controlPoint2: CGPointMake(center.x-lineWidth*3/2, center.y+s3*lineWidth/2))
path1.addCurveToPoint(CGPointMake(center.x+lineWidth/2, center.y+s3*lineWidth/2), controlPoint1: CGPointMake(center.x, center.y+s3*lineWidth), controlPoint2: CGPointMake(center.x, center.y+s3*lineWidth))
path1.addCurveToPoint(CGPointMake(center.x+lineWidth, center.y), controlPoint1: CGPointMake(center.x+lineWidth*3/2, center.y+s3*lineWidth/2), controlPoint2: CGPointMake(center.x+lineWidth*3/2, center.y+s3*lineWidth/2))
path1.addCurveToPoint(CGPointMake(center.x+lineWidth/2, center.y-s3*lineWidth/2), controlPoint1: CGPointMake(center.x+lineWidth*3/2, center.y-s3*lineWidth/2), controlPoint2: CGPointMake(center.x+lineWidth*3/2, center.y-s3*lineWidth/2))
let keyframeAnimation1=CAKeyframeAnimation(keyPath: "position")
keyframeAnimation1.path = path1.CGPath
keyframeAnimation1.repeatCount = repeatcount/6
keyframeAnimation1.removedOnCompletion = false
keyframeAnimation1.duration = timeDuration
keyframeAnimation1.cumulative = false
keyframeAnimation1.fillMode = kCAFillModeForwards
keyframeAnimation1.timingFunction=CAMediaTimingFunction(name: "linear")
let circle1 = UIView()
circle1.frame = CGRectMake(0, 0, radius*2, radius*2)
circle1.backgroundColor = UIColor.whiteColor()
circle1.layer.cornerRadius = radius
circle1.layer.masksToBounds = true
circle1.layer.addAnimation(keyframeAnimation1, forKey: "position")
waittingView.addSubview(circle1)
// 换成两个圆
let sectionView = UIView()
sectionView.frame = CGRectMake(0, 0, radius*4+distance*2, radius*2)
sectionView.backgroundColor = UIColor.clearColor()
// 左边的圆
let circle2 = UIView()
circle2.frame = CGRectMake(0, 0, radius*2, radius*2)
circle2.backgroundColor = UIColor.whiteColor()
circle2.layer.cornerRadius = radius
circle2.layer.masksToBounds = true
sectionView.addSubview(circle2)
// 右边的圆
let circle3 = UIView()
circle3.frame = CGRectMake(radius*2+distance*2, 0, radius*2, radius*2)
circle3.backgroundColor = UIColor.whiteColor()
circle3.layer.cornerRadius = radius
circle3.layer.masksToBounds = true
sectionView.addSubview(circle3)
// 旋转整体 120度/0.5秒
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = (CGFloat)(120/360*(2*M_PI))
rotationAnimation.duration = timeDuration/6.0
rotationAnimation.additive = true
rotationAnimation.cumulative = true
rotationAnimation.repeatCount = repeatcount
rotationAnimation.fillMode = kCAFillModeForwards
rotationAnimation.removedOnCompletion = false
rotationAnimation.timingFunction = CAMediaTimingFunction(name: "linear")
let path2 = UIBezierPath(arcCenter: center, radius: radius*0.5, startAngle: (CGFloat)(4/6*M_PI), endAngle: (CGFloat)(-1*M_PI-2/6*M_PI), clockwise: false)
let keyframeAnimation2=CAKeyframeAnimation(keyPath: "position")
keyframeAnimation2.path = path2.CGPath
keyframeAnimation2.repeatCount = repeatcount/6
keyframeAnimation2.removedOnCompletion = false
keyframeAnimation2.duration = timeDuration
keyframeAnimation2.repeatDuration = 0
keyframeAnimation2.fillMode = kCAFillModeForwards
keyframeAnimation2.timingFunction=CAMediaTimingFunction(name: "linear")
sectionView.transform = CGAffineTransformMakeRotation((CGFloat)(30/360*M_PI))
sectionView.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
sectionView.layer.addAnimation(keyframeAnimation2, forKey: "keyframeAnimation")
waittingView.addSubview(sectionView)
self.view.addSubview(waittingView)
}
}
| 80f9de6fc5592fc2516e9fb3bf842d9a | 47.932432 | 243 | 0.678956 | false | false | false | false |
egnwd/ic-bill-hack | refs/heads/master | quick-split/quick-split/FriendCollectionViewCell.swift | mit | 1 | //
// FriendCollectionViewCell.swift
// quick-split
//
// Created by Elliot Greenwood on 02.20.2016.
// Copyright © 2016 stealth-phoenix. All rights reserved.
//
import UIKit
class FriendCollectionViewCell: UICollectionViewCell {
let cellSize = CGSize(width: 75, height: 100)
let defaultColour = UIColor.clearColor()
var name: UILabel = UILabel()
var avatar: UIImageView = UIImageView()
var friend: Friend?
var isChosen = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func populateWithFriend(friend: Friend) {
self.friend = friend
let imageLength = 64
let imageX = (Int(cellSize.width) - imageLength) / 2
avatar = UIImageView(frame: CGRect(x: imageX, y: 0, width: imageLength, height: imageLength))
avatar.image = friend.picture
let lyr = avatar.layer
lyr.masksToBounds = true
lyr.cornerRadius = avatar.bounds.size.width / 2
self.addSubview(avatar)
name = UILabel(frame: CGRect(x: 0, y: imageLength+10, width: Int(cellSize.width), height: 24))
name.text = friend.name
name.textAlignment = .Center
self.addSubview(name)
}
func highlightCell(withColour colour: UIColor) {
self.avatar.layer.borderWidth = 4
self.avatar.layer.borderColor = colour.CGColor
friend!.colour = colour
}
func unhighlightCell() {
self.avatar.layer.borderWidth = 0
friend!.colour = defaultColour
}
}
| 18468f01554716ac73ec6443de21ba28 | 26.576923 | 98 | 0.691771 | false | false | false | false |
GoodMorningCody/EverybodySwift | refs/heads/master | WeeklyToDo/WeeklyToDo/Weekly.swift | mit | 1 | //
// Weekly.swift
// WeeklyToDo
//
// Created by Cody on 2015. 1. 22..
// Copyright (c) 2015년 TIEKLE. All rights reserved.
//
import Foundation
class Weekly {
class func weekday(index : Int, useStandardFormat : Bool) -> String {
// index에 해당하는 요일을 다국어로 변환한 후 반환
// ie. index =0 is today
var dateFormatter = NSDateFormatter()
if useStandardFormat==false {
dateFormatter.locale = NSLocale.currentLocale()
}
return dateFormatter.weekdaySymbols[index] as String
}
class func weekdayFromNow(offset : Int, useStandardFormat : Bool) -> String {
var dateFormatter = NSDateFormatter()
if useStandardFormat==false {
dateFormatter.locale = NSLocale.currentLocale()
}
dateFormatter.dateFormat = "EEEE"
var date = NSDate(timeIntervalSinceNow: 60.0*60.0*24.0 * Double(offset))
return dateFormatter.stringFromDate(date)
}
class func dateFromNow(toSymbol: String) -> NSDate? {
var symbols = NSDateFormatter().weekdaySymbols + NSDateFormatter().weekdaySymbols as [String]
var symbolOnToday = weekdayFromNow(0, useStandardFormat:false)
var length = 0
var foundedStartIndex = false
for symbol in symbols {
if symbol==symbolOnToday {
foundedStartIndex = true
}
else if foundedStartIndex==true {
++length
}
if symbol == toSymbol {
break
}
}
var component = NSCalendar.currentCalendar().components(
NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay,
fromDate: NSDate(timeIntervalSinceNow: Double(60*60*24*length))
)
return NSCalendar.currentCalendar().dateFromComponents(component)
}
// class func lengthFromNow(toSymbol:String) -> Int {
// var symbols = NSDateFormatter().weekdaySymbols + NSDateFormatter().weekdaySymbols
// var symbolOnToday = weekdayFromNow(0, useStandardFormat:false)
// var length = 0
// var foundedStartIndex = false
// for symbol in symbols {
// if symbol as String==symbolOnToday {
// foundedStartIndex = true
// }
// else if foundedStartIndex==true {
// ++length
// }
//
// if symbol as String == toSymbol {
// break
// }
// }
// return length
// }
} | 54bdbeee3d2d5b29bbcdc7f7ab3ebd6e | 31.7875 | 112 | 0.576659 | false | false | false | false |
lojals/curiosity_reader | refs/heads/master | curiosity_reader/curiosity_reader/src/components/ArticleComponent.swift | gpl-2.0 | 1 | //
// ArticleComponent.swift
// curiosity_reader
//
// Created by Jorge Raul Ovalle Zuleta on 5/16/15.
// Copyright (c) 2015 Olinguito. All rights reserved.
//
import UIKit
@objc protocol ArticleComponentDelegate{
optional func tapInArticle()
}
class ArticleComponent: UIView {
var tapGesture:UITapGestureRecognizer!
var delegate:ArticleComponentDelegate!
var question:UILabel!
var data:JSON!
init(frame: CGRect, data:JSON) {
super.init(frame: frame)
self.data = data
self.backgroundColor = UIColor.whiteColor()
self.layer.borderColor = UIColor.themeGreyMedium().CGColor
self.layer.borderWidth = 1
tapGesture = UITapGestureRecognizer(target: self, action: Selector("goToArticle:"))
self.addGestureRecognizer(tapGesture)
question = UILabel(frame: CGRectMake(20, 5, frame.width-50, 70))
question.font = UIFont.fontRegular(17.5)
question.numberOfLines = 0
question.text = "¿Cuál es el nombre del director de Star War Episodio VII: The Force Awakeness?"
question.textAlignment = NSTextAlignment.Left
question.textColor = UIColor.blackColor()
self.addSubview(question)
var tag = TagComponent(tag: "Ciencia ficción", icon: UIImage(named: "sfi"))
tag.frame.origin.x = 20
tag.frame.origin.y = question.frame.maxY + 5
self.addSubview(tag)
}
func goToArticle(sender:UIView){
delegate.tapInArticle!()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 2d931b0c8696b945787ec3f4a0ef682f | 29.773585 | 104 | 0.663397 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet | refs/heads/good | SwiftGL-Demo/Source/Common/TextureShader.swift | mit | 1 | //
// TextureShader.swift
// SwiftGL
//
// Created by jerry on 2016/3/13.
// Copyright © 2016年 Jerry Chan. All rights reserved.
//
import SwiftGL
struct TextureMappingVertice{
var position:Vec4
var textureUV:Vec2
}
enum ImageMode{
case fill
case fit
}
class TextureShader: GLShaderWrapper {
var imgWidth:Float = 0,imgHeight:Float = 0
init() {
super.init(name:"RenderTexture")
//
addAttribute("position", type: Vec4.self)
addAttribute("textureUV", type: Vec2.self)
//
addUniform("MVP")
addUniform("imageTexture")
addUniform("alpha")
}
func setSize(_ width:Float,height:Float)
{
initVertex(width, height: height)
}
func genImageVertices(_ leftTop:Vec4,rightBottom:Vec4)
{
let ltx = leftTop.x / imgWidth
let lty = leftTop.y / imgHeight
let rbx = rightBottom.x / imgWidth
let rby = rightBottom.y / imgHeight
let v1 = TextureMappingVertice(position: Vec4(leftTop.x,leftTop.y), textureUV: Vec2(ltx,lty))
let v2 = TextureMappingVertice(position: Vec4(rightBottom.x,leftTop.y), textureUV: Vec2(rbx,lty))
let v3 = TextureMappingVertice(position: Vec4(leftTop.x,rightBottom.y), textureUV: Vec2(ltx,rby))
let v4 = TextureMappingVertice(position:Vec4(rightBottom.x,rightBottom.y), textureUV: Vec2(rbx,rby))
imageVertices = [v1,v2,v3,v4]
}
func genImageVertices(_ position:Vec4,size:Vec2)
{
imageVertices[0].position = position
imageVertices[1].position = Vec4(position.x+size.x,position.y)
imageVertices[2].position = Vec4(position.x,position.y+size.y)
imageVertices[3].position = Vec4(position.x+size.x,position.y+size.y)
}
var imageVertices:[TextureMappingVertice] = []
// var squareVertices:[GLfloat] = [
// 0, 0,
// 200, 0,
// 0, 200,
// 200, 200,
// ]
//
// let textureVertices:[GLfloat] = [
// 0.0, 1.0,
// 1.0, 1.0,
// 0.0, 0.0,
// 1.0, 0.0,
//
// ]
func initVertex(_ width:Float,height:Float)
{
imgWidth = width
imgHeight = height
imageVertices.append(TextureMappingVertice(position: Vec4(0,0), textureUV: Vec2(0,0)))
imageVertices.append(TextureMappingVertice(position: Vec4(width,0), textureUV: Vec2(1,0)))
imageVertices.append(TextureMappingVertice(position: Vec4(0,height), textureUV: Vec2(0,1)))
imageVertices.append(TextureMappingVertice(position: Vec4(width,height), textureUV: Vec2(1,1)))
}
func bindImageTexture(_ texture:Texture,alpha:Float,leftTop:Vec4,rightBottom:Vec4)
{
shader.bind(getUniform("imageTexture")!,texture , index: 2)
shader.bind(getUniform("alpha")!, alpha)
shader.useProgram()
genImageVertices(leftTop, rightBottom: rightBottom)
bindVertexs(imageVertices)
}
func bindImageTexture(_ texture:Texture,alpha:Float,position:Vec4,size:Vec2)
{
shader.bind(getUniform("imageTexture")!,texture , index: 2)
shader.bind(getUniform("alpha")!, alpha)
shader.useProgram()
genImageVertices(position, size: size)
//genImageVertices(leftTop, rightBottom: rightBottom)
bindVertexs(imageVertices)
}
func bindImageTexture(_ texture:Texture,alpha:Float)
{
bindImageTexture(texture, alpha: alpha, position: Vec4(0,0), size: Vec2(imgWidth,imgHeight))
}
}
| 45381a0ea5ef07bec8977321a2be481b | 30.565217 | 108 | 0.613774 | false | false | false | false |
notohiro/NowCastMapView | refs/heads/master | NowCastMapView/Overlay.swift | mit | 1 | //
// Overlay.swift
// NowCastMapView
//
// Created by Hiroshi Noto on 6/20/15.
// Copyright (c) 2015 Hiroshi Noto. All rights reserved.
//
import Foundation
import MapKit
public class Overlay: NSObject, MKOverlay {
public var coordinate: CLLocationCoordinate2D {
let latitude = (Constants.originLatitude + Constants.terminalLatitude) / 2
let longitude = (Constants.originLongitude + Constants.terminalLongitude) / 2
return CLLocationCoordinate2DMake(latitude, longitude)
}
public var boundingMapRect: MKMapRect {
let origin = MKMapPoint(CLLocationCoordinate2DMake(Constants.originLatitude, Constants.originLongitude))
let end = MKMapPoint(CLLocationCoordinate2DMake(Constants.terminalLatitude, Constants.terminalLongitude))
let size = MKMapSize(width: end.x - origin.x, height: end.y - origin.y)
return MKMapRect(x: origin.x, y: origin.y, width: size.width, height: size.height)
}
public func intersects(_ mapRect: MKMapRect) -> Bool {
return mapRect.intersects(TileModel.serviceAreaMapRect)
}
}
| b74a47407ff08421b7b30b0c8f9740ed | 34.666667 | 110 | 0.737383 | false | false | false | false |
OctMon/OMExtension | refs/heads/master | OMExtension/OMExtension/Source/UIKit/OMTextView.swift | mit | 1 | //
// OMTextView.swift
// OMExtension
//
// The MIT License (MIT)
//
// Copyright (c) 2016 OctMon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
#if os(iOS)
import UIKit
public extension OMExtension where OMBase: UITextView {
func addTextLimit(length: Int, limitHandler: (() -> Void)? = nil) {
NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextViewTextDidChange, object: nil, queue: OperationQueue.main) { (notification) in
if (((self.base.text! as NSString).length > length) && self.base.markedTextRange == nil) {
self.base.text = (self.base.text! as NSString).substring(to: length)
limitHandler?()
}
}
}
func addDoneButton(barStyle: UIBarStyle = .default, title: String? = "完成") {
let toolbar = UIToolbar()
toolbar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(title: title, style: .done, target: self, action: #selector(UITextView.doneAction))]
toolbar.barStyle = barStyle
toolbar.sizeToFit()
base.inputAccessoryView = toolbar
}
}
public extension UITextView {
@objc fileprivate func doneAction() { endEditing(true) }
}
#endif
| 6faf85d30612745ac194922787e88dcd | 36.138462 | 205 | 0.678542 | false | false | false | false |
ben-ng/swift | refs/heads/master | test/IDE/complete_value_expr.swift | apache-2.0 | 1 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_2 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_3 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_4 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_DOT_5 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_NO_DOT_1 | %FileCheck %s -check-prefix=FOO_OBJECT_NO_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_OBJECT_NO_DOT_2 | %FileCheck %s -check-prefix=FOO_OBJECT_NO_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_STRUCT_DOT_1 | %FileCheck %s -check-prefix=FOO_STRUCT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FOO_STRUCT_NO_DOT_1 | %FileCheck %s -check-prefix=FOO_STRUCT_NO_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_FUNC_0 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_FUNC_0
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_FUNC_1 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_FUNC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_FUNC_2 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_FUNC_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_VARARG_FUNC_0 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_VARARG_FUNC_0
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_VARARG_FUNC_1 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_VARARG_FUNC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_VARARG_FUNC_2 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_VARARG_FUNC_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_OVERLOADED_FUNC_1 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_OVERLOADED_FUNC_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IMPLICITLY_CURRIED_OVERLOADED_FUNC_2 | %FileCheck %s -check-prefix=IMPLICITLY_CURRIED_OVERLOADED_FUNC_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_1 | %FileCheck %s -check-prefix=IN_SWITCH_CASE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_2 | %FileCheck %s -check-prefix=IN_SWITCH_CASE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_3 | %FileCheck %s -check-prefix=IN_SWITCH_CASE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_SWITCH_CASE_4 | %FileCheck %s -check-prefix=IN_SWITCH_CASE
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VF1 | %FileCheck %s -check-prefix=VF1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VF2 | %FileCheck %s -check-prefix=VF2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BASE_MEMBERS | %FileCheck %s -check-prefix=BASE_MEMBERS
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=BASE_MEMBERS_STATIC | %FileCheck %s -check-prefix=BASE_MEMBERS_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_NO_DOT_1 | %FileCheck %s -check-prefix=PROTO_MEMBERS_NO_DOT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_NO_DOT_2 | %FileCheck %s -check-prefix=PROTO_MEMBERS_NO_DOT_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_NO_DOT_3 | %FileCheck %s -check-prefix=PROTO_MEMBERS_NO_DOT_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_1 | %FileCheck %s -check-prefix=PROTO_MEMBERS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_2 | %FileCheck %s -check-prefix=PROTO_MEMBERS_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_3 | %FileCheck %s -check-prefix=PROTO_MEMBERS_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTO_MEMBERS_4 | %FileCheck %s -check-prefix=PROTO_MEMBERS_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_0 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_0
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_2 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_3 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_4 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_5 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_6 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_6
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_7 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_7
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_8 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_8
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_9 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_9
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_10 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_10
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_11 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_11
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_12 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_12
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_2 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_VARARG_FUNCTION_CALL_3 | %FileCheck %s -check-prefix=INSIDE_VARARG_FUNCTION_CALL_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_OVERLOADED_FUNCTION_CALL_1 | %FileCheck %s -check-prefix=INSIDE_OVERLOADED_FUNCTION_CALL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1 | %FileCheck %s -check-prefix=INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_2 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_3 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_4 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_5 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_FUNC_PARAM_6 | %FileCheck %s -check-prefix=RESOLVE_FUNC_PARAM_6
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_CONSTRUCTOR_PARAM_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_CONSTRUCTOR_PARAM_2 | %FileCheck %s -check-prefix=RESOLVE_CONSTRUCTOR_PARAM_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_CONSTRUCTOR_PARAM_3 | %FileCheck %s -check-prefix=RESOLVE_CONSTRUCTOR_PARAM_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_PAREN_PATTERN_1 | %FileCheck %s -check-prefix=FUNC_PAREN_PATTERN_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_PAREN_PATTERN_2 | %FileCheck %s -check-prefix=FUNC_PAREN_PATTERN_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=FUNC_PAREN_PATTERN_3 | %FileCheck %s -check-prefix=FUNC_PAREN_PATTERN_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CHAINED_CALLS_1 | %FileCheck %s -check-prefix=CHAINED_CALLS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CHAINED_CALLS_2 | %FileCheck %s -check-prefix=CHAINED_CALLS_2
// Disabled because we aren't handling failures well.
// FIXME: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CHAINED_CALLS_3 | %FileCheck %s -check-prefix=CHAINED_CALLS_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_1 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_2 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_3 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_4 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_5 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_ERROR_1 | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_ERROR_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_1_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_1_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_2_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_2_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_3_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_3_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_4_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_4_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_GENERIC_PARAMS_5_STATIC | %FileCheck %s -check-prefix=RESOLVE_GENERIC_PARAMS_5_STATIC
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_1 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_2 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_3 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_UNSOLVED_VARIABLES_4 | %FileCheck %s -check-prefix=TC_UNSOLVED_VARIABLES_4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RESOLVE_MODULES_1 | %FileCheck %s -check-prefix=RESOLVE_MODULES_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INTERPOLATED_STRING_1 | %FileCheck %s -check-prefix=FOO_OBJECT_DOT1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_WILLCONFORMP1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_WILLCONFORMP1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DIDCONFORMP2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DIDCONFORMP2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DIDCONFORMP3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DIDCONFORMP3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_GENERICP1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_GENERICP1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_GENERICP2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_GENERICP2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_GENERICP3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_GENERICP3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE1_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE1_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_P1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE3_SUB | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME_SUB
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONCRETE4 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_CONSTRAINED_GENERIC_3_SUB | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME_SUB
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE2_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INSIDE_CONCRETE2_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_ONLYME
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_TA_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_TA
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_TA_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_TA
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INIT_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_INIT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_INIT_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_INIT_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4_DOT_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4_DOT_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_P4_T_DOT_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_P4_T_DOT_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_UNUSABLE_EXISTENTIAL | %FileCheck %s -check-prefix=PROTOCOL_EXT_UNUSABLE_EXISTENTIAL
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DEDUP_1 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DEDUP_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DEDUP_2 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DEDUP_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=PROTOCOL_EXT_DEDUP_3 | %FileCheck %s -check-prefix=PROTOCOL_EXT_DEDUP_3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=THROWS1 | %FileCheck %s -check-prefix=THROWS1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=THROWS2 | %FileCheck %s -check-prefix=THROWS2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_THROWS1 | %FileCheck %s -check-prefix=MEMBER_THROWS1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_THROWS2 | %FileCheck %s -check-prefix=MEMBER_THROWS2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MEMBER_THROWS3 | %FileCheck %s -check-prefix=MEMBER_THROWS3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INIT_THROWS1 | %FileCheck %s -check-prefix=INIT_THROWS1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE1 > %t.autoclosure1
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE2 > %t.autoclosure2
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE3 > %t.autoclosure3
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure3
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE4 > %t.autoclosure4
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure4
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AUTOCLOSURE5 > %t.autoclosure5
// RUN: %FileCheck %s -check-prefix=AUTOCLOSURE_STRING < %t.autoclosure5
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_1 | %FileCheck %s -check-prefix=GENERIC_TYPEALIAS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=GENERIC_TYPEALIAS_2 | %FileCheck %s -check-prefix=GENERIC_TYPEALIAS_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DEPRECATED_1 | %FileCheck %s -check-prefix=DEPRECATED_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DOT_EXPR_NON_NOMINAL_1 | %FileCheck %s -check-prefix=DOT_EXPR_NON_NOMINAL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=DOT_EXPR_NON_NOMINAL_2 | %FileCheck %s -check-prefix=DOT_EXPR_NON_NOMINAL_2
// Test code completion of expressions that produce a value.
struct FooStruct {
lazy var lazyInstanceVar = 0
var instanceVar = 0
mutating
func instanceFunc0() {}
mutating
func instanceFunc1(_ a: Int) {}
mutating
func instanceFunc2(_ a: Int, b: inout Double) {}
mutating
func instanceFunc3(_ a: Int, _: (Float, Double)) {}
mutating
func instanceFunc4(_ a: Int?, b: Int!, c: inout Int?, d: inout Int!) {}
mutating
func instanceFunc5() -> Int? {}
mutating
func instanceFunc6() -> Int! {}
mutating
func instanceFunc7(a a: Int) {}
mutating
func instanceFunc8(_ a: (Int, Int)) {}
mutating
func instanceFunc9(@autoclosure a: () -> Int) {}
mutating
func varargInstanceFunc0(_ v: Int...) {}
mutating
func varargInstanceFunc1(_ a: Float, v: Int...) {}
mutating
func varargInstanceFunc2(_ a: Float, b: Double, v: Int...) {}
mutating
func overloadedInstanceFunc1() -> Int {}
mutating
func overloadedInstanceFunc1() -> Double {}
mutating
func overloadedInstanceFunc2(_ x: Int) -> Int {}
mutating
func overloadedInstanceFunc2(_ x: Double) -> Int {}
mutating
func builderFunc1(_ a: Int) -> FooStruct { return self }
subscript(i: Int) -> Double {
get {
return Double(i)
}
set(v) {
instanceVar = i
}
}
subscript(i: Int, j: Int) -> Double {
get {
return Double(i + j)
}
set(v) {
instanceVar = i + j
}
}
mutating
func selectorVoidFunc1(_ a: Int, b x: Float) {}
mutating
func selectorVoidFunc2(_ a: Int, b x: Float, c y: Double) {}
mutating
func selectorVoidFunc3(_ a: Int, b _: (Float, Double)) {}
mutating
func selectorStringFunc1(_ a: Int, b x: Float) -> String {}
mutating
func selectorStringFunc2(_ a: Int, b x: Float, c y: Double) -> String {}
mutating
func selectorStringFunc3(_ a: Int, b _: (Float, Double)) -> String{}
struct NestedStruct {}
class NestedClass {}
enum NestedEnum {}
// Cannot declare a nested protocol.
// protocol NestedProtocol {}
typealias NestedTypealias = Int
static var staticVar: Int = 4
static func staticFunc0() {}
static func staticFunc1(_ a: Int) {}
static func overloadedStaticFunc1() -> Int {}
static func overloadedStaticFunc1() -> Double {}
static func overloadedStaticFunc2(_ x: Int) -> Int {}
static func overloadedStaticFunc2(_ x: Double) -> Int {}
}
extension FooStruct {
var extProp: Int {
get {
return 42
}
set(v) {}
}
mutating
func extFunc0() {}
static var extStaticProp: Int {
get {
return 42
}
set(v) {}
}
static func extStaticFunc0() {}
struct ExtNestedStruct {}
class ExtNestedClass {}
enum ExtNestedEnum {
case ExtEnumX(Int)
}
typealias ExtNestedTypealias = Int
}
var fooObject: FooStruct
// FOO_OBJECT_DOT: Begin completions
// FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: lazyInstanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc2({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc3({#(a): Int#}, {#(Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc4({#(a): Int?#}, {#b: Int!#}, {#c: &Int?#}, {#d: &Int!#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc5()[#Int?#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc6()[#Int!#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc7({#a: Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc8({#(a): (Int, Int)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc9({#a: Int#})[#Void#]{{; name=.+$}}
//
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc0({#(v): Int...#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc1({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc2({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}}
//
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1()[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1()[#Double#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#(x): Int#})[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#(x): Double#})[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: builderFunc1({#(a): Int#})[#FooStruct#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc1({#(a): Int#}, {#b: Float#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc3({#(a): Int#}, {#b: (Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc1({#(a): Int#}, {#b: Float#})[#String#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#String#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc3({#(a): Int#}, {#b: (Float, Double)#})[#String#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: extProp[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: extFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT-NEXT: End completions
// FOO_OBJECT_NO_DOT: Begin completions
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .lazyInstanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .instanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc2({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc3({#(a): Int#}, {#(Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc4({#(a): Int?#}, {#b: Int!#}, {#c: &Int?#}, {#d: &Int!#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc5()[#Int?#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc6()[#Int!#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc7({#a: Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc8({#(a): (Int, Int)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc9({#a: Int#})[#Void#]{{; name=.+$}}
//
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc0({#(v): Int...#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc1({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc2({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}}
//
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1()[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1()[#Double#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#(x): Int#})[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#(x): Double#})[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .builderFunc1({#(a): Int#})[#FooStruct#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}, {#Int#}][#Double#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc1({#(a): Int#}, {#b: Float#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc3({#(a): Int#}, {#b: (Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc1({#(a): Int#}, {#b: Float#})[#String#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc2({#(a): Int#}, {#b: Float#}, {#c: Double#})[#String#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc3({#(a): Int#}, {#b: (Float, Double)#})[#String#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceVar]/CurrNominal: .extProp[#Int#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .extFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_NO_DOT-NEXT: BuiltinOperator/None: = {#Foo
// FOO_OBJECT_NO_DOT-NEXT: End completions
// FOO_STRUCT_DOT: Begin completions
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc1({#self: &FooStruct#})[#(Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc2({#self: &FooStruct#})[#(Int, b: inout Double) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc3({#self: &FooStruct#})[#(Int, (Float, Double)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc4({#self: &FooStruct#})[#(Int?, b: Int!, c: inout Int?, d: inout Int!) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc5({#self: &FooStruct#})[#() -> Int?#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc6({#self: &FooStruct#})[#() -> Int!#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc7({#self: &FooStruct#})[#(a: Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc8({#self: &FooStruct#})[#((Int, Int)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc9({#self: &FooStruct#})[#(a: @autoclosure () -> Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc0({#self: &FooStruct#})[#(Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc1({#self: &FooStruct#})[#(Float, v: Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: varargInstanceFunc2({#self: &FooStruct#})[#(Float, b: Double, v: Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Double#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#self: &FooStruct#})[#(Int) -> Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: overloadedInstanceFunc2({#self: &FooStruct#})[#(Double) -> Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: builderFunc1({#self: &FooStruct#})[#(Int) -> FooStruct#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc1({#self: &FooStruct#})[#(Int, b: Float) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorVoidFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc1({#self: &FooStruct#})[#(Int, b: Float) -> String#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> String#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: selectorStringFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> String#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Struct]/CurrNominal: NestedStruct[#FooStruct.NestedStruct#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Class]/CurrNominal: NestedClass[#FooStruct.NestedClass#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Enum]/CurrNominal: NestedEnum[#FooStruct.NestedEnum#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[TypeAlias]/CurrNominal: NestedTypealias[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticVar]/CurrNominal: staticVar[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: staticFunc0()[#Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc1()[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc1()[#Double#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc2({#(x): Int#})[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: overloadedStaticFunc2({#(x): Double#})[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Constructor]/CurrNominal: init({#lazyInstanceVar: Int?#}, {#instanceVar: Int#})[#FooStruct#]; name=init(lazyInstanceVar: Int?, instanceVar: Int){{$}}
// FOO_STRUCT_DOT-NEXT: Decl[Constructor]/CurrNominal: init()[#FooStruct#]; name=init(){{$}}
// FOO_STRUCT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: extFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticVar]/CurrNominal: extStaticProp[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[StaticMethod]/CurrNominal: extStaticFunc0()[#Void#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Struct]/CurrNominal: ExtNestedStruct[#FooStruct.ExtNestedStruct#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Class]/CurrNominal: ExtNestedClass[#FooStruct.ExtNestedClass#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[Enum]/CurrNominal: ExtNestedEnum[#FooStruct.ExtNestedEnum#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: Decl[TypeAlias]/CurrNominal: ExtNestedTypealias[#Int#]{{; name=.+$}}
// FOO_STRUCT_DOT-NEXT: End completions
// FOO_STRUCT_NO_DOT: Begin completions
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc1({#self: &FooStruct#})[#(Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc2({#self: &FooStruct#})[#(Int, b: inout Double) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc3({#self: &FooStruct#})[#(Int, (Float, Double)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc4({#self: &FooStruct#})[#(Int?, b: Int!, c: inout Int?, d: inout Int!) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc5({#self: &FooStruct#})[#() -> Int?#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc6({#self: &FooStruct#})[#() -> Int!#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc7({#self: &FooStruct#})[#(a: Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc8({#self: &FooStruct#})[#((Int, Int)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc9({#self: &FooStruct#})[#(a: @autoclosure () -> Int) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc0({#self: &FooStruct#})[#(Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc1({#self: &FooStruct#})[#(Float, v: Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .varargInstanceFunc2({#self: &FooStruct#})[#(Float, b: Double, v: Int...) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc1({#self: &FooStruct#})[#() -> Double#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#self: &FooStruct#})[#(Int) -> Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .overloadedInstanceFunc2({#self: &FooStruct#})[#(Double) -> Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .builderFunc1({#self: &FooStruct#})[#(Int) -> FooStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc1({#self: &FooStruct#})[#(Int, b: Float) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorVoidFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc1({#self: &FooStruct#})[#(Int, b: Float) -> String#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc2({#self: &FooStruct#})[#(Int, b: Float, c: Double) -> String#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .selectorStringFunc3({#self: &FooStruct#})[#(Int, b: (Float, Double)) -> String#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Struct]/CurrNominal: .NestedStruct[#FooStruct.NestedStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Class]/CurrNominal: .NestedClass[#FooStruct.NestedClass#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Enum]/CurrNominal: .NestedEnum[#FooStruct.NestedEnum#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[TypeAlias]/CurrNominal: .NestedTypealias[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .staticVar[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .staticFunc0()[#Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .staticFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc1()[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc1()[#Double#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc2({#(x): Int#})[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .overloadedStaticFunc2({#(x): Double#})[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Constructor]/CurrNominal: ({#lazyInstanceVar: Int?#}, {#instanceVar: Int#})[#FooStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Constructor]/CurrNominal: ()[#FooStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: .extFunc0({#self: &FooStruct#})[#() -> Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticVar]/CurrNominal: .extStaticProp[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[StaticMethod]/CurrNominal: .extStaticFunc0()[#Void#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Struct]/CurrNominal: .ExtNestedStruct[#FooStruct.ExtNestedStruct#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Class]/CurrNominal: .ExtNestedClass[#FooStruct.ExtNestedClass#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[Enum]/CurrNominal: .ExtNestedEnum[#FooStruct.ExtNestedEnum#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: Decl[TypeAlias]/CurrNominal: .ExtNestedTypealias[#Int#]{{; name=.+$}}
// FOO_STRUCT_NO_DOT-NEXT: End completions
func testObjectExpr() {
fooObject.#^FOO_OBJECT_DOT_1^#
}
func testDotDotTokenSplitWithCodeCompletion() {
fooObject.#^FOO_OBJECT_DOT_2^#.bar
}
func testObjectExprBuilderStyle1() {
fooObject
.#^FOO_OBJECT_DOT_3^#
}
func testObjectExprBuilderStyle2() {
fooObject
.builderFunc1(42).#^FOO_OBJECT_DOT_4^#
}
func testObjectExprBuilderStyle3() {
fooObject
.builderFunc1(42)
.#^FOO_OBJECT_DOT_5^#
}
func testObjectExprWithoutDot() {
fooObject#^FOO_OBJECT_NO_DOT_1^#
}
func testObjectExprWithoutSpaceAfterCodeCompletion() {
fooObject#^FOO_OBJECT_NO_DOT_2^#.bar
}
func testMetatypeExpr() {
FooStruct.#^FOO_STRUCT_DOT_1^#
}
func testMetatypeExprWithoutDot() {
FooStruct#^FOO_STRUCT_NO_DOT_1^#
}
func testImplicitlyCurriedFunc(_ fs: inout FooStruct) {
FooStruct.instanceFunc0(&fs)#^IMPLICITLY_CURRIED_FUNC_0^#
// IMPLICITLY_CURRIED_FUNC_0: Begin completions
// IMPLICITLY_CURRIED_FUNC_0-NEXT: Pattern/ExprSpecific: ()[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_FUNC_0-NEXT: End completions
FooStruct.instanceFunc1(&fs)#^IMPLICITLY_CURRIED_FUNC_1^#
// IMPLICITLY_CURRIED_FUNC_1: Begin completions
// IMPLICITLY_CURRIED_FUNC_1-NEXT: Pattern/ExprSpecific: ({#(a): Int#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_FUNC_1-NEXT: End completions
FooStruct.instanceFunc2(&fs)#^IMPLICITLY_CURRIED_FUNC_2^#
// IMPLICITLY_CURRIED_FUNC_2: Begin completions
// IMPLICITLY_CURRIED_FUNC_2-NEXT: Pattern/ExprSpecific: ({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_FUNC_2-NEXT: End completions
FooStruct.varargInstanceFunc0(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_0^#
// IMPLICITLY_CURRIED_VARARG_FUNC_0: Begin completions
// IMPLICITLY_CURRIED_VARARG_FUNC_0-NEXT: Pattern/ExprSpecific: ({#(v): Int...#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_VARARG_FUNC_0-NEXT: End completions
FooStruct.varargInstanceFunc1(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_1^#
// IMPLICITLY_CURRIED_VARARG_FUNC_1: Begin completions
// IMPLICITLY_CURRIED_VARARG_FUNC_1-NEXT: Pattern/ExprSpecific: ({#(a): Float#}, {#v: Int...#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_VARARG_FUNC_1-NEXT: End completions
FooStruct.varargInstanceFunc2(&fs)#^IMPLICITLY_CURRIED_VARARG_FUNC_2^#
// IMPLICITLY_CURRIED_VARARG_FUNC_2: Begin completions
// IMPLICITLY_CURRIED_VARARG_FUNC_2-NEXT: Pattern/ExprSpecific: ({#(a): Float#}, {#b: Double#}, {#v: Int...#})[#Void#]{{; name=.+$}}
// IMPLICITLY_CURRIED_VARARG_FUNC_2-NEXT: End completions
// This call is ambiguous, and the expression is invalid.
// Ensure that we don't suggest to call the result.
FooStruct.overloadedInstanceFunc1(&fs)#^IMPLICITLY_CURRIED_OVERLOADED_FUNC_1^#
// IMPLICITLY_CURRIED_OVERLOADED_FUNC_1: found code completion token
// IMPLICITLY_CURRIED_OVERLOADED_FUNC_1-NOT: Begin completions
// This call is ambiguous, and the expression is invalid.
// Ensure that we don't suggest to call the result.
FooStruct.overloadedInstanceFunc2(&fs)#^IMPLICITLY_CURRIED_OVERLOADED_FUNC_2^#
// IMPLICITLY_CURRIED_OVERLOADED_FUNC_2: found code completion token
// IMPLICITLY_CURRIED_OVERLOADED_FUNC_2-NOT: Begin completions
}
//===---
//===--- Test that we can complete inside 'case'.
//===---
func testSwitch1() {
switch fooObject {
case #^IN_SWITCH_CASE_1^#
}
switch fooObject {
case 1, #^IN_SWITCH_CASE_2^#
}
switch unknown_var {
case #^IN_SWITCH_CASE_3^#
}
switch {
case #^IN_SWITCH_CASE_4^#
}
}
// IN_SWITCH_CASE: Begin completions
// IN_SWITCH_CASE-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// IN_SWITCH_CASE-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// IN_SWITCH_CASE: End completions
//===--- Helper types that are used in this test
struct FooGenericStruct<T> {
init(t: T) { fooInstanceVarT = t }
var fooInstanceVarT: T
var fooInstanceVarTBrackets: [T]
mutating
func fooVoidInstanceFunc1(_ a: T) {}
mutating
func fooTInstanceFunc1(_ a: T) -> T { return a }
mutating
func fooUInstanceFunc1<U>(_ a: U) -> U { return a }
static var fooStaticVarT: Int = 0
static var fooStaticVarTBrackets: [Int] = [0]
static func fooVoidStaticFunc1(_ a: T) {}
static func fooTStaticFunc1(_ a: T) -> T { return a }
static func fooUInstanceFunc1<U>(_ a: U) -> U { return a }
}
class FooClass {
var fooClassInstanceVar = 0
func fooClassInstanceFunc0() {}
func fooClassInstanceFunc1(_ a: Int) {}
}
enum FooEnum {
}
protocol FooProtocol {
var fooInstanceVar1: Int { get set }
var fooInstanceVar2: Int { get }
typealias FooTypeAlias1
func fooInstanceFunc0() -> Double
func fooInstanceFunc1(_ a: Int) -> Double
subscript(i: Int) -> Double { get set }
}
class FooProtocolImpl : FooProtocol {
var fooInstanceVar1 = 0
val fooInstanceVar2 = 0
typealias FooTypeAlias1 = Float
init() {}
func fooInstanceFunc0() -> Double {
return 0.0
}
func fooInstanceFunc1(_ a: Int) -> Double {
return Double(a)
}
subscript(i: Int) -> Double {
return 0.0
}
}
protocol FooExProtocol : FooProtocol {
func fooExInstanceFunc0() -> Double
}
protocol BarProtocol {
var barInstanceVar: Int { get set }
typealias BarTypeAlias1
func barInstanceFunc0() -> Double
func barInstanceFunc1(_ a: Int) -> Double
}
protocol BarExProtocol : BarProtocol {
func barExInstanceFunc0() -> Double
}
protocol BazProtocol {
func bazInstanceFunc0() -> Double
}
typealias BarBazProtocolComposition = BarProtocol & BazProtocol
let fooProtocolInstance: FooProtocol = FooProtocolImpl()
let fooBarProtocolInstance: FooProtocol & BarProtocol
let fooExBarExProtocolInstance: FooExProtocol & BarExProtocol
typealias FooTypealias = Int
//===--- Test that we can code complete inside function calls.
func testInsideFunctionCall0() {
ERROR(#^INSIDE_FUNCTION_CALL_0^#
// INSIDE_FUNCTION_CALL_0: Begin completions
// INSIDE_FUNCTION_CALL_0-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_0: End completions
}
func testInsideFunctionCall1() {
var a = FooStruct()
a.instanceFunc0(#^INSIDE_FUNCTION_CALL_1^#
// There should be no other results here because the function call
// unambiguously resolves to overload that takes 0 arguments.
// INSIDE_FUNCTION_CALL_1: Begin completions
// INSIDE_FUNCTION_CALL_1-NEXT: Pattern/ExprSpecific: ['('])[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_1-NEXT: End completions
}
func testInsideFunctionCall2() {
var a = FooStruct()
a.instanceFunc1(#^INSIDE_FUNCTION_CALL_2^#
// INSIDE_FUNCTION_CALL_2: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_FUNCTION_CALL_2-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_2-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_2: End completions
}
func testInsideFunctionCall3() {
FooStruct().instanceFunc1(42, #^INSIDE_FUNCTION_CALL_3^#
// INSIDE_FUNCTION_CALL_3: Begin completions
// FIXME: There should be no results here because the function call
// unambiguously resolves to overload that takes 1 argument.
// INSIDE_FUNCTION_CALL_3-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_3: End completions
}
func testInsideFunctionCall4() {
var a = FooStruct()
a.instanceFunc2(#^INSIDE_FUNCTION_CALL_4^#
// INSIDE_FUNCTION_CALL_4: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_FUNCTION_CALL_4-DAG: Pattern/ExprSpecific: ['(']{#Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_4-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_4: End completions
}
func testInsideFunctionCall5() {
FooStruct().instanceFunc2(42, #^INSIDE_FUNCTION_CALL_5^#
// INSIDE_FUNCTION_CALL_5: Begin completions
// INSIDE_FUNCTION_CALL_5-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_5: End completions
}
func testInsideFunctionCall6() {
var a = FooStruct()
a.instanceFunc7(#^INSIDE_FUNCTION_CALL_6^#
// INSIDE_FUNCTION_CALL_6: Begin completions
// INSIDE_FUNCTION_CALL_6-NEXT: Pattern/ExprSpecific: ['(']{#a: Int#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_6-NEXT: End completions
}
func testInsideFunctionCall7() {
var a = FooStruct()
a.instanceFunc8(#^INSIDE_FUNCTION_CALL_7^#
// INSIDE_FUNCTION_CALL_7: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_FUNCTION_CALL_7: Pattern/ExprSpecific: ['(']{#(Int, Int)#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_7: End completions
}
func testInsideFunctionCall8(_ x: inout FooStruct) {
x.instanceFunc0(#^INSIDE_FUNCTION_CALL_8^#)
// Since we already have '()', there is no pattern to complete.
// INSIDE_FUNCTION_CALL_8-NOT: Pattern/{{.*}}:
}
func testInsideFunctionCall9(_ x: inout FooStruct) {
x.instanceFunc1(#^INSIDE_FUNCTION_CALL_9^#)
// Annotated ')'
// INSIDE_FUNCTION_CALL_9: Begin completions
// INSIDE_FUNCTION_CALL_9-DAG: Pattern/ExprSpecific: ['(']{#Int#}[')'][#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_9-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_9: End completions
}
func testInsideFunctionCall10(_ x: inout FooStruct) {
x.instanceFunc2(#^INSIDE_FUNCTION_CALL_10^#)
// Annotated ')'
// INSIDE_FUNCTION_CALL_10: Begin completions
// INSIDE_FUNCTION_CALL_10-DAG: Pattern/ExprSpecific: ['(']{#Int#}, {#b: &Double#}[')'][#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_10-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_10: End completions
}
func testInsideFunctionCall11(_ x: inout FooStruct) {
x.instanceFunc2(#^INSIDE_FUNCTION_CALL_11^#,
// INSIDE_FUNCTION_CALL_11-NOT: Pattern/{{.*}}:{{.*}}({{.*}}{#Int#}
}
func testInsideFunctionCall12(_ x: inout FooStruct) {
x.instanceFunc2(#^INSIDE_FUNCTION_CALL_12^#<#placeholder#>
// INSIDE_FUNCTION_CALL_12-NOT: Pattern/{{.*}}:{{.*}}({{.*}}{#Int#}
}
func testInsideVarargFunctionCall1() {
var a = FooStruct()
a.varargInstanceFunc0(#^INSIDE_VARARG_FUNCTION_CALL_1^#
// INSIDE_VARARG_FUNCTION_CALL_1: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_VARARG_FUNCTION_CALL_1-DAG: Pattern/ExprSpecific: ['(']{#Int...#})[#Void#]{{; name=.+$}}
// INSIDE_VARARG_FUNCTION_CALL_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_VARARG_FUNCTION_CALL_1: End completions
}
func testInsideVarargFunctionCall2() {
FooStruct().varargInstanceFunc0(42, #^INSIDE_VARARG_FUNCTION_CALL_2^#
// INSIDE_VARARG_FUNCTION_CALL_2: Begin completions
// INSIDE_VARARG_FUNCTION_CALL_2-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_VARARG_FUNCTION_CALL_2: End completions
}
func testInsideVarargFunctionCall3() {
FooStruct().varargInstanceFunc0(42, 4242, #^INSIDE_VARARG_FUNCTION_CALL_3^#
// INSIDE_VARARG_FUNCTION_CALL_3: Begin completions
// INSIDE_VARARG_FUNCTION_CALL_3-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_VARARG_FUNCTION_CALL_3: End completions
}
func testInsideOverloadedFunctionCall1() {
var a = FooStruct()
a.overloadedInstanceFunc2(#^INSIDE_OVERLOADED_FUNCTION_CALL_1^#
// INSIDE_OVERLOADED_FUNCTION_CALL_1: Begin completions
// FIXME: produce call patterns here.
// INSIDE_OVERLOADED_FUNCTION_CALL_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_OVERLOADED_FUNCTION_CALL_1: End completions
}
func testInsideFunctionCallOnClassInstance1(_ a: FooClass) {
a.fooClassInstanceFunc1(#^INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1^#
// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1: Begin completions
// FIXME: we should print the non-API param name rdar://20962472
// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1-DAG: Pattern/ExprSpecific: ['(']{#Int#})[#Void#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// INSIDE_FUNCTION_CALL_ON_CLASS_INSTANCE_1: End completions
}
//===--- Variables that have function types.
class FuncTypeVars {
var funcVar1: () -> Double
var funcVar2: (a: Int) -> Double // adding the label is erroneous.
}
var funcTypeVarsObject: FuncTypeVars
func testFuncTypeVars() {
funcTypeVarsObject.funcVar1#^VF1^#
// VF1: Begin completions
// VF1-NEXT: Pattern/ExprSpecific: ()[#Double#]{{; name=.+$}}
// VF1-NEXT: BuiltinOperator/None: = {#() -> Double##() -> Double#}[#Void#]
// VF1-NEXT: End completions
funcTypeVarsObject.funcVar2#^VF2^#
// VF2: Begin completions
// VF2-NEXT: Pattern/ExprSpecific: ({#Int#})[#Double#]{{; name=.+$}}
// VF2-NEXT: BuiltinOperator/None: = {#(Int) -> Double##(Int) -> Double#}[#Void#]
// VF2-NEXT: End completions
}
//===--- Check that we look into base classes.
class MembersBase {
var baseVar = 0
func baseInstanceFunc() {}
class func baseStaticFunc() {}
}
class MembersDerived : MembersBase {
var derivedVar = 0
func derivedInstanceFunc() {}
class func derivedStaticFunc() {}
}
var membersDerived: MembersDerived
func testLookInBase() {
membersDerived.#^BASE_MEMBERS^#
// BASE_MEMBERS: Begin completions
// BASE_MEMBERS-NEXT: Decl[InstanceVar]/CurrNominal: derivedVar[#Int#]{{; name=.+$}}
// BASE_MEMBERS-NEXT: Decl[InstanceMethod]/CurrNominal: derivedInstanceFunc()[#Void#]{{; name=.+$}}
// BASE_MEMBERS-NEXT: Decl[InstanceVar]/Super: baseVar[#Int#]{{; name=.+$}}
// BASE_MEMBERS-NEXT: Decl[InstanceMethod]/Super: baseInstanceFunc()[#Void#]{{; name=.+$}}
// BASE_MEMBERS-NEXT: End completions
}
func testLookInBaseStatic() {
MembersDerived.#^BASE_MEMBERS_STATIC^#
// BASE_MEMBERS_STATIC: Begin completions
// BASE_MEMBERS_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: derivedInstanceFunc({#self: MembersDerived#})[#() -> Void#]{{; name=.+$}}
// BASE_MEMBERS_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: derivedStaticFunc()[#Void#]{{; name=.+$}}
// BASE_MEMBERS_STATIC-NEXT: Decl[Constructor]/CurrNominal: init()[#MembersDerived#]; name=init(){{$}}
// BASE_MEMBERS_STATIC-NEXT: Decl[InstanceMethod]/Super: baseInstanceFunc({#self: MembersBase#})[#() -> Void#]{{; name=.+$}}
// BASE_MEMBERS_STATIC-NEXT: Decl[StaticMethod]/Super: baseStaticFunc()[#Void#]{{; name=.+$}}
// BASE_MEMBERS_STATIC-NEXT: End completions
}
//===--- Check that we can look into protocols.
func testLookInProtoNoDot1() {
fooProtocolInstance#^PROTO_MEMBERS_NO_DOT_1^#
// PROTO_MEMBERS_NO_DOT_1: Begin completions
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_1-NEXT: End completions
}
func testLookInProtoNoDot2() {
fooBarProtocolInstance#^PROTO_MEMBERS_NO_DOT_2^#
// PROTO_MEMBERS_NO_DOT_2: Begin completions
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceVar]/CurrNominal: .barInstanceVar[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_2-NEXT: End completions
}
func testLookInProtoNoDot3() {
fooExBarExProtocolInstance#^PROTO_MEMBERS_NO_DOT_3^#
// PROTO_MEMBERS_NO_DOT_3: Begin completions
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceVar]/Super: .barInstanceVar[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/CurrNominal: .barExInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceVar]/Super: .fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceVar]/Super: .fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/Super: .fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[Subscript]/Super: [{#Int#}][#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooExInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_NO_DOT_3-NEXT: End completions
}
func testLookInProto1() {
fooProtocolInstance.#^PROTO_MEMBERS_1^#
// PROTO_MEMBERS_1: Begin completions
// PROTO_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_1-NEXT: End completions
}
func testLookInProto2() {
fooBarProtocolInstance.#^PROTO_MEMBERS_2^#
// PROTO_MEMBERS_2: Begin completions
// PROTO_MEMBERS_2-NEXT: Decl[InstanceVar]/CurrNominal: barInstanceVar[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceVar]/CurrNominal: fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_2-NEXT: End completions
}
func testLookInProto3() {
fooExBarExProtocolInstance.#^PROTO_MEMBERS_3^#
// PROTO_MEMBERS_3: Begin completions
// PROTO_MEMBERS_3-NEXT: Decl[InstanceVar]/Super: barInstanceVar[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/CurrNominal: barExInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: Decl[InstanceMethod]/CurrNominal: fooExInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_3-NEXT: End completions
}
func testLookInProto4(_ a: FooProtocol & BarBazProtocolComposition) {
a.#^PROTO_MEMBERS_4^#
// PROTO_MEMBERS_4: Begin completions
// PROTO_MEMBERS_4-DAG: Decl[InstanceMethod]/CurrNominal: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_4-DAG: Decl[InstanceMethod]/CurrNominal: barInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_4-DAG: Decl[InstanceMethod]/CurrNominal: bazInstanceFunc0()[#Double#]{{; name=.+$}}
// PROTO_MEMBERS_4: End completions
}
//===--- Check that we can resolve function parameters.
func testResolveFuncParam1(_ fs: FooStruct) {
fs.#^RESOLVE_FUNC_PARAM_1^#
}
class TestResolveFuncParam2 {
func testResolveFuncParam2a(_ fs: FooStruct) {
fs.#^RESOLVE_FUNC_PARAM_2^#
}
}
func testResolveFuncParam3<Foo : FooProtocol>(_ foo: Foo) {
foo.#^RESOLVE_FUNC_PARAM_3^#
// RESOLVE_FUNC_PARAM_3: Begin completions
// RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_3-NEXT: End completions
}
func testResolveFuncParam4<FooBar : FooProtocol & BarProtocol>(_ fooBar: FooBar) {
fooBar.#^RESOLVE_FUNC_PARAM_4^#
// RESOLVE_FUNC_PARAM_4: Begin completions
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceVar]/Super: barInstanceVar[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_4-NEXT: End completions
}
func testResolveFuncParam5<FooExBarEx : FooExProtocol & BarExProtocol>(_ a: FooExBarEx) {
a.#^RESOLVE_FUNC_PARAM_5^#
// RESOLVE_FUNC_PARAM_5: Begin completions
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceVar]/Super: barInstanceVar[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: barInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: barExInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: Decl[InstanceMethod]/Super: fooExInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_5-NEXT: End completions
}
func testResolveFuncParam6<Foo : FooProtocol where Foo : FooClass>(_ foo: Foo) {
foo.#^RESOLVE_FUNC_PARAM_6^#
// RESOLVE_FUNC_PARAM_6: Begin completions
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceVar]/Super: fooClassInstanceVar[#Int#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooClassInstanceFunc0()[#Void#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: Decl[InstanceMethod]/Super: fooClassInstanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// RESOLVE_FUNC_PARAM_6-NEXT: End completions
}
class TestResolveConstructorParam1 {
init(fs: FooStruct) {
fs.#^RESOLVE_CONSTRUCTOR_PARAM_1^#
}
}
class TestResolveConstructorParam2 {
init<Foo : FooProtocol>(foo: Foo) {
foo.#^RESOLVE_CONSTRUCTOR_PARAM_2^#
// RESOLVE_CONSTRUCTOR_PARAM_2: Begin completions
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_2-NEXT: End completions
}
}
class TestResolveConstructorParam3<Foo : FooProtocol> {
init(foo: Foo) {
foo.#^RESOLVE_CONSTRUCTOR_PARAM_3^#
// RESOLVE_CONSTRUCTOR_PARAM_3: Begin completions
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar1[#Int#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceVar]/Super: fooInstanceVar2[#Int#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc0()[#Double#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: Decl[InstanceMethod]/Super: fooInstanceFunc1({#(a): Int#})[#Double#]{{; name=.+$}}
// RESOLVE_CONSTRUCTOR_PARAM_3-NEXT: End completions
}
}
//===--- Check that we can handle ParenPattern in function arguments.
struct FuncParenPattern {
init(_: Int) {}
init(_: (Int, Int)) {}
mutating
func instanceFunc(_: Int) {}
subscript(_: Int) -> Int {
get {
return 0
}
}
}
func testFuncParenPattern1(_ fpp: FuncParenPattern) {
fpp#^FUNC_PAREN_PATTERN_1^#
// FUNC_PAREN_PATTERN_1: Begin completions
// FUNC_PAREN_PATTERN_1-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#Int#})[#Void#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_1-NEXT: Decl[Subscript]/CurrNominal: [{#Int#}][#Int#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_1-NEXT: End completions
}
func testFuncParenPattern2(_ fpp: FuncParenPattern) {
FuncParenPattern#^FUNC_PAREN_PATTERN_2^#
// FUNC_PAREN_PATTERN_2: Begin completions
// FUNC_PAREN_PATTERN_2-NEXT: Decl[Constructor]/CurrNominal: ({#Int#})[#FuncParenPattern#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_2-NEXT: Decl[Constructor]/CurrNominal: ({#(Int, Int)#})[#FuncParenPattern#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_2-NEXT: Decl[InstanceMethod]/CurrNominal: .instanceFunc({#self: &FuncParenPattern#})[#(Int) -> Void#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_2-NEXT: End completions
}
func testFuncParenPattern3(_ fpp: inout FuncParenPattern) {
fpp.instanceFunc#^FUNC_PAREN_PATTERN_3^#
// FUNC_PAREN_PATTERN_3: Begin completions
// FUNC_PAREN_PATTERN_3-NEXT: Pattern/ExprSpecific: ({#Int#})[#Void#]{{; name=.+$}}
// FUNC_PAREN_PATTERN_3-NEXT: End completions
}
//===--- Check that we can code complete after function calls
struct SomeBuilder {
init(a: Int) {}
func doFoo() -> SomeBuilder { return self }
func doBar() -> SomeBuilder { return self }
func doBaz(_ z: Double) -> SomeBuilder { return self }
}
func testChainedCalls1() {
SomeBuilder(42)#^CHAINED_CALLS_1^#
// CHAINED_CALLS_1: Begin completions
// CHAINED_CALLS_1-DAG: Decl[InstanceMethod]/CurrNominal: .doFoo()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_1-DAG: Decl[InstanceMethod]/CurrNominal: .doBar()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_1-DAG: Decl[InstanceMethod]/CurrNominal: .doBaz({#(z): Double#})[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_1: End completions
}
func testChainedCalls2() {
SomeBuilder(42).doFoo()#^CHAINED_CALLS_2^#
// CHAINED_CALLS_2: Begin completions
// CHAINED_CALLS_2-DAG: Decl[InstanceMethod]/CurrNominal: .doFoo()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_2-DAG: Decl[InstanceMethod]/CurrNominal: .doBar()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_2-DAG: Decl[InstanceMethod]/CurrNominal: .doBaz({#(z): Double#})[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_2: End completions
}
func testChainedCalls3() {
// doBaz() takes a Double. Check that we can recover.
SomeBuilder(42).doFoo().doBaz(SomeBuilder(24))#^CHAINED_CALLS_3^#
// CHAINED_CALLS_3: Begin completions
// CHAINED_CALLS_3-DAG: Decl[InstanceMethod]/CurrNominal: .doFoo()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_3-DAG: Decl[InstanceMethod]/CurrNominal: .doBar()[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_3-DAG: Decl[InstanceMethod]/CurrNominal: .doBaz({#z: Double#})[#SomeBuilder#]{{; name=.+$}}
// CHAINED_CALLS_3: End completions
}
//===--- Check that we can code complete expressions that have generic parameters
func testResolveGenericParams1() {
FooGenericStruct<FooStruct>()#^RESOLVE_GENERIC_PARAMS_1^#
// RESOLVE_GENERIC_PARAMS_1: Begin completions
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[FooStruct]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1-NEXT: End completions
FooGenericStruct<FooStruct>#^RESOLVE_GENERIC_PARAMS_1_STATIC^#
// RESOLVE_GENERIC_PARAMS_1_STATIC: Begin completions
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: FooStruct#})[#FooGenericStruct<FooStruct>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(FooStruct) -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(FooStruct) -> FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_1_STATIC-NEXT: End completions
}
func testResolveGenericParams2<Foo : FooProtocol>(_ foo: Foo) {
FooGenericStruct<Foo>()#^RESOLVE_GENERIC_PARAMS_2^#
// RESOLVE_GENERIC_PARAMS_2: Begin completions
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#FooProtocol#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[FooProtocol]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): FooProtocol#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): FooProtocol#})[#FooProtocol#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2-NEXT: End completions
FooGenericStruct<Foo>#^RESOLVE_GENERIC_PARAMS_2_STATIC^#
// RESOLVE_GENERIC_PARAMS_2_STATIC: Begin completions
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: FooProtocol#})[#FooGenericStruct<FooProtocol>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<FooProtocol>#})[#FooProtocol -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<FooProtocol>#})[#FooProtocol -> FooProtocol#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<FooProtocol>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): FooProtocol#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): FooProtocol#})[#FooProtocol#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_2_STATIC-NEXT: End completions
}
struct TestResolveGenericParams3_4<T> {
func testResolveGenericParams3() {
FooGenericStruct<FooStruct>()#^RESOLVE_GENERIC_PARAMS_3^#
// RESOLVE_GENERIC_PARAMS_3: Begin completions
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[FooStruct]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3-NEXT: End completions
FooGenericStruct<FooStruct>#^RESOLVE_GENERIC_PARAMS_3_STATIC^#
// RESOLVE_GENERIC_PARAMS_3_STATIC: Begin completions, 9 items
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: FooStruct#})[#FooGenericStruct<FooStruct>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(FooStruct) -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(FooStruct) -> FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<FooStruct>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): FooStruct#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): FooStruct#})[#FooStruct#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_3_STATIC-NEXT: End completions
}
func testResolveGenericParams4(_ t: T) {
FooGenericStruct<T>(t)#^RESOLVE_GENERIC_PARAMS_4^#
// RESOLVE_GENERIC_PARAMS_4: Begin completions
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#T#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[T]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): T#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): T#})[#T#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4-NEXT: End completions
FooGenericStruct<T>#^RESOLVE_GENERIC_PARAMS_4_STATIC^#
// RESOLVE_GENERIC_PARAMS_4_STATIC: Begin completions
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: T#})[#FooGenericStruct<T>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<T>#})[#(T) -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<T>#})[#(T) -> T#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<T>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): T#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): T#})[#T#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_4_STATIC-NEXT: End completions
}
func testResolveGenericParams5<U>(_ u: U) {
FooGenericStruct<U>(u)#^RESOLVE_GENERIC_PARAMS_5^#
// RESOLVE_GENERIC_PARAMS_5: Begin completions
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarT[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceVar]/CurrNominal: .fooInstanceVarTBrackets[#[U]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#(a): U#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5-NEXT: End completions
FooGenericStruct<U>#^RESOLVE_GENERIC_PARAMS_5_STATIC^#
// RESOLVE_GENERIC_PARAMS_5_STATIC: Begin completions
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[Constructor]/CurrNominal: ({#t: U#})[#FooGenericStruct<U>#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooVoidInstanceFunc1({#self: &FooGenericStruct<U>#})[#(U) -> Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooTInstanceFunc1({#self: &FooGenericStruct<U>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[InstanceMethod]/CurrNominal: .fooUInstanceFunc1({#self: &FooGenericStruct<U>#})[#(U) -> U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarT[#Int#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticVar]/CurrNominal: .fooStaticVarTBrackets[#[Int]#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooVoidStaticFunc1({#(a): U#})[#Void#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooTStaticFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: Decl[StaticMethod]/CurrNominal: .fooUInstanceFunc1({#(a): U#})[#U#]{{; name=.+$}}
// RESOLVE_GENERIC_PARAMS_5_STATIC-NEXT: End completions
}
}
func testResolveGenericParamsError1() {
// There is no type 'Foo'. Check that we don't crash.
// FIXME: we could also display correct completion results here, because
// swift does not have specialization, and the set of completion results does
// not depend on the generic type argument.
FooGenericStruct<NotDefinedType>()#^RESOLVE_GENERIC_PARAMS_ERROR_1^#
// RESOLVE_GENERIC_PARAMS_ERROR_1: found code completion token
// RESOLVE_GENERIC_PARAMS_ERROR_1-NOT: Begin completions
}
//===--- Check that we can code complete expressions that have unsolved type variables.
class BuilderStyle<T> {
var count = 0
func addString(_ s: String) -> BuilderStyle<T> {
count += 1
return self
}
func add(_ t: T) -> BuilderStyle<T> {
count += 1
return self
}
func get() -> Int {
return count
}
}
func testTypeCheckWithUnsolvedVariables1() {
BuilderStyle().#^TC_UNSOLVED_VARIABLES_1^#
}
// TC_UNSOLVED_VARIABLES_1: Begin completions
// TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceVar]/CurrNominal: count[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceMethod]/CurrNominal: addString({#(s): String#})[#BuilderStyle<T>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceMethod]/CurrNominal: add({#(t): T#})[#BuilderStyle<T>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_1-NEXT: Decl[InstanceMethod]/CurrNominal: get()[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_1-NEXT: End completions
func testTypeCheckWithUnsolvedVariables2() {
BuilderStyle().addString("abc").#^TC_UNSOLVED_VARIABLES_2^#
}
// TC_UNSOLVED_VARIABLES_2: Begin completions
// TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceVar]/CurrNominal: count[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceMethod]/CurrNominal: addString({#(s): String#})[#BuilderStyle<T>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceMethod]/CurrNominal: add({#(t): T#})[#BuilderStyle<T>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_2-NEXT: Decl[InstanceMethod]/CurrNominal: get()[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_2-NEXT: End completions
func testTypeCheckWithUnsolvedVariables3() {
BuilderStyle().addString("abc").add(42).#^TC_UNSOLVED_VARIABLES_3^#
}
// TC_UNSOLVED_VARIABLES_3: Begin completions
// TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceVar]/CurrNominal: count[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceMethod]/CurrNominal: addString({#(s): String#})[#BuilderStyle<Int>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceMethod]/CurrNominal: add({#(t): Int#})[#BuilderStyle<Int>#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_3-NEXT: Decl[InstanceMethod]/CurrNominal: get()[#Int#]{{; name=.+$}}
// TC_UNSOLVED_VARIABLES_3-NEXT: End completions
func testTypeCheckNil() {
nil#^TC_UNSOLVED_VARIABLES_4^#
}
// TC_UNSOLVED_VARIABLES_4-NOT: Decl{{.*}}: .{{[a-zA-Z]}}
//===--- Check that we can look up into modules
func testResolveModules1() {
Swift#^RESOLVE_MODULES_1^#
// RESOLVE_MODULES_1: Begin completions
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int8[#Int8#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int16[#Int16#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int32[#Int32#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Int64[#Int64#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[Struct]/OtherModule[Swift]: .Bool[#Bool#]{{; name=.+$}}
// RESOLVE_MODULES_1-DAG: Decl[TypeAlias]/OtherModule[Swift]: .Float32[#Float#]{{; name=.+$}}
// RESOLVE_MODULES_1: End completions
}
//===--- Check that we can complete inside interpolated string literals
func testInterpolatedString1() {
"\(fooObject.#^INTERPOLATED_STRING_1^#)"
}
// FOO_OBJECT_DOT1: Begin completions
// FOO_OBJECT_DOT1-DAG: Decl[InstanceVar]/CurrNominal: lazyInstanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc0()[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc1({#(a): Int#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc2({#(a): Int#}, {#b: &Double#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc3({#(a): Int#}, {#(Float, Double)#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended/TypeRelation[Invalid]: instanceFunc4({#(a): Int?#}, {#b: Int!#}, {#c: &Int?#}, {#d: &Int!#})[#Void#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc5()[#Int?#]{{; name=.+$}}
// FOO_OBJECT_DOT1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc6()[#Int!#]{{; name=.+$}}
//===--- Check protocol extensions
struct WillConformP1 {
}
protocol P1 {
func reqP1()
}
protocol P2 : P1 {
func reqP2()
}
protocol P3 : P1, P2 {
}
extension P1 {
final func extP1() {}
}
extension P2 {
final func extP2() {}
}
extension P3 {
final func reqP1() {}
final func reqP2() {}
final func extP3() {}
}
extension WillConformP1 : P1 {
func reqP1() {}
}
struct DidConformP2 : P2 {
func reqP1() {}
func reqP2() {}
}
struct DidConformP3 : P3 {
}
func testProtocol1(_ x: P1) {
x.#^PROTOCOL_EXT_P1^#
}
// PROTOCOL_EXT_P1: Begin completions
// PROTOCOL_EXT_P1-DAG: Decl[InstanceMethod]/CurrNominal: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P1-DAG: Decl[InstanceMethod]/CurrNominal: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P1: End completions
func testProtocol2(_ x: P2) {
x.#^PROTOCOL_EXT_P2^#
}
// PROTOCOL_EXT_P2: Begin completions
// PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/CurrNominal: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P2-DAG: Decl[InstanceMethod]/CurrNominal: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P2: End completions
func testProtocol3(_ x: P3) {
x.#^PROTOCOL_EXT_P3^#
}
// PROTOCOL_EXT_P3: Begin completions
// FIXME: the next two should both be "CurrentNominal"
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3-DAG: Decl[InstanceMethod]/CurrNominal: extP3()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P3: End completions
func testConformingConcrete1(_ x: WillConformP1) {
x.#^PROTOCOL_EXT_WILLCONFORMP1^#
}
// PROTOCOL_EXT_WILLCONFORMP1: Begin completions
// PROTOCOL_EXT_WILLCONFORMP1-DAG: Decl[InstanceMethod]/CurrNominal: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_WILLCONFORMP1-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_WILLCONFORMP1: End completions
func testConformingConcrete2(_ x: DidConformP2) {
x.#^PROTOCOL_EXT_DIDCONFORMP2^#
}
// PROTOCOL_EXT_DIDCONFORMP2: Begin completions
// PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/CurrNominal: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/CurrNominal: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP2-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP2: End completions
func testConformingConcrete3(_ x: DidConformP3) {
x.#^PROTOCOL_EXT_DIDCONFORMP3^#
}
// PROTOCOL_EXT_DIDCONFORMP3: Begin completions
// FIXME: the next two should both be "CurrentNominal"
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3-DAG: Decl[InstanceMethod]/Super: extP3()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_DIDCONFORMP3: End completions
func testGenericConforming1<T: P1>(x: T) {
x.#^PROTOCOL_EXT_GENERICP1^#
}
// PROTOCOL_EXT_GENERICP1: Begin completions
// PROTOCOL_EXT_GENERICP1-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP1-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP1: End completions
func testGenericConforming2<T: P2>(x: T) {
x.#^PROTOCOL_EXT_GENERICP2^#
}
// PROTOCOL_EXT_GENERICP2: Begin completions
// PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP2-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP2: End completions
func testGenericConforming3<T: P3>(x: T) {
x.#^PROTOCOL_EXT_GENERICP3^#
}
// PROTOCOL_EXT_GENERICP3: Begin completions
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: reqP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: reqP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: extP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: extP2()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3-DAG: Decl[InstanceMethod]/Super: extP3()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_GENERICP3: End completions
struct OnlyMe {}
protocol P4 {
associatedtype T
}
extension P4 where Self.T : P1 {
final func extP4WhenP1() {}
final var x: Int { return 1 }
init() {}
}
extension P4 where Self.T : P1 {
init(x: Int) {}
}
extension P4 where Self.T == OnlyMe {
final func extP4OnlyMe() {}
final subscript(x: Int) -> Int { return 2 }
}
struct Concrete1 : P4 {
typealias T = WillConformP1
}
struct Generic1<S: P1> : P4 {
typealias T = S
}
struct Concrete2 : P4 {
typealias T = OnlyMe
}
struct Generic2<S> : P4 {
typealias T = S
}
func testConstrainedP4(_ x: P4) {
x.#^PROTOCOL_EXT_P4^#
}
// PROTOCOL_EXT_P4-NOT: extP4
func testConstrainedConcrete1(_ x: Concrete1) {
x.#^PROTOCOL_EXT_CONCRETE1^#
}
func testConstrainedConcrete2(_ x: Generic1<WillConformP1>) {
x.#^PROTOCOL_EXT_CONCRETE2^#
}
func testConstrainedGeneric1<S: P1>(x: Generic1<S>) {
x.#^PROTOCOL_EXT_CONSTRAINED_GENERIC_1^#
}
func testConstrainedGeneric2<S: P4 where S.T : P1>(x: S) {
x.#^PROTOCOL_EXT_CONSTRAINED_GENERIC_2^#
}
extension Concrete1 {
func testInsideConstrainedConcrete1_1() {
#^PROTOCOL_EXT_INSIDE_CONCRETE1_1^#
}
func testInsideConstrainedConcrete1_2() {
self.#^PROTOCOL_EXT_INSIDE_CONCRETE1_2^#
}
}
// PROTOCOL_EXT_P4_P1: Begin completions
// PROTOCOL_EXT_P4_P1-NOT: extP4OnlyMe()
// PROTOCOL_EXT_P4_P1-DAG: Decl[InstanceMethod]/Super: extP4WhenP1()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_P1-DAG: Decl[InstanceVar]/Super: x[#Int#]{{; name=.+$}}
// PROTOCOL_EXT_P4_P1-NOT: extP4OnlyMe()
// PROTOCOL_EXT_P4_P1: End completions
func testConstrainedConcrete3(_ x: Concrete2) {
x.#^PROTOCOL_EXT_CONCRETE3^#
}
func testConstrainedConcrete3_sub(_ x: Concrete2) {
x#^PROTOCOL_EXT_CONCRETE3_SUB^#
}
func testConstrainedConcrete4(_ x: Generic2<OnlyMe>) {
x.#^PROTOCOL_EXT_CONCRETE4^#
}
func testConstrainedGeneric1<S: P4 where S.T == OnlyMe>(x: S) {
x.#^PROTOCOL_EXT_CONSTRAINED_GENERIC_3^#
}
func testConstrainedGeneric1_sub<S: P4 where S.T == OnlyMe>(x: S) {
x#^PROTOCOL_EXT_CONSTRAINED_GENERIC_3_SUB^#
}
extension Concrete2 {
func testInsideConstrainedConcrete2_1() {
#^PROTOCOL_EXT_INSIDE_CONCRETE2_1^#
}
func testInsideConstrainedConcrete2_2() {
self.#^PROTOCOL_EXT_INSIDE_CONCRETE2_2^#
}
}
// PROTOCOL_EXT_P4_ONLYME: Begin completions
// PROTOCOL_EXT_P4_ONLYME-NOT: extP4WhenP1()
// PROTOCOL_EXT_P4_ONLYME-NOT: x[#Int#]
// PROTOCOL_EXT_P4_ONLYME-DAG: Decl[InstanceMethod]/Super: extP4OnlyMe()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_ONLYME-NOT: extP4WhenP1()
// PROTOCOL_EXT_P4_ONLYME-NOT: x[#Int#]
// PROTOCOL_EXT_P4_ONLYME: End completions
// PROTOCOL_EXT_P4_ONLYME_SUB: Begin completions
// PROTOCOL_EXT_P4_ONLYME_SUB: Decl[Subscript]/Super: [{#Int#}][#Int#]{{; name=.+$}}
// PROTOCOL_EXT_P4_ONLYME_SUB: End completions
func testTypealias1() {
Concrete1.#^PROTOCOL_EXT_TA_1^#
}
func testTypealias1<S: P4 where S.T == WillConformP1>() {
S.#^PROTOCOL_EXT_TA_2^#
}
// PROTOCOL_EXT_TA: Begin completions
// PROTOCOL_EXT_TA_2-DAG: Decl[AssociatedType]/{{Super|CurrNominal}}: T
// PROTOCOL_EXT_TA: End completions
func testProtExtInit1() {
Concrete1(#^PROTOCOL_EXT_INIT_1^#
}
// PROTOCOL_EXT_INIT_1: Begin completions
// PROTOCOL_EXT_INIT_1: Decl[Constructor]/Super: ['('])[#Concrete1#]{{; name=.+$}}
// PROTOCOL_EXT_INIT_1: Decl[Constructor]/Super: ['(']{#x: Int#})[#Concrete1#]{{; name=.+$}}
// PROTOCOL_EXT_INIT_1: End completions
func testProtExtInit2<S: P4 where S.T : P1>() {
S(#^PROTOCOL_EXT_INIT_2^#
}
// PROTOCOL_EXT_INIT_2: Begin completions
// PROTOCOL_EXT_INIT_2: Decl[Constructor]/Super: ['('])[#P4#]{{; name=.+$}}
// PROTOCOL_EXT_INIT_2: Decl[Constructor]/Super: ['(']{#x: Int#})[#P4#]{{; name=.+$}}
// PROTOCOL_EXT_INIT_2: End completions
extension P4 where Self.T == OnlyMe {
final func test1() {
self.#^PROTOCOL_EXT_P4_DOT_1^#
}
final func test2() {
#^PROTOCOL_EXT_P4_DOT_2^#
}
}
// PROTOCOL_EXT_P4_DOT: Begin completions
// PROTOCOL_EXT_P4_DOT-NOT: extP4WhenP1()
// PROTOCOL_EXT_P4_DOT-DAG: Decl[InstanceMethod]/Super: extP4OnlyMe()[#Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_DOT-NOT: extP4WhenP1()
// PROTOCOL_EXT_P4_DOT: End completions
extension P4 where Self.T == WillConformP1 {
final func test() {
T.#^PROTOCOL_EXT_P4_T_DOT_1^#
}
}
// PROTOCOL_EXT_P4_T_DOT_1: Begin completions
// PROTOCOL_EXT_P4_T_DOT_1-DAG: Decl[InstanceMethod]/CurrNominal: reqP1({#self: WillConformP1#})[#() -> Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_T_DOT_1-DAG: Decl[InstanceMethod]/Super: extP1({#self: WillConformP1#})[#() -> Void#]{{; name=.+$}}
// PROTOCOL_EXT_P4_T_DOT_1: End completions
protocol PWithT {
associatedtype T
func foo(_ x: T) -> T
}
extension PWithT {
final func bar(_ x: T) -> T {
return x
}
}
// Note: PWithT cannot actually be used as an existential type because it has
// an associated type. But we should still be able to give code completions.
func testUnusableProtExt(_ x: PWithT) {
x.#^PROTOCOL_EXT_UNUSABLE_EXISTENTIAL^#
}
// PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: Begin completions
// PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: Decl[InstanceMethod]/CurrNominal: foo({#(x): PWithT.T#})[#PWithT.T#]{{; name=.+}}
// PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: Decl[InstanceMethod]/CurrNominal: bar({#(x): PWithT.T#})[#PWithT.T#]{{; name=.+}}
// PROTOCOL_EXT_UNUSABLE_EXISTENTIAL: End completions
protocol dedupP {
associatedtype T
func foo() -> T
var bar: T {get}
subscript(x: T) -> T {get}
}
extension dedupP {
func foo() -> T { return T() }
var bar: T { return T() }
subscript(x: T) -> T { return T() }
}
struct dedupS : dedupP {
func foo() -> Int { return T() }
var bar: Int = 5
subscript(x: Int) -> Int { return 10 }
}
func testDeDuped(_ x: dedupS) {
x#^PROTOCOL_EXT_DEDUP_1^#
// PROTOCOL_EXT_DEDUP_1: Begin completions, 3 items
// PROTOCOL_EXT_DEDUP_1: Decl[InstanceMethod]/CurrNominal: .foo()[#Int#]; name=foo()
// PROTOCOL_EXT_DEDUP_1: Decl[InstanceVar]/CurrNominal: .bar[#Int#]; name=bar
// PROTOCOL_EXT_DEDUP_1: Decl[Subscript]/CurrNominal: [{#Int#}][#Int#]; name=[Int]
// PROTOCOL_EXT_DEDUP_1: End completions
}
func testDeDuped2(_ x: dedupP) {
x#^PROTOCOL_EXT_DEDUP_2^#
// PROTOCOL_EXT_DEDUP_2: Begin completions, 4 items
// PROTOCOL_EXT_DEDUP_2: Decl[InstanceMethod]/CurrNominal: .foo()[#dedupP.T#]; name=foo()
// PROTOCOL_EXT_DEDUP_2: Decl[InstanceVar]/CurrNominal: .bar[#dedupP.T#]; name=bar
// PROTOCOL_EXT_DEDUP_2: Decl[Subscript]/CurrNominal: [{#Self.T#}][#Self.T#]; name=[Self.T]
// FIXME: duplicate subscript on protocol type rdar://problem/22086900
// PROTOCOL_EXT_DEDUP_2: Decl[Subscript]/CurrNominal: [{#Self.T#}][#Self.T#]; name=[Self.T]
// PROTOCOL_EXT_DEDUP_2: End completions
}
func testDeDuped3<T : dedupP where T.T == Int>(_ x: T) {
x#^PROTOCOL_EXT_DEDUP_3^#
// PROTOCOL_EXT_DEDUP_3: Begin completions, 3 items
// PROTOCOL_EXT_DEDUP_3: Decl[InstanceMethod]/Super: .foo()[#Int#]; name=foo()
// PROTOCOL_EXT_DEDUP_3: Decl[InstanceVar]/Super: .bar[#Int#]; name=bar
// PROTOCOL_EXT_DEDUP_3: Decl[Subscript]/Super: [{#Self.T#}][#Self.T#]; name=[Self.T]
// PROTOCOL_EXT_DEDUP_3: End completions
}
//===--- Check calls that may throw
func globalFuncThrows() throws {}
func globalFuncRethrows(_ x: () throws -> ()) rethrows {}
struct HasThrowingMembers {
func memberThrows() throws {}
func memberRethrows(_ x: () throws -> ()) rethrows {}
init() throws {}
init(x: () throws -> ()) rethrows {}
}
func testThrows001() {
globalFuncThrows#^THROWS1^#
// THROWS1: Begin completions
// THROWS1: Pattern/ExprSpecific: ()[' throws'][#Void#]; name=() throws
// THROWS1: End completions
}
func testThrows002() {
globalFuncRethrows#^THROWS2^#
// THROWS2: Begin completions
// THROWS2: Pattern/ExprSpecific: ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows
// THROWS2: End completions
}
func testThrows003(_ x: HasThrowingMembers) {
x.#^MEMBER_THROWS1^#
// MEMBER_THROWS1: Begin completions
// MEMBER_THROWS1-DAG: Decl[InstanceMethod]/CurrNominal: memberThrows()[' throws'][#Void#]
// MEMBER_THROWS1-DAG: Decl[InstanceMethod]/CurrNominal: memberRethrows({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]
// MEMBER_THROWS1: End completions
}
func testThrows004(_ x: HasThrowingMembers) {
x.memberThrows#^MEMBER_THROWS2^#
// MEMBER_THROWS2: Begin completions
// MEMBER_THROWS2: Pattern/ExprSpecific: ()[' throws'][#Void#]; name=() throws
// MEMBER_THROWS2: End completions
}
func testThrows005(_ x: HasThrowingMembers) {
x.memberRethrows#^MEMBER_THROWS3^#
// MEMBER_THROWS3: Begin completions
// MEMBER_THROWS3: Pattern/ExprSpecific: ({#(x): () throws -> ()##() throws -> ()#})[' rethrows'][#Void#]; name=(x: () throws -> ()) rethrows
// MEMBER_THROWS3: End completions
}
func testThrows006() {
HasThrowingMembers(#^INIT_THROWS1^#
// INIT_THROWS1: Begin completions
// INIT_THROWS1: Decl[Constructor]/CurrNominal: ['('])[' throws'][#HasThrowingMembers#]
// INIT_THROWS1: Decl[Constructor]/CurrNominal: ['(']{#x: () throws -> ()##() throws -> ()#})[' rethrows'][#HasThrowingMembers#]
// INIT_THROWS1: End completions
}
// rdar://21346928
// Just sample some String API to sanity check.
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: characters[#String.CharacterView#]
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf16[#String.UTF16View#]
// AUTOCLOSURE_STRING: Decl[InstanceVar]/CurrNominal: utf8[#String.UTF8View#]
func testWithAutoClosure1(_ x: String?) {
(x ?? "autoclosure").#^AUTOCLOSURE1^#
}
func testWithAutoClosure2(_ x: String?) {
let y = (x ?? "autoclosure").#^AUTOCLOSURE2^#
}
func testWithAutoClosure3(_ x: String?) {
let y = (x ?? "autoclosure".#^AUTOCLOSURE3^#)
}
func testWithAutoClosure4(_ x: String?) {
let y = { let z = (x ?? "autoclosure").#^AUTOCLOSURE4^# }
}
func testWithAutoClosure5(_ x: String?) {
if let y = (x ?? "autoclosure").#^AUTOCLOSURE5^# {
}
}
func testGenericTypealias1() {
typealias MyPair<T> = (T, T)
var x: MyPair<Int>
x.#^GENERIC_TYPEALIAS_1^#
}
// GENERIC_TYPEALIAS_1: Pattern/CurrNominal: 0[#Int#];
// GENERIC_TYPEALIAS_1: Pattern/CurrNominal: 1[#Int#];
func testGenericTypealias2() {
struct Enclose {
typealias MyPair<T> = (T, T)
}
Enclose.#^GENERIC_TYPEALIAS_2^#
}
// GENERIC_TYPEALIAS_2: Decl[TypeAlias]/CurrNominal: MyPair[#(T, T)#];
struct Deprecated {
@available(*, deprecated)
func deprecated(x: Deprecated) {
x.#^DEPRECATED_1^#
}
}
// DEPRECATED_1: Decl[InstanceMethod]/CurrNominal/NotRecommended: deprecated({#x: Deprecated#})[#Void#];
struct Person {
var firstName: String
}
class Other { var nameFromOther: Int = 1 }
class TestDotExprWithNonNominal {
var other: Other
func test1() {
let person = Person(firstName: other.#^DOT_EXPR_NON_NOMINAL_1^#)
// DOT_EXPR_NON_NOMINAL_1-NOT: Instance
// DOT_EXPR_NON_NOMINAL_1: Decl[InstanceVar]/CurrNominal: nameFromOther[#Int#];
// DOT_EXPR_NON_NOMINAL_1-NOT: Instance
}
func test2() {
let person = Person(firstName: 1.#^DOT_EXPR_NON_NOMINAL_2^#)
// DOT_EXPR_NON_NOMINAL_2-NOT: other
// DOT_EXPR_NON_NOMINAL_2-NOT: firstName
// DOT_EXPR_NON_NOMINAL_2: Decl[InstanceVar]/CurrNominal: hashValue[#Int#];
// DOT_EXPR_NON_NOMINAL_2-NOT: other
// DOT_EXPR_NON_NOMINAL_2-NOT: firstName
}
}
| a0d8f806ae69cd83ce5277058916e10a | 57.256809 | 202 | 0.695718 | false | true | false | false |
khizkhiz/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01015-swift-inflightdiagnostic.swift | apache-2.0 | 1 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var d {
func a() -> {
class A {
}
func a(f<h == d: T>()
let foo as String) {
protocol C {
func a<I : a {
var a(")(self)
}
protocol B : Sequence> Any, range.C> V {
struct c(a: T> U) {
}
class B {
var b: [c<T>?) {
}
}
case .C<B : b(b() {
case C("[Byte]()
struct B<T where B {
typealias b = Swift.init(array: a {
return b: P {
case b {
}
}
typealias F = c] {
}
class B : d = {
class A? {
print() -> {
func f<T> Int = [self[T : d {
}
class A {
struct Q<T> <T) {
}({
enum S(bytes: Hashable> (T: T] {
}
typealias b {
i> Any) {
class func b<1 {
i<T) -> [Any, let b {
return "
| 91a552e4f8eb4618260d73797d498d98 | 15.333333 | 87 | 0.58801 | false | false | false | false |
fernandomarins/food-drivr-pt | refs/heads/master | hackathon-for-hunger/User.swift | mit | 1 | //
// User.swift
// hackathon-for-hunger
//
// Created by Ian Gristock on 4/2/16.
// Copyright © 2016 Hacksmiths. All rights reserved.
//
import Foundation
import RealmSwift
import ObjectMapper
enum UserRole: Int {
case Donor = 0
case Driver = 1
}
class User: Object, Mappable {
typealias JsonDict = [String: AnyObject]
dynamic var id: Int = 0
dynamic var auth_token: String?
dynamic var name: String?
dynamic var email: String?
dynamic var avatar: String?
dynamic var organisation: String?
dynamic var phone: String?
dynamic var role = 0
dynamic var settings: Setting?
var userRole: UserRole {
get{
if let userRole = UserRole(rawValue: role) {
return userRole
}
return .Donor
}
set{
role = newValue.rawValue
}
}
required convenience init?(_ map: Map) {
self.init()
}
func mapping(map: Map) {
id <- map["id"]
auth_token <- map["auth_token"]
name <- map["name"]
email <- map["email"]
avatar <- map["avatar"]
organisation <- map["organization.name"]
phone <- map["phone"]
role <- map["role_id"]
settings <- map["setting"]
}
convenience init(dict: JsonDict) {
self.init()
self.id = dict["id"] as! Int
self.auth_token = dict["auth_token"] as? String
self.avatar = dict["avatar"] as? String
self.email = dict["email"] as? String
self.name = dict["name"] as? String
if let org = dict["organization"]?["name"] as? String {
self.organisation = org
}
self.phone = dict["phone"] as? String
self.role = dict["role_id"] as! Int
if let settingDict = dict["setting"] as? JsonDict {
self.settings = Setting(value: settingDict)
}
}
} | 1601b9565786bd15a45dd30f933c1b36 | 25.447368 | 63 | 0.530612 | false | false | false | false |
Andruschenko/SeatTreat | refs/heads/master | SeatTreat/TopSeatView.swift | gpl-2.0 | 1 | //
// TopSeatView.swift
// SeatTreat
//
// Created by Andru on 17/10/15.
// Copyright © 2015 André Kovac. All rights reserved.
//
import UIKit
import Font_Awesome_Swift
@IBDesignable class TopSeatView: UIView {
// Our custom view from the XIB file
var view: UIView!
let faType: FAType = FAType.FADiamond
// Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var icon: UILabel!
@IBInspectable var image: UIImage? {
get {
return imageView.image
}
set(image) {
imageView.image = image
}
}
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
xibSetup()
// set icon
icon.setFAIcon(faType, iconSize: 25)
}
required init?(coder aDecoder: NSCoder) {
// 1. setup any properties here
// 2. call super.init(coder:)
super.init(coder: aDecoder)
// 3. Setup view from .xib file
xibSetup()
// set icon
icon.setFAIcon(faType, iconSize: 25)
}
func xibSetup() {
view = loadViewFromNib()
// use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nibName = "TopSeatView"
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| b28db382282f9965e2d3d365e0f06837 | 24.829545 | 101 | 0.58161 | false | false | false | false |
admkopec/BetaOS | refs/heads/x86_64 | Kernel/Modules/ACPI/SDTHeader.swift | apache-2.0 | 1 | //
// SDTHeader.swift
// Kernel
//
// Created by Adam Kopeć on 10/16/17.
// Copyright © 2017 Adam Kopeć. All rights reserved.
//
struct SDTHeader: CustomStringConvertible {
let Signature: String
let Length: UInt32
let Revision: UInt8
let Checksum: UInt8
let OemID: String
let OemTableID: String
let OemRev: UInt32
let CreatorID: String
let CreatorRev: UInt32
var description: String {
return "\(Signature): \(OemID): \(CreatorID): \(OemTableID): rev: \(Revision)"
}
init(ptr: UnsafeMutablePointer<ACPISDTHeader_t>) {
Signature = String(&ptr.pointee.Signature.0, maxLength: 4)
Length = ptr.pointee.Length
Revision = ptr.pointee.Revision
Checksum = ptr.pointee.Checksum
OemID = String(&ptr.pointee.OEMID.0, maxLength: 6)
OemTableID = String(&ptr.pointee.OEMTableID.0, maxLength: 8)
OemRev = ptr.pointee.OEMRevision
CreatorID = String(&ptr.pointee.CreatorID, maxLength: 4)
CreatorRev = ptr.pointee.CreatorRevision
}
}
| ac2f524eb003479674259535d9b0d416 | 30.428571 | 86 | 0.63 | false | false | false | false |
filestack/filestack-ios | refs/heads/master | Sources/Filestack/UI/Internal/PhotoEditor/EditionController/ViewController/EditorViewController.swift | mit | 1 | //
// EditorViewController.swift
// EditImage
//
// Created by Mihály Papp on 03/07/2018.
// Copyright © 2018 Mihály Papp. All rights reserved.
//
import UIKit
final class EditorViewController: UIViewController, UIGestureRecognizerDelegate {
enum EditMode {
case crop, circle, none
}
var editMode = EditMode.none {
didSet {
turnOff(mode: oldValue)
turnOn(mode: editMode)
updatePaths()
}
}
var editor: ImageEditor?
let bottomToolbar = BottomEditorToolbar()
let topToolbar = TopEditorToolbar()
let preview = UIView()
let imageView = ImageEditorView()
let imageClearBackground = UIView()
private let cropLayer = CropLayer()
private let circleLayer = CircleLayer()
var panGestureRecognizer = UIPanGestureRecognizer()
var pinchGestureRecognizer = UIPinchGestureRecognizer()
lazy var cropHandler = CropGesturesHandler(delegate: self)
lazy var circleHandler = CircleGesturesHandler(delegate: self)
var completion: ((UIImage?) -> Void)?
init(image: UIImage, completion: @escaping (UIImage?) -> Void) {
self.editor = ImageEditor(image: image)
self.completion = completion
super.init(nibName: nil, bundle: nil)
setupGestureRecognizer()
setupView()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension EditorViewController {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updatePaths()
imageClearBackground.frame = imageFrame.applying(CGAffineTransform(translationX: 4, y: 4))
}
}
private extension EditorViewController {
func turnOff(mode: EditMode) {
hideLayer(for: mode)
}
func turnOn(mode: EditMode) {
addLayer(for: mode)
bottomToolbar.isEditing = (mode != .none)
}
}
private extension EditorViewController {
func layer(for mode: EditMode) -> CALayer? {
switch mode {
case .crop: return cropLayer
case .circle: return circleLayer
case .none: return nil
}
}
func isVisible(layer: CALayer) -> Bool {
return imageView.layer.sublayers?.contains(layer) ?? false
}
func addLayer(for mode: EditMode) {
guard let editLayer = layer(for: mode), !isVisible(layer: editLayer) else { return }
imageView.layer.addSublayer(editLayer)
}
func hideLayer(for mode: EditMode) {
layer(for: mode)?.removeFromSuperlayer()
}
func updatePaths() {
switch editMode {
case .crop: updateCropPaths()
case .circle: updateCirclePaths()
case .none: return
}
}
func updateCropPaths() {
cropLayer.imageFrame = imageFrame
cropLayer.cropRect = cropHandler.croppedRect
}
func updateCirclePaths() {
circleLayer.imageFrame = imageFrame
circleLayer.circleCenter = circleHandler.circleCenter
circleLayer.circleRadius = circleHandler.circleRadius
}
}
extension EditorViewController {
@objc func handlePanGesture(recognizer: UIPanGestureRecognizer) {
switch editMode {
case .crop: cropHandler.handlePanGesture(recognizer: recognizer)
case .circle: circleHandler.handlePanGesture(recognizer: recognizer)
case .none: return
}
}
@objc func handlePinchGesture(recognizer: UIPinchGestureRecognizer) {
switch editMode {
case .crop: return
case .circle: circleHandler.handlePinchGesture(recognizer: recognizer)
case .none: return
}
}
}
// MARK: EditCropDelegate
extension EditorViewController: EditCropDelegate {
func updateCropInset(_: UIEdgeInsets) {
updateCropPaths()
}
}
// MARK: EditCircleDelegate
extension EditorViewController: EditCircleDelegate {
func updateCircle(_: CGPoint, radius _: CGFloat) {
updateCirclePaths()
}
}
| 9d18ce55b423ef04a9c1dd0e3a4e8ea4 | 25.350993 | 98 | 0.659211 | false | false | false | false |
wordpress-mobile/WordPress-iOS | refs/heads/trunk | WordPress/Classes/ViewRelated/Domains/Views/ShapeWithTextView.swift | gpl-2.0 | 1 | import SwiftUI
/// A rounded rectangle shape with a white title and a primary background color
struct ShapeWithTextView: View {
var title: String
var body: some View {
Text(title)
}
func largeRoundedRectangle(textColor: Color = .white,
backgroundColor: Color = Appearance.largeRoundedRectangleDefaultTextColor) -> some View {
body
.frame(minWidth: 0, maxWidth: .infinity)
.padding(.all, Appearance.largeRoundedRectangleTextPadding)
.foregroundColor(textColor)
.background(backgroundColor)
.clipShape(RoundedRectangle(cornerRadius: Appearance.largeRoundedRectangleCornerRadius,
style: .continuous))
}
func smallRoundedRectangle(textColor: Color = Appearance.smallRoundedRectangleDefaultTextColor,
backgroundColor: Color = Appearance.smallRoundedRectangleDefaultBackgroundColor) -> some View {
body
.font(.system(size: Appearance.smallRoundedRectangleFontSize))
.padding(Appearance.smallRoundedRectangleInsets)
.foregroundColor(textColor)
.background(backgroundColor)
.clipShape(RoundedRectangle(cornerRadius: Appearance.smallRoundedRectangleCornerRadius,
style: .continuous))
}
private enum Appearance {
// large rounded rectangle
static let largeRoundedRectangleCornerRadius: CGFloat = 8.0
static let largeRoundedRectangleTextPadding: CGFloat = 12.0
static let largeRoundedRectangleDefaultTextColor = Color(UIColor.muriel(color: .primary))
// small rounded rectangle
static let smallRoundedRectangleCornerRadius: CGFloat = 4.0
static let smallRoundedRectangleInsets = EdgeInsets(top: 4.0, leading: 8.0, bottom: 4.0, trailing: 8.0)
static let smallRoundedRectangleDefaultBackgroundColor = Color(UIColor.muriel(name: .green, .shade5))
static let smallRoundedRectangleDefaultTextColor = Color(UIColor.muriel(name: .green, .shade100))
static let smallRoundedRectangleFontSize: CGFloat = 14.0
}
}
| 19c5b15d9bfdd749b512e0391541c1d7 | 46.826087 | 126 | 0.675455 | false | false | false | false |
glassonion1/R9HTTPRequest | refs/heads/master | R9HTTPRequest/HttpJsonClient.swift | mit | 1 | //
// HttpJsonClient.swift
// R9HTTPRequest
//
// Created by taisuke fujita on 2017/10/03.
// Copyright © 2017年 Revolution9. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
public class HttpJsonClient<T: Codable>: HttpClient {
public typealias ResponseType = T
public init() {
}
public func action(method: HttpClientMethodType, url: URL, requestBody: Data?, headers: HTTPHeaders?) -> Observable<T> {
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData)
request.httpMethod = method.rawValue
request.allHTTPHeaderFields = headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = requestBody
let scheduler = ConcurrentDispatchQueueScheduler(qos: .background)
return URLSession.shared.rx.data(request: request).timeout(30, scheduler: scheduler).map { data -> T in
let jsonDecoder = JSONDecoder()
let response = try! jsonDecoder.decode(T.self, from: data)
return response
}
}
}
| dae25f150a49729a555e0cac63f70f89 | 31.676471 | 124 | 0.674167 | false | false | false | false |
marcw/volte-ios | refs/heads/master | Volte/Timeline/TimelineView.swift | agpl-3.0 | 1 | //
// TimelineView.swift
// Volte
//
// Created by Romain Pouclet on 2016-10-12.
// Copyright © 2016 Perfectly-Cooked. All rights reserved.
//
import Foundation
import ReactiveSwift
import UIKit
protocol TimelineViewDelegate: class {
func didPullToRefresh()
func didTap(url: URL)
}
class TimelineView: UIView {
private let tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .plain)
tableView.register(TimelineMessageCell.self, forCellReuseIdentifier: "TimelineItemCell")
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.estimatedRowHeight = 140
tableView.rowHeight = UITableViewAutomaticDimension
tableView.allowsSelection = false
return tableView
}()
private let emptyMessage: UILabel = {
let message = UILabel()
message.text = L10n.Timeline.Empty
message.textColor = .black
message.alpha = 0
message.translatesAutoresizingMaskIntoConstraints = false
return message
}()
private let refreshControl = UIRefreshControl()
fileprivate let viewModel: TimelineViewModel
weak var delegate: TimelineViewDelegate?
init(viewModel: TimelineViewModel) {
self.viewModel = viewModel
super.init(frame: .zero)
backgroundColor = .white
tableView.dataSource = self
tableView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
addSubview(tableView)
addSubview(emptyMessage)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: topAnchor),
tableView.leftAnchor.constraint(equalTo: leftAnchor),
tableView.bottomAnchor.constraint(equalTo: bottomAnchor),
tableView.rightAnchor.constraint(equalTo: rightAnchor),
emptyMessage.centerXAnchor.constraint(equalTo: centerXAnchor),
emptyMessage.centerYAnchor.constraint(equalTo: centerYAnchor)
])
let messagesCount = viewModel.messages.producer.map({ $0.count })
messagesCount.observe(on: UIScheduler()).startWithValues { [weak self] count in
CATransaction.begin()
CATransaction.setCompletionBlock({
self?.tableView.reloadData()
})
self?.refreshControl.endRefreshing()
CATransaction.commit()
UIView.animate(withDuration: 0.3) {
let isEmpty = count == 0
self?.tableView.alpha = isEmpty ? 0 : 1
self?.emptyMessage.alpha = isEmpty ? 1 : 0
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func handleRefresh() {
self.delegate?.didPullToRefresh()
}
}
extension TimelineView: UITableViewDataSource, UITableViewDataSourcePrefetching {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.messages.value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let messages = viewModel.messages.value
let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineItemCell", for: indexPath) as! TimelineMessageCell
cell.delegate = self
cell.configure(item: messages[indexPath.row])
let digest = messages[indexPath.row].author!.data(using: String.Encoding.utf8)!
let avatarURL = URL(string: "https://www.gravatar.com/avatar/\(digest.md5().toHexString())?d=identicon")!
URLSession.shared.dataTask(with: avatarURL) { data, _, _ in
guard let data = data else {
print("Unable to load avatar")
return
}
DispatchQueue.main.async {
cell.avatarView.image = UIImage(data: data)
}
}.resume()
return cell
}
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
}
}
extension TimelineView: TimelineMessageCellDelegate {
func didTap(url: URL) {
delegate?.didTap(url: url)
}
}
| 6a5ad39aa74eadfc6054fd4df2d950f4 | 30.820896 | 124 | 0.651032 | false | false | false | false |
3ph/SplitSlider | refs/heads/master | Example/SplitSlider/ViewController.swift | mit | 1 | //
// ViewController.swift
// SplitSlider
//
// Created by Tomas Friml on 06/22/2017.
//
// MIT License
//
// Copyright (c) 2017 Tomas Friml
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import SplitSlider
class ViewController: UIViewController {
@IBOutlet weak var splitSlider: SplitSlider!
@IBOutlet weak var snapToStep: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
splitSlider.delegate = self
splitSlider.labelFont = UIFont.systemFont(ofSize: UIFont.smallSystemFontSize)
splitSlider.left.step = 30
}
@IBAction func snapToStepToggle(_ sender: Any) {
if let toggle = sender as? UISwitch {
splitSlider.snapToStep = toggle.isOn
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController : SplitSliderDelegate {
func slider(_ slider: SplitSlider, didSelect portion: SplitSliderPortion?) {
let portionString = portion == slider.left ? "left" : "right"
NSLog("Selected part: \(portion == nil ? "none" : portionString)")
}
func slider(_ slider: SplitSlider, didUpdate value: CGFloat, for portion: SplitSliderPortion) {
NSLog("Current value: \(value)")
}
}
| 2cb27a646ca8923b4cca4335741e815d | 34.865672 | 99 | 0.697045 | false | false | false | false |
MangoMade/MMSegmentedControl | refs/heads/master | Example/Example/SegmentedViewController.swift | mit | 1 | //
// SegmentedViewController.swift
// MMSegmentedControl
//
// Created by Aqua on 2017/4/17.
// Copyright © 2017年 Aqua. All rights reserved.
//
import UIKit
import MMSegmentedControl
class ChildViewController: UIViewController {
var backgroundColor: UIColor = .white
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
print(#function)
view.backgroundColor = backgroundColor
}
}
class SegmentedViewController: UIViewController {
private var children = [UIViewController]()
private let segmentedView = SegmentedControlView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
automaticallyAdjustsScrollViewInsets = false
let titles = ["推荐", "开庭", "开庭", "开庭", "开庭"]
let items = titles.enumerated().map { (index, title) -> SegmentedControlViewItem in
let viewController = ChildViewController()
viewController.backgroundColor = index % 2 == 1 ? UIColor.white : UIColor.lightGray
addChildViewController(viewController)
viewController.didMove(toParentViewController: self)
children.append(viewController)
// let label = UILabel()
// label.text = title
// label.bounds = CGRect(x: 0, y: 0, width: 100, height: 50)
// label.center = CGPoint(x: Screen.width / 2, y: 100)
// label.textAlignment = .center
// viewController.view.addSubview(label)
return SegmentedControlViewItem(title: title, childViewController: viewController)
}
segmentedView.items = items
segmentedView.segmentedControl.shouldFill = true
segmentedView.segmentedControl.leftMargin = 30
segmentedView.segmentedControl.rightMargin = 30
segmentedView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(segmentedView)
// segmentedView.frame = CGRect(x: 0,
// y: Screen.navBarHeight,
// width: Screen.width,
// height: Screen.height - Screen.navBarHeight)
NSLayoutConstraint(item: segmentedView,
attribute: .left,
relatedBy: .equal,
toItem: view,
attribute: .left,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: segmentedView,
attribute: .right,
relatedBy: .equal,
toItem: view,
attribute: .right,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: segmentedView,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: segmentedView,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .top,
multiplier: 1,
constant: Screen.navBarHeight).isActive = true
let add = UIBarButtonItem(title: "add", style: .plain, target: self, action: #selector(add(_:)))
let pop = UIBarButtonItem(title: "delete", style: .plain, target: self, action: #selector(pop(_:)))
navigationItem.rightBarButtonItems = [pop, add]
}
@objc func add(_ sender: UIBarButtonItem) {
let viewController = UIViewController()
viewController.view.backgroundColor = .white
addChildViewController(viewController)
viewController.didMove(toParentViewController: self)
children.append(viewController)
let label = UILabel()
label.text = title
label.bounds = CGRect(x: 0, y: 0, width: 100, height: 50)
label.center = CGPoint(x: Screen.width / 2, y: 100)
label.textAlignment = .center
viewController.view.addSubview(label)
segmentedView.items.append(SegmentedControlViewItem(title: "开庭", childViewController: viewController))
}
@objc func pop(_ sender: UIBarButtonItem) {
let _ = segmentedView.items.popLast()
// segmentedView.segmentedControlHeight = 50
}
}
| 8c3d4825ca2e5b987866448536fe6c94 | 36.296875 | 110 | 0.547759 | false | false | false | false |
IvoPaunov/selfie-apocalypse | refs/heads/master | Selfie apocalypse/Frameworks/DCKit/UITextFields/DCMandatoryNumberTextField.swift | mit | 1 | //
// MandatoryNumberTextField.swift
// DCKit
//
// Created by Andrey Gordeev on 11/03/15.
// Copyright (c) 2015 Andrey Gordeev ([email protected]). All rights reserved.
//
import UIKit
/// Allows to set a max possible value.
public class DCMandatoryNumberTextField: DCMandatoryTextField {
@IBInspectable public var maxValue: Float = 999
// MARK: - Initializers
// IBDesignables require both of these inits, otherwise we'll get an error: IBDesignable View Rendering times out.
// http://stackoverflow.com/questions/26772729/ibdesignable-view-rendering-times-out
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Build control
override public func customInit() {
super.customInit()
keyboardType = UIKeyboardType.DecimalPad
}
// MARK: - Validation
override public func isValid() -> Bool {
let value = (text ?? "" as NSString).floatValue
var valid = value < maxValue
// If the field is Mandatory and empty - it's invalid
if text == "" {
valid = !isMandatory
}
selected = !valid
return valid
}
}
| af2d511ea9602177ba3a0533bb8dc48e | 24.75 | 118 | 0.613891 | false | false | false | false |
ZackKingS/Tasks | refs/heads/master | task/Classes/Main/View/RefreshHeder.swift | apache-2.0 | 1 | //
// HomeRefreshHeder.swift
// TodayNews
//
// Created by 杨蒙 on 2017/8/17.
// Copyright © 2017年 hrscy. All rights reserved.
//
import MJRefresh
class RefreshHeder: MJRefreshGifHeader {
override func prepare() {
super.prepare()
// 设置普通状态图片
var images = [UIImage]()
for index in 0..<30 {
let image = UIImage(named: "dropdown_0\(index)")
images.append(image!)
}
setImages(images, for: .idle)
// 设置即将刷新状态的动画图片(一松开就会刷新的状态)
var refreshingImages = [UIImage]()
for index in 0..<16 {
let image = UIImage(named: "dropdown_loading_0\(index)")
refreshingImages.append(image!)
}
// 设置正在刷新状态的动画图片
setImages(refreshingImages, for: .refreshing)
/// 设置state状态下的文字
setTitle("下拉推荐", for: .idle)
setTitle("松开推荐", for: .pulling)
setTitle("推荐中", for: .refreshing)
}
override func placeSubviews() {
super.placeSubviews()
gifView.contentMode = .center
gifView.frame = CGRect(x: 0, y: 4, width: mj_w, height: 25)
stateLabel.font = UIFont.systemFont(ofSize: 12)
stateLabel.frame = CGRect(x: 0, y: 35, width: mj_w, height: 14)
}
}
| 459ce7061fe1502023cb7091437b4602 | 28.046512 | 71 | 0.577262 | false | false | false | false |
mauryat/firefox-ios | refs/heads/master | Shared/Functions.swift | mpl-2.0 | 3 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import SwiftyJSON
// Pipelining.
precedencegroup PipelinePrecedence {
associativity: left
}
infix operator |> : PipelinePrecedence
public func |> <T, U>(x: T, f: (T) -> U) -> U {
return f(x)
}
// Basic currying.
public func curry<A, B>(_ f: @escaping (A) -> B) -> (A) -> B {
return { a in
return f(a)
}
}
public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
return { a in
return { b in
return f(a, b)
}
}
}
public func curry<A, B, C, D>(_ f: @escaping (A, B, C) -> D) -> (A) -> (B) -> (C) -> D {
return { a in
return { b in
return { c in
return f(a, b, c)
}
}
}
}
public func curry<A, B, C, D, E>(_ f: @escaping (A, B, C, D) -> E) -> (A, B, C) -> (D) -> E {
return { (a, b, c) in
return { d in
return f(a, b, c, d)
}
}
}
// Function composition.
infix operator •
public func •<T, U, V>(f: @escaping (T) -> U, g: @escaping (U) -> V) -> (T) -> V {
return { t in
return g(f(t))
}
}
public func •<T, V>(f: @escaping (T) -> Void, g: @escaping () -> V) -> (T) -> V {
return { t in
f(t)
return g()
}
}
public func •<V>(f: @escaping () -> Void, g: @escaping () -> V) -> () -> V {
return {
f()
return g()
}
}
// Why not simply provide an override for ==? Well, that's scary, and can accidentally recurse.
// This is enough to catch arrays, which Swift will delegate to element-==.
public func optArrayEqual<T: Equatable>(_ lhs: [T]?, rhs: [T]?) -> Bool {
switch (lhs, rhs) {
case (.none, .none):
return true
case (.none, _):
return false
case (_, .none):
return false
default:
// This delegates to Swift's own array '==', which calls T's == on each element.
return lhs! == rhs!
}
}
/**
* Given an array, return an array of slices of size `by` (possibly excepting the last slice).
*
* If `by` is longer than the input, returns a single chunk.
* If `by` is less than 1, acts as if `by` is 1.
* If the length of the array isn't a multiple of `by`, the final slice will
* be smaller than `by`, but never empty.
*
* If the input array is empty, returns an empty array.
*/
public func chunk<T>(_ arr: [T], by: Int) -> [ArraySlice<T>] {
var result = [ArraySlice<T>]()
var chunk = -1
let size = max(1, by)
for (index, elem) in arr.enumerated() {
if index % size == 0 {
result.append(ArraySlice<T>())
chunk += 1
}
result[chunk].append(elem)
}
return result
}
public func chunkCollection<E, X, T: Collection>(_ items: T, by: Int, f: ([E]) -> [X]) -> [X] where T.Iterator.Element == E {
assert(by >= 0)
let max = by > 0 ? by : 1
var i = 0
var acc: [E] = []
var results: [X] = []
var iter = items.makeIterator()
while let item = iter.next() {
if i >= max {
results.append(contentsOf: f(acc))
acc = []
i = 0
}
acc.append(item)
i += 1
}
if !acc.isEmpty {
results.append(contentsOf: f(acc))
}
return results
}
public extension Sequence {
// [T] -> (T -> K) -> [K: [T]]
// As opposed to `groupWith` (to follow Haskell's naming), which would be
// [T] -> (T -> K) -> [[T]]
func groupBy<Key, Value>(_ selector: (Self.Iterator.Element) -> Key, transformer: (Self.Iterator.Element) -> Value) -> [Key: [Value]] {
var acc: [Key: [Value]] = [:]
for x in self {
let k = selector(x)
var a = acc[k] ?? []
a.append(transformer(x))
acc[k] = a
}
return acc
}
func zip<S: Sequence>(_ elems: S) -> [(Self.Iterator.Element, S.Iterator.Element)] {
var rights = elems.makeIterator()
return self.flatMap { lhs in
guard let rhs = rights.next() else {
return nil
}
return (lhs, rhs)
}
}
}
public func optDictionaryEqual<K: Equatable, V: Equatable>(_ lhs: [K: V]?, rhs: [K: V]?) -> Bool {
switch (lhs, rhs) {
case (.none, .none):
return true
case (.none, _):
return false
case (_, .none):
return false
default:
return lhs! == rhs!
}
}
/**
* Return members of `a` that aren't nil, changing the type of the sequence accordingly.
*/
public func optFilter<T>(_ a: [T?]) -> [T] {
return a.flatMap { $0 }
}
/**
* Return a new map with only key-value pairs that have a non-nil value.
*/
public func optFilter<K, V>(_ source: [K: V?]) -> [K: V] {
var m = [K: V]()
for (k, v) in source {
if let v = v {
m[k] = v
}
}
return m
}
/**
* Map a function over the values of a map.
*/
public func mapValues<K, T, U>(_ source: [K: T], f: ((T) -> U)) -> [K: U] {
var m = [K: U]()
for (k, v) in source {
m[k] = f(v)
}
return m
}
public func findOneValue<K, V>(_ map: [K: V], f: (V) -> Bool) -> V? {
for v in map.values {
if f(v) {
return v
}
}
return nil
}
/**
* Take a JSON array, returning the String elements as an array.
* It's usually convenient for this to accept an optional.
*/
public func jsonsToStrings(_ arr: [JSON]?) -> [String]? {
return arr?.flatMap { $0.stringValue }
}
// Encapsulate a callback in a way that we can use it with NSTimer.
private class Callback {
private let handler:() -> Void
init(handler:@escaping () -> Void) {
self.handler = handler
}
@objc
func go() {
handler()
}
}
/**
* Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call
* Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires.
**/
public func debounce(_ delay: TimeInterval, action:@escaping () -> Void) -> () -> Void {
let callback = Callback(handler: action)
var timer: Timer?
return {
// If calling again, invalidate the last timer.
if let timer = timer {
timer.invalidate()
}
timer = Timer(timeInterval: delay, target: callback, selector: #selector(Callback.go), userInfo: nil, repeats: false)
RunLoop.current.add(timer!, forMode: RunLoopMode.defaultRunLoopMode)
}
}
| 863a1e86a34d804e1dead6ebc85944b5 | 25.126482 | 139 | 0.530862 | false | false | false | false |
zmeriksen/Layers | refs/heads/master | Layers/LayerHandler.swift | mit | 1 | //
// LayerHandler.swift
// Layers
//
// Created by Zach Eriksen on 6/26/15.
// Copyright (c) 2015 Leif. All rights reserved.
//
import Foundation
import UIKit
let purple = UIColor(red: 115/255, green: 115/255, blue: 150/255, alpha: 1)
let blue = UIColor(red: 102/255, green: 168/255, blue: 174/255, alpha: 1)
let lightGreen = UIColor(red: 196/255, green: 213/255, blue: 173/255, alpha: 1)
let darkGreen = UIColor(red: 107/255, green: 134/255, blue: 113/255, alpha: 1)
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
class LayerHandler : UIView{
fileprivate let WarningLayer = [
"WARNING: Layer limit of 8 hit",
"WARNING: Default init will have frame of x: 0, y: 0, width: \(screenWidth), height: \(screenHeight)",
"WARNING: You must have at least one layer!"
]
var layers : [Layer] = [] {
didSet{
layerHeight = frame.height/CGFloat(layers.count)
var y : CGFloat = 0
for layer in layers{
layer.frame = CGRect(x: layer.frame.origin.x, y: y, width: layer.frame.width, height: layerHeight!)
layer.updateLayer()
layer.layerHeight = layerHeight
y += layerHeight!
}
}
}
fileprivate var y : CGFloat = 0
fileprivate var tagForLayers = 0
fileprivate var layerHeight : CGFloat?
init(){
super.init(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))
layerHeight = frame.height
print(WarningLayer[1])
}
override init(frame: CGRect) {
super.init(frame: frame)
layerHeight = frame.height
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func layerPressed(_ sender : AnyObject){
for layer in layers{
switch sender.tag! {
case layer.tag:
layer.animateToMaximizedPosition()
case -1..<layer.tag:
layer.animateBackToOriginalPosition()
default:
layer.animateToMinimizedPosition()
}
}
}
func resetLayersToOriginalPosition(){
for layer in layers{
layer.animateBackToOriginalPosition()
}
}
func addLayer(_ color : UIColor, title : String) -> Layer?{
if layers.count >= 8 {
print(WarningLayer[0])
return nil
}
resetLayersToOriginalPosition()
let layer = Layer(y: y, color: color, title: title, tag: tagForLayers,layerWidth: frame.width, layerHeight : layerHeight!)
tagForLayers += 1
y += layerHeight!
let button = UIButton(frame: CGRect(x: 0, y: 0, width: frame.width, height: layerHeight!))
button.addTarget(self, action: #selector(LayerHandler.layerPressed(_:)), for: UIControlEvents.touchUpInside)
button.tag = layer.tag
layer.addSubview(button)
layer.sendSubview(toBack: button)
layers.append(layer)
addSubview(layer)
return layer
}
func layerWithTitle(_ title : String) -> Layer? {
for layer in layers {
if layer.label?.text == title {
return layer
}
}
return nil
}
func removeLayerWithTitle(_ title : String){
if layers.count == 1 {
print(WarningLayer[2])
return
}
for layer in layers {
layer.removeFromSuperview()
if layer.label?.text == title {
layers.remove(at: layer.tag)
}
}
resetLayersTags()
}
func removeLayerWithTag(_ tag : UInt32){
if layers.count == 1 {
print(WarningLayer[2])
return
}
for l in layers {
l.removeFromSuperview()
if UInt32(l.label!.tag) == tag {
layers.remove(at: l.tag)
}
}
resetLayersTags()
}
fileprivate func resetLayersTags(){
tagForLayers = 0
for layer in layers {
layer.tag = tagForLayers
for sub in layer.subviews {
if let button : UIButton = sub as? UIButton {
button.frame = CGRect(x: 0, y: 0, width: layer.frame.width, height: layer.frame.height)
button.tag = tagForLayers
tagForLayers += 1
}
}
addSubview(layer)
}
resetLayersToOriginalPosition()
}
}
| 2b6949ba750fcaf575a61d32cae41b14 | 30.306122 | 130 | 0.556932 | false | false | false | false |
wangruofeng/ClassicPhotos-Starter-fixed | refs/heads/master | ClassicPhotos/ListViewController.swift | mit | 1 | //
// ListViewController.swift
// ClassicPhotos
//
// Created by Richard Turton on 03/07/2014.
// Copyright (c) 2014 raywenderlich. All rights reserved.
//
import UIKit
import CoreImage
let dataSourceURL = NSURL(string:"http://www.raywenderlich.com/downloads/ClassicPhotosDictionary.plist")
class ListViewController: UITableViewController {
var photos = [PhotoRecord]()
let pendingOperations = PendingOperations()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Classic Photos"
fetchPhotoDetails()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fetchPhotoDetails() {
let request = NSURLRequest(URL:dataSourceURL!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if data != nil {
var datasourceDictionary = [:]
do {
datasourceDictionary = try NSPropertyListSerialization.propertyListWithData(data!, options: NSPropertyListMutabilityOptions.Immutable, format: nil) as! NSDictionary as! [String : String]
} catch {
print("Error occured while reading from the plist file")
}
for(key, value) in datasourceDictionary {
let name = key as? String
let url = NSURL(string:value as? String ?? "")
if name != nil && url != nil {
let photoRecord = PhotoRecord(name:name!, url:url!)
self.photos.append(photoRecord)
}
}
self.tableView.reloadData()
}
if error != nil {
let alert = UIAlertView(title:"Oops!",message:error!.localizedDescription, delegate:nil, cancelButtonTitle:"OK")
alert.show()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
// #pragma mark - Table view data source
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return photos.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath)
//1
if cell.accessoryView == nil {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
cell.accessoryView = indicator
}
let indicator = cell.accessoryView as! UIActivityIndicatorView
//2
let photoDetails = photos[indexPath.row]
//3
cell.textLabel?.text = photoDetails.name
cell.imageView?.image = photoDetails.image
//4
switch (photoDetails.state){
case .Filtered:
indicator.stopAnimating()
case .Failed:
indicator.stopAnimating()
cell.textLabel?.text = "Failed to load"
case .New, .Downloaded:
indicator.startAnimating()
if (!tableView.dragging && !tableView.decelerating) {
self.startOperationsForPhotoRecord(photoDetails, indexPath: indexPath)
}
}
return cell
}
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
//1
suspendAllOperations()
}
override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// 2
if !decelerate {
loadImagesForOnscreenCells()
resumeAllOperations()
}
}
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
// 3
loadImagesForOnscreenCells()
resumeAllOperations()
}
func suspendAllOperations () {
pendingOperations.downloadQueue.suspended = true
pendingOperations.filtrationQueue.suspended = true
}
func resumeAllOperations () {
pendingOperations.downloadQueue.suspended = false
pendingOperations.filtrationQueue.suspended = false
}
func loadImagesForOnscreenCells () {
//1
if let pathsArray = tableView.indexPathsForVisibleRows {
//2
var allPendingOperations = Set(pendingOperations.downloadsInProgress.keys)
allPendingOperations.unionInPlace(pendingOperations.filtrationsInProgress.keys)
//3
var toBeCancelled = allPendingOperations
let visiblePaths = Set(pathsArray as [NSIndexPath])
toBeCancelled.subtractInPlace(visiblePaths)
//4
var toBeStarted = visiblePaths
toBeStarted.subtractInPlace(allPendingOperations)
// 5
for indexPath in toBeCancelled {
if let pendingDownload = pendingOperations.downloadsInProgress[indexPath] {
pendingDownload.cancel()
}
pendingOperations.downloadsInProgress.removeValueForKey(indexPath)
if let pendingFiltration = pendingOperations.filtrationsInProgress[indexPath] {
pendingFiltration.cancel()
}
pendingOperations.filtrationsInProgress.removeValueForKey(indexPath)
}
// 6
for indexPath in toBeStarted {
let indexPath = indexPath as NSIndexPath
let recordToProcess = self.photos[indexPath.row]
startOperationsForPhotoRecord(recordToProcess, indexPath: indexPath)
}
}
}
func startOperationsForPhotoRecord(photoDetails: PhotoRecord, indexPath: NSIndexPath){
switch (photoDetails.state) {
case .New:
startDownloadForRecord(photoDetails, indexPath: indexPath)
case .Downloaded:
startFiltrationForRecord(photoDetails, indexPath: indexPath)
default:
NSLog("do nothing")
}
}
func startDownloadForRecord(photoDetails: PhotoRecord, indexPath: NSIndexPath){
//1
if let _ = pendingOperations.downloadsInProgress[indexPath] {
return
}
//2
let downloader = ImageDownloader(photoRecord: photoDetails)
//3
downloader.completionBlock = {
if downloader.cancelled {
return
}
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.downloadsInProgress.removeValueForKey(indexPath)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
})
}
//4
pendingOperations.downloadsInProgress[indexPath] = downloader
//5
pendingOperations.downloadQueue.addOperation(downloader)
}
func startFiltrationForRecord(photoDetails: PhotoRecord, indexPath: NSIndexPath){
if let _ = pendingOperations.filtrationsInProgress[indexPath]{
return
}
let filterer = ImageFiltration(photoRecord: photoDetails)
filterer.completionBlock = {
if filterer.cancelled {
return
}
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.filtrationsInProgress.removeValueForKey(indexPath)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
})
}
pendingOperations.filtrationsInProgress[indexPath] = filterer
pendingOperations.filtrationQueue.addOperation(filterer)
}
}
| bf7f02ea0bfb429a62101579a664f6b0 | 30.127193 | 194 | 0.688037 | false | false | false | false |
TonnyTao/HowSwift | refs/heads/master | Funny Swift.playground/Pages/GCD.xcplaygroundpage/Contents.swift | mit | 1 | import Foundation
import Dispatch
import PlaygroundSupport
//: The most common GCD patterns: run IO operation or compute in background thread then update UI in main thread
DispatchQueue.global().async {
// Cocurrent thread
dispatchPrecondition(condition: .notOnQueue(DispatchQueue.main))
DispatchQueue.main.async {
// Main thread
}
}
//: Perform mutiple times concurrently
DispatchQueue.concurrentPerform(iterations: 2) { (i) in
print(i)
}
//: Cancelable block only existed in NSOperation in old times, and before Swift3.0 we have to use complex tricks to implement it in GCD. But now cancelable closure is easy in Swift3.0.
let workItem = DispatchWorkItem {
print("a")
}
DispatchQueue.global().async(execute: workItem)
workItem.cancel()
//: dispatch_once is no longer available in Swift. Goodbye, dispatch_once, Hello, globals initialize or static properties.
// Static properties (useful for singletons).
class Object {
static let sharedInstance = Object()
//or
static let sharedInstance1 = { () -> Object in
let obj = Object()
obj.doSomething()
return obj
}()
func doSomething() {
}
}
// Global constant.
let variable: Object = {
let variable = Object()
variable.doSomething()
return variable
}()
//: Delay perform after 3 seconds
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
print("World")
}
print("Hello ")
//: Group, parallel
let group1 = DispatchGroup()
group1.enter()
DispatchQueue.global().sync { //remote api fetch
group1.leave()
}
group1.enter()
DispatchQueue.global().sync { //another remote api fetch
group1.leave()
}
group1.notify(queue: .main) {
print("parallel end")
}
//: Group with different queue
let group = DispatchGroup()
let queue1 = DispatchQueue(label: "networking")
let queue2 = DispatchQueue(label: "process")
queue1.async(group: group) {
print("task 1")
}
queue2.async(group: group) {
print("task 2")
}
group.notify(queue: .main) {
print("end")
}
PlaygroundPage.current.needsIndefiniteExecution = true
| 0f9c6598ead201610d989b8b3e2236d5 | 19.921569 | 184 | 0.686504 | false | false | false | false |
thelukester92/swift-engine | refs/heads/master | swift-engine/Engine/Systems/LGAnimationSystem.swift | mit | 1 | //
// LGAnimationSystem.swift
// swift-engine
//
// Created by Luke Godfrey on 8/8/14.
// Copyright (c) 2014 Luke Godfrey. See LICENSE.
//
public final class LGAnimationSystem: LGSystem
{
public enum Event: String
{
case AnimationEnd = "animationEnd"
}
var sprites = [LGSprite]()
var animatables = [LGAnimatable]()
var animations = [LGAnimation?]()
public override init() {}
override public func accepts(entity: LGEntity) -> Bool
{
return entity.has(LGSprite) && entity.has(LGAnimatable)
}
override public func add(entity: LGEntity)
{
super.add(entity)
let sprite = entity.get(LGSprite)!
let animatable = entity.get(LGAnimatable)!
sprites.append(sprite)
animatables.append(animatable)
animations.append(nil)
}
override public func remove(index: Int)
{
super.remove(index)
sprites.removeAtIndex(index)
animatables.removeAtIndex(index)
animations.removeAtIndex(index)
}
override public func update()
{
for id in 0 ..< entities.count
{
let sprite = sprites[id]
let animatable = animatables[id]
if let animation = animatable.currentAnimation
{
if animations[id] == nil || animations[id]! != animation
{
animations[id] = animation
sprite.frame = animation.start
animatable.counter = 0
}
if animation.end > animation.start
{
if ++animatable.counter > animation.ticksPerFrame
{
animatable.counter = 0
if ++sprite.frame > animation.end
{
if animation.loops
{
sprite.frame = animation.start
}
else
{
sprite.frame = animation.end
}
if let scriptable = entities[id].get(LGScriptable)
{
scriptable.events.append(LGScriptable.Event(name: Event.AnimationEnd.rawValue))
}
}
}
}
}
}
}
}
| ae0cf0dedc5610783c6f751cd9ac7f58 | 19.362637 | 87 | 0.636805 | false | false | false | false |
arvedviehweger/swift | refs/heads/master | benchmark/single-source/ByteSwap.swift | apache-2.0 | 1 | //===--- ByteSwap.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks performance of Swift byte swap.
// rdar://problem/22151907
import Foundation
import TestsUtils
// a naive O(n) implementation of byteswap.
func byteswap_n(_ a: UInt64) -> UInt64 {
var result = ((a & 0x00000000000000FF) << 56)
result |= ((a & 0x000000000000FF00) << 40)
result |= ((a & 0x0000000000FF0000) << 24)
result |= ((a & 0x00000000FF000000) << 8)
result |= ((a & 0x000000FF00000000) >> 8)
result |= ((a & 0x0000FF0000000000) >> 24)
result |= ((a & 0x00FF000000000000) >> 40)
result |= ((a & 0xFF00000000000000) >> 56)
return result
}
// a O(logn) implementation of byteswap.
func byteswap_logn(_ a: UInt64) -> UInt64 {
var a = a
a = (a & 0x00000000FFFFFFFF) << 32 | (a & 0xFFFFFFFF00000000) >> 32
a = (a & 0x0000FFFF0000FFFF) << 16 | (a & 0xFFFF0000FFFF0000) >> 16
a = (a & 0x00FF00FF00FF00FF) << 8 | (a & 0xFF00FF00FF00FF00) >> 8
return a
}
@inline(never)
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.")
CheckResults(byteswap_logn(byteswap_n(9129)) == 9129, "Incorrect results in ByteSwap.")
CheckResults(byteswap_logn(byteswap_n(3333)) == 3333, "Incorrect results in ByteSwap.")
}
}
| 2678ee360a100f8f6e415358cbe9f7bf | 36.326531 | 91 | 0.611263 | false | false | false | false |
envoyproxy/envoy | refs/heads/main | mobile/test/swift/integration/DirectResponsePrefixPathMatchIntegrationTest.swift | apache-2.0 | 2 | import Envoy
import XCTest
final class DirectResponsePrefixPathMatchIntegrationTest: XCTestCase {
func testDirectResponseWithPrefixMatch() {
let headersExpectation = self.expectation(description: "Response headers received")
let dataExpectation = self.expectation(description: "Response data received")
let requestHeaders = RequestHeadersBuilder(
method: .get, authority: "127.0.0.1", path: "/v1/foo/bar?param=1"
).build()
let engine = TestEngineBuilder()
.addDirectResponse(
.init(
matcher: RouteMatcher(pathPrefix: "/v1/foo"),
status: 200, body: "hello world", headers: ["x-response-foo": "aaa"]
)
)
.build()
var responseBuffer = Data()
engine
.streamClient()
.newStreamPrototype()
.setOnResponseHeaders { headers, endStream, _ in
XCTAssertEqual(200, headers.httpStatus)
XCTAssertEqual(["aaa"], headers.value(forName: "x-response-foo"))
XCTAssertFalse(endStream)
headersExpectation.fulfill()
}
.setOnResponseData { data, endStream, _ in
responseBuffer.append(contentsOf: data)
if endStream {
XCTAssertEqual("hello world", String(data: responseBuffer, encoding: .utf8))
dataExpectation.fulfill()
}
}
.start()
.sendHeaders(requestHeaders, endStream: true)
let expectations = [headersExpectation, dataExpectation]
XCTAssertEqual(.completed, XCTWaiter().wait(for: expectations, timeout: 10, enforceOrder: true))
engine.terminate()
}
}
| 7c358d2139d2448d97b5513b9dc525d7 | 32.340426 | 100 | 0.663689 | false | true | false | false |
danielmartinprieto/AudioPlayer | refs/heads/master | AudioPlayer/AudioPlayer/player/extensions/AudioPlayer+PlayerEvent.swift | mit | 1 | //
// AudioPlayer+PlayerEvent.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 03/04/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import CoreMedia
extension AudioPlayer {
/// Handles player events.
///
/// - Parameters:
/// - producer: The event producer that generated the player event.
/// - event: The player event.
func handlePlayerEvent(from producer: EventProducer, with event: PlayerEventProducer.PlayerEvent) {
switch event {
case .endedPlaying(let error):
if let error = error {
state = .failed(.foundationError(error))
} else {
nextOrStop()
}
case .interruptionBegan where state.isPlaying || state.isBuffering:
//We pause the player when an interruption is detected
backgroundHandler.beginBackgroundTask()
pausedForInterruption = true
pause()
case .interruptionEnded(let shouldResume) where pausedForInterruption:
if resumeAfterInterruption && shouldResume {
resume()
}
pausedForInterruption = false
backgroundHandler.endBackgroundTask()
case .loadedDuration(let time):
if let currentItem = currentItem, let time = time.ap_timeIntervalValue {
updateNowPlayingInfoCenter()
delegate?.audioPlayer(self, didFindDuration: time, for: currentItem)
}
case .loadedMetadata(let metadata):
if let currentItem = currentItem, !metadata.isEmpty {
currentItem.parseMetadata(metadata)
delegate?.audioPlayer(self, didUpdateEmptyMetadataOn: currentItem, withData: metadata)
}
case .loadedMoreRange:
if let currentItem = currentItem, let currentItemLoadedRange = currentItemLoadedRange {
delegate?.audioPlayer(self, didLoad: currentItemLoadedRange, for: currentItem)
if bufferingStrategy == .playWhenPreferredBufferDurationFull && state == .buffering,
let currentItemLoadedAhead = currentItemLoadedAhead,
currentItemLoadedAhead.isNormal,
currentItemLoadedAhead >= self.preferredBufferDurationBeforePlayback {
playImmediately()
}
}
case .progressed(let time):
if let currentItemProgression = time.ap_timeIntervalValue, let item = player?.currentItem,
item.status == .readyToPlay {
//This fixes the behavior where sometimes the `playbackLikelyToKeepUp` isn't
//changed even though it's playing (happens mostly at the first play though).
if state.isBuffering || state.isPaused {
if shouldResumePlaying {
stateBeforeBuffering = nil
state = .playing
player?.rate = rate
} else {
player?.rate = 0
state = .paused
}
backgroundHandler.endBackgroundTask()
}
//Then we can call the didUpdateProgressionTo: delegate method
let itemDuration = currentItemDuration ?? 0
let percentage = (itemDuration > 0 ? Float(currentItemProgression / itemDuration) * 100 : 0)
delegate?.audioPlayer(self, didUpdateProgressionTo: currentItemProgression, percentageRead: percentage)
}
case .readyToPlay:
//There is enough data in the buffer
if shouldResumePlaying {
stateBeforeBuffering = nil
state = .playing
player?.rate = rate
playImmediately()
} else {
player?.rate = 0
state = .paused
}
//TODO: where to start?
retryEventProducer.stopProducingEvents()
backgroundHandler.endBackgroundTask()
case .routeChanged:
//In some route changes, the player pause automatically
//TODO: there should be a check if state == playing
if let currentItemTimebase = player?.currentItem?.timebase, CMTimebaseGetRate(currentItemTimebase) == 0 {
state = .paused
}
case .sessionMessedUp:
#if os(iOS) || os(tvOS)
//We reenable the audio session directly in case we're in background
setAudioSession(active: true)
//Aaaaand we: restart playing/go to next
state = .stopped
qualityAdjustmentEventProducer.interruptionCount += 1
retryOrPlayNext()
#endif
case .startedBuffering:
//The buffer is empty and player is loading
if case .playing = state, !qualityIsBeingChanged {
qualityAdjustmentEventProducer.interruptionCount += 1
}
stateBeforeBuffering = state
if reachability.isReachable() || (currentItem?.soundURLs[currentQuality]?.ap_isOfflineURL ?? false) {
state = .buffering
} else {
state = .waitingForConnection
}
backgroundHandler.beginBackgroundTask()
default:
break
}
}
}
| 6945704eb99203e5793d1a4d8ce3cda2 | 38.57971 | 119 | 0.571219 | false | false | false | false |
icanzilb/EventBlankApp | refs/heads/master | EventBlank/EventBlank/AppDelegate.swift | mit | 2 | //
// AppDelegate.swift
// EventBlank
//
// Created by Marin Todorov on 3/12/15.
// Copyright (c) 2015 Underplot ltd. All rights reserved.
//
import UIKit
import SQLite
import MAThemeKit
import DynamicColor
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let databaseProvider = DatabaseProvider(
path: FilePath(inLibrary: eventDataFileName),
defaultPath: FilePath(inBundle: eventDataFileName),
preferNewerSourceFile: true)
let appDataProvider = DatabaseProvider(
path: FilePath(inLibrary: appDataFileName),
defaultPath: FilePath(inBundle: appDataFileName))
var event: Row!
var updateManager: UpdateManager?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
loadEventData()
//start the update manager if there's a remote file
if let updateUrlString = event[Event.updateFileUrl], let updateUrl = NSURL(string: updateUrlString) where !updateUrlString.isEmpty {
backgroundQueue({
self.startUpdateManager(url: updateUrl)
})
}
return true
}
func startUpdateManager(url updateUrl: NSURL) {
updateManager = UpdateManager(
filePath: FilePath(inLibrary: eventDataFileName),
remoteURL: updateUrl, autostart: false)
updateManager!.fileBinder.addAction(didReplaceFile: {success in
mainQueue({
self.databaseProvider!.didChangeSourceFile(success)
self.loadEventData()
})
}, withKey: nil)
updateManager!.fileBinder.addAction(didReplaceFile: {_ in
//reload event data
delay(seconds: 2.0, {
self.notification(kDidReplaceEventFileNotification, object: nil)
//replace the schedule controller, test again if that's the only way
let tabBarController = self.window!.rootViewController as! UITabBarController
let scheduleVC: AnyObject = tabBarController.storyboard!.instantiateViewControllerWithIdentifier("ScheduleViewController") as AnyObject
var tabVCs = tabBarController.viewControllers!
tabVCs[EventBlankTabIndex.Schedule.rawValue] = scheduleVC
tabBarController.setViewControllers(tabVCs, animated: false)
})
}, withKey: nil)
}
func loadEventData() {
//load event data
event = databaseProvider!.database[EventConfig.tableName].first!
setupUI()
}
func setupUI() {
window?.backgroundColor = UIColor.whiteColor()
let primaryColor = UIColor(hexString: event[Event.mainColor])
let secondaryColor = UIColor(hexString: event[Event.secondaryColor])
MAThemeKit.customizeNavigationBarColor(primaryColor, textColor: UIColor.whiteColor(), buttonColor: UIColor.whiteColor())
MAThemeKit.customizeButtonColor(primaryColor)
MAThemeKit.customizeSwitchOnColor(primaryColor)
MAThemeKit.customizeSearchBarColor(primaryColor, buttonTintColor: UIColor.whiteColor())
MAThemeKit.customizeActivityIndicatorColor(primaryColor)
MAThemeKit.customizeSegmentedControlWithMainColor(UIColor.whiteColor(), secondaryColor: primaryColor)
MAThemeKit.customizeSliderColor(primaryColor)
MAThemeKit.customizePageControlCurrentPageColor(primaryColor)
MAThemeKit.customizeTabBarColor(UIColor.whiteColor().mixWithColor(primaryColor, weight: 0.025), textColor: primaryColor)
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
if let updateManager = updateManager where updateManager.fileBinder.running {
updateManager.stop()
}
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
if let updateManager = updateManager where !updateManager.fileBinder.running {
updateManager.start()
}
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
updateManager?.stop()
}
}
| 79b5da397cfda4837610729809d7fdfd | 43.976378 | 285 | 0.694503 | false | false | false | false |
eriklu/qch | refs/heads/master | Extension/UIImage+qch.swift | mit | 1 | //
// UIImage+qch.swift
//
import UIKit
extension UIImage {
/**
* 返回一个指定高度,一像素款宽的指定颜色的图片
*/
static func qch_imageWithColor( color : UIColor, height : CGFloat) -> UIImage{
let rect = CGRect(x: 0, y: 0, width: 1.0, height: height)
UIGraphicsBeginImageContext(rect.size)
let content = UIGraphicsGetCurrentContext()
content?.setFillColor(color.cgColor)
content?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
/**
* 返回指定宽度的图片。图片宽高比和原图片相同,图片最小高度为1
* width: 目标图片宽度; <=0 返回图片自身
*/
func qch_resizeToWidth( width : CGFloat = 800) -> UIImage? {
return autoreleasepool(invoking: { () -> UIImage? in
if width <= 0 {
return self
}
// if self.size.width <= width {
// return self
// }
let newSize = CGSize(width: width, height: ceil(size.height * width / size.width) )
UIGraphicsBeginImageContext(newSize)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage
})
}
}
| 6e3d3703962e1d64b4988c4c85f47446 | 28.586957 | 95 | 0.570169 | false | false | false | false |
qutheory/vapor | refs/heads/master | Sources/Vapor/Utilities/URI.swift | mit | 1 | import CURLParser
public struct URI: ExpressibleByStringInterpolation, CustomStringConvertible {
/// A URI's scheme.
public struct Scheme: ExpressibleByStringInterpolation {
/// HTTP
public static let http: Self = "http"
/// HTTPS
public static let https: Self = "https"
/// HTTP over Unix Domain Socket Paths. The socket path should be encoded as the host in the URI, making sure to encode any special characters:
/// ```
/// host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
/// ```
/// Do note that URI's initializer will encode the host in this way if you use `init(scheme:host:port:path:query:fragment:)`.
public static let httpUnixDomainSocket: Self = "http+unix"
/// HTTPS over Unix Domain Socket Paths. The socket path should be encoded as the host in the URI, making sure to encode any special characters:
/// ```
/// host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
/// ```
/// Do note that URI's initializer will encode the host in this way if you use `init(scheme:host:port:path:query:fragment:)`.
public static let httpsUnixDomainSocket: Self = "https+unix"
public let value: String?
public init(stringLiteral value: String) {
self.value = value
}
public init(_ value: String? = nil) {
self.value = value
}
}
public var string: String
public init(string: String = "/") {
self.string = string
}
public var description: String {
return self.string
}
public init(
scheme: String?,
host: String? = nil,
port: Int? = nil,
path: String,
query: String? = nil,
fragment: String? = nil
) {
self.init(
scheme: Scheme(scheme),
host: host,
port: port,
path: path,
query: query,
fragment: fragment
)
}
public init(
scheme: Scheme = Scheme(),
host: String? = nil,
port: Int? = nil,
path: String,
query: String? = nil,
fragment: String? = nil
) {
var string = ""
if let scheme = scheme.value {
string += scheme + "://"
}
if let host = host?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
string += host
}
if let port = port {
string += ":" + port.description
}
if path.hasPrefix("/") {
string += path
} else {
string += "/" + path
}
if let query = query {
string += "?" + query
}
if let fragment = fragment {
string += "#" + fragment
}
self.string = string
}
public init(stringLiteral value: String) {
self.init(string: value)
}
private enum Component {
case scheme, host, port, path, query, fragment, userinfo
}
public var scheme: String? {
get {
return self.parse(.scheme)
}
set {
self = .init(
scheme: newValue,
host: self.host,
port: self.port,
path: self.path,
query: self.query,
fragment: self.fragment
)
}
}
public var host: String? {
get {
return self.parse(.host)
}
set {
self = .init(
scheme: self.scheme,
host: newValue,
port: self.port,
path: self.path,
query: self.query,
fragment: self.fragment
)
}
}
public var port: Int? {
get {
return self.parse(.port).flatMap(Int.init)
}
set {
self = .init(
scheme: self.scheme,
host: self.host,
port: newValue,
path: self.path,
query: self.query,
fragment: self.fragment
)
}
}
public var path: String {
get {
return self.parse(.path) ?? ""
}
set {
self = .init(
scheme: self.scheme,
host: self.host,
port: self.port,
path: newValue,
query: self.query,
fragment: self.fragment
)
}
}
public var query: String? {
get {
return self.parse(.query)
}
set {
self = .init(
scheme: self.scheme,
host: self.host,
port: self.port,
path: self.path,
query: newValue,
fragment: self.fragment
)
}
}
public var fragment: String? {
get {
return self.parse(.fragment)
}
set {
self = .init(
scheme: self.scheme,
host: self.host,
port: self.port,
path: self.path,
query: self.query,
fragment: newValue
)
}
}
private func parse(_ component: Component) -> String? {
var url = urlparser_url()
urlparser_parse(self.string, self.string.count, 0, &url)
let data: urlparser_field_data
switch component {
case .scheme:
data = url.field_data.0
case .host:
data = url.field_data.1
case .port:
data = url.field_data.2
case .path:
data = url.field_data.3
case .query:
data = url.field_data.4
case .fragment:
data = url.field_data.5
case .userinfo:
data = url.field_data.6
}
if data.len == 0 {
return nil
}
let start = self.string.index(self.string.startIndex, offsetBy: numericCast(data.off))
let end = self.string.index(start, offsetBy: numericCast(data.len))
return String(self.string[start..<end])
}
}
| c76c6b6c66b206ddc1464bfdd5727feb | 26.666667 | 152 | 0.480818 | false | false | false | false |
kairosinc/Kairos-SDK-iOS-Swift | refs/heads/master | examples/enroll.swift | mit | 1 | /*
* Copyright (c) 2017, Kairos AR, Inc.
* All rights reserved.
*
* Api Docs: https://www.kairos.com/docs/api/
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
import Foundation
import PlaygroundSupport
import UIKit
// Signup for a free Kairos API credentials at: https://developer.kairos.com/signup
struct KairosConfig {
static let app_id = "xxxxxxxxxxxx"
static let app_key = "xxxxxxxxxxxx"
}
// Instantiate KairosAPI class
var Kairos = KairosAPI(app_id: KairosConfig.app_id, app_key: KairosConfig.app_key)
// setup json request params, with image url
var jsonBody = [
"image": "https://media.kairos.com/test1.jpg",
"gallery_name": "kairos-test",
"subject_id": "test1"
]
// Example - Enroll
Kairos.request(method: "enroll", data: jsonBody) { data in
// check image key exist and get data
if let image = ((data as? [String : AnyObject])!["images"])![0] {
// get root image and primary key objects
let attributes = (image as? [String : AnyObject])!["attributes"]
let transaction = (image as? [String : AnyObject])!["transaction"]
// get specific enrolled attributes
var gender = (attributes as? [String : AnyObject])?["gender"]!["type"]!! as! String
let gender_type = (gender == "F") ? "female" : "male"
let age = (attributes as? [String : AnyObject])!["age"]! as! Int
let confidence_percent = 100 * ((transaction as? [String : AnyObject])!["confidence"]! as! Double)
// display results
print("\n--- Enroll")
print("Gender: \(gender_type)")
print("Age: \(age)")
print("Confidence: \(confidence_percent)% \n")
}
else {
print("Error - Enroll: unable to get image data")
}
}
| 76e721f839db86487cb2676c457490c9 | 33.75 | 106 | 0.635663 | false | true | false | false |
Constructor-io/constructorio-client-swift | refs/heads/master | AutocompleteClient/FW/Logic/Request/CIOTrackBrowseResultClickData.swift | mit | 1 | //
// CIOTrackBrowseResultClickData.swift
// Constructor.io
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
/**
Struct encapsulating the parameters that must/can be set set in order to track browse result click
*/
struct CIOTrackBrowseResultClickData: CIORequestData {
let filterName: String
let filterValue: String
let customerID: String
let resultPositionOnPage: Int?
var sectionName: String?
let resultID: String?
let variationID: String?
func url(with baseURL: String) -> String {
return String(format: Constants.TrackBrowseResultClick.format, baseURL)
}
init(filterName: String, filterValue: String, customerID: String, resultPositionOnPage: Int?, sectionName: String? = nil, resultID: String? = nil, variationID: String? = nil) {
self.filterName = filterName
self.filterValue = filterValue
self.customerID = customerID
self.resultPositionOnPage = resultPositionOnPage
self.sectionName = sectionName
self.resultID = resultID
self.variationID = variationID
}
func decorateRequest(requestBuilder: RequestBuilder) {}
func httpMethod() -> String {
return "POST"
}
func httpBody(baseParams: [String: Any]) -> Data? {
var dict = [
"filter_name": self.filterName,
"filter_value": self.filterValue,
"item_id": self.customerID
] as [String: Any]
if self.variationID != nil {
dict["variation_id"] = self.variationID
}
if self.resultPositionOnPage != nil {
dict["result_position_on_page"] = Int(self.resultPositionOnPage!)
}
if self.sectionName != nil {
dict["section"] = self.sectionName
}
if self.resultID != nil {
dict["result_id"] = self.resultID
}
dict["beacon"] = true
dict.merge(baseParams) { current, _ in current }
return try? JSONSerialization.data(withJSONObject: dict)
}
}
| 75f5df1d9604b145dc4e0179e1aaee0c | 29.057971 | 180 | 0.636451 | false | false | false | false |
cikelengfeng/Jude | refs/heads/master | Jude/Antlr4/atn/LexerModeAction.swift | mit | 2 | /// Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
/// Implements the {@code mode} lexer action by calling {@link org.antlr.v4.runtime.Lexer#mode} with
/// the assigned mode.
///
/// - Sam Harwell
/// - 4.2
public final class LexerModeAction: LexerAction, CustomStringConvertible {
fileprivate final var mode: Int
/// Constructs a new {@code mode} action with the specified mode value.
/// - parameter mode: The mode value to pass to {@link org.antlr.v4.runtime.Lexer#mode}.
public init(_ mode: Int) {
self.mode = mode
}
/// Get the lexer mode this action should transition the lexer to.
///
/// - returns: The lexer mode for this {@code mode} command.
public func getMode() -> Int {
return mode
}
/// {@inheritDoc}
/// - returns: This method returns {@link org.antlr.v4.runtime.atn.LexerActionType#MODE}.
public override func getActionType() -> LexerActionType {
return LexerActionType.mode
}
/// {@inheritDoc}
/// - returns: This method returns {@code false}.
public override func isPositionDependent() -> Bool {
return false
}
/// {@inheritDoc}
///
/// <p>This action is implemented by calling {@link org.antlr.v4.runtime.Lexer#mode} with the
/// value provided by {@link #getMode}.</p>
override
public func execute(_ lexer: Lexer) {
lexer.mode(mode)
}
override
public var hashValue: Int {
var hash: Int = MurmurHash.initialize()
hash = MurmurHash.update(hash, getActionType().rawValue)
hash = MurmurHash.update(hash, mode)
return MurmurHash.finish(hash, 2)
}
public var description: String {
return "mode(\(mode))"
}
}
public func ==(lhs: LexerModeAction, rhs: LexerModeAction) -> Bool {
if lhs === rhs {
return true
}
return lhs.mode == rhs.mode
}
| 8097a809f63df776e4947ad10f9c80be | 27.319444 | 100 | 0.632173 | false | false | false | false |
CoderHarry/Melon | refs/heads/master | Melon/Melon.swift | mit | 1 | //
// Melon
// Melon
//
// Created by Caiyanzhi on 2016/10/7.
// Copyright © 2016年 Caiyanzhi. All rights reserved.
//
import UIKit
public class Melon {
fileprivate var melonManager:MelonManager!
public static func build(HTTPMethod method: Melon.HTTPMethod, url: String) -> Melon {
let melon = Melon()
melon.melonManager = MelonManager(url: url, method: method)
return melon
}
public init() {}
public static func GET(_ url:String) -> Melon {
return build(HTTPMethod: .GET, url: url)
}
public static func POST(_ url:String) -> Melon {
return build(HTTPMethod: .POST, url: url)
}
public func addParams(_ params:[String: Any]) -> Melon {
melonManager.addParams(params)
return self
}
public func setTimeoutInterval(_ timeoutInterval:TimeInterval) {
melonManager.setTimeoutInterval(timeoutInterval)
}
public func addHeaders(_ headers: [String:String]) -> Melon {
melonManager.addHeaders(headers)
return self
}
public func setHTTPHeader(_ key: String, _ value: String) -> Melon {
melonManager.setHTTPHeader(key, value)
return self
}
public func cancel(_ callback: (() -> Void)? = nil) {
melonManager.cancelCallback = callback
melonManager.task.cancel()
}
}
// MARK: - call back
extension Melon {
public func responseString(_ callback: ((_ jsonString:String?, _ response:HTTPURLResponse?)->Void)?) -> Melon {
return responseData({ (data, response) in
if let data = data {
let string = String(data: data, encoding: .utf8)
callback?(string, response)
} else {
callback?(nil, response)
}
})
}
public func responseJSON(_ callback: ((_ jsonObject:Any?, _ response:HTTPURLResponse?)->Void)?) -> Melon {
return responseData { (data, response) in
if let data = data {
let object = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
callback?(object, response)
} else {
callback?(nil, response)
}
}
}
public func responseData(_ callback:((_ data:Data?, _ response:HTTPURLResponse?) -> Void)?) -> Melon {
melonManager.fire(callback)
return self
}
public func responseXML() -> Melon {
return self
}
public func onNetworkError(_ errorCallback: ((_ error:NSError)->Void)?) -> Melon {
melonManager.addErrorCallback(errorCallback)
return self
}
}
// MARK: - upload Methods
public extension Melon {
public func uploadProgress(_ uploadProgress:((_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64)->Void)?) -> Melon {
melonManager.addUploadProgressCallback(uploadProgress)
return self
}
public func addFiles(_ formdatas: [Melon.FormData]) -> Melon {
melonManager.addFiles(formdatas)
return self
}
}
// MARK: - download Methods
public extension Melon {
public static func Download(_ url:String) -> Melon {
let melon = Melon()
melon.melonManager = MelonManager(downloadUrl: url)
return melon
}
public func downloadProgress(_ downloadProgress:((_ bytesWritten: Int64, _ totalBytesWritten: Int64, _ totalBytesExpectedToWrite: Int64) -> Void)?) -> Melon {
melonManager.addDownloadProgressCallback(downloadProgress)
return self
}
}
| 108bcfc34acbc766f39b433c440e534d | 27.372093 | 162 | 0.597541 | false | false | false | false |
pinterest/plank | refs/heads/master | Sources/Core/Schema.swift | apache-2.0 | 1 | //
// schema.swift
// Plank
//
// Created by Rahul Malik on 7/23/15.
// Copyright © 2015 Rahul Malik. All rights reserved.
//
import Foundation
typealias JSONObject = [String: Any]
public enum JSONType: String {
case object
case array
case string
case integer
case number
case boolean
case pointer = "$ref" // Used for combining schemas via references.
case polymorphic = "oneOf" // JSONType composed of other JSONTypes
static func typeFromProperty(prop: JSONObject) -> JSONType? {
if (prop["oneOf"] as? [JSONObject]) != nil {
return JSONType.polymorphic
}
if (prop["$ref"] as? String) != nil {
return JSONType.pointer
}
return (prop["type"] as? String).flatMap(JSONType.init)
}
}
public enum StringFormatType: String {
case dateTime = "date-time" // Date representation, as defined by RFC 3339, section 5.6.
case email // Internet email address, see RFC 5322, section 3.4.1.
case hostname // Internet host name, see RFC 1034, section 3.1.
case ipv4 // IPv4 address, according to dotted-quad ABNF syntax as defined in RFC 2673, section 3.2.
case ipv6 // IPv6 address, as defined in RFC 2373, section 2.2.
case uri // A universal resource identifier (URI), according to RFC3986.
}
public struct EnumValue<ValueType> {
let defaultValue: ValueType
let description: String
init(defaultValue: ValueType, description: String) {
self.defaultValue = defaultValue
self.description = description
}
init(withObject object: JSONObject) {
if let defaultVal = object["default"] as? ValueType, let descriptionVal = object["description"] as? String {
defaultValue = defaultVal
description = descriptionVal
} else {
fatalError("Invalid schema specification for enum: \(object)")
}
}
}
public indirect enum EnumType {
case integer([EnumValue<Int>]) // TODO: Revisit if we should have default values for integer enums
case string([EnumValue<String>], defaultValue: EnumValue<String>)
}
public struct URLSchemaReference: LazySchemaReference {
let url: URL
public let force: () -> Schema?
}
public protocol LazySchemaReference {
var force: () -> Schema? { get }
}
extension Dictionary {
init(elements: [(Key, Value)]) {
self.init()
for (key, value) in elements {
updateValue(value, forKey: key)
}
}
}
func decodeRef(from source: URL, with ref: String) -> URL {
if ref.hasPrefix("#") {
// Local URL
return URL(string: ref, relativeTo: source)!
} else {
let baseUrl = source.deletingLastPathComponent()
let lastPathComponentString = URL(string: ref)?.pathComponents.last
return baseUrl.appendingPathComponent(lastPathComponentString!)
}
}
public enum Nullability: String {
case nullable
case nonnull
}
// Ask @bkase about whether this makes more sense to wrap schemas to express nullability
// or if it would be better to have a protocol (i.e. NullabilityProperty) that we would pattern
// match on to detect nullable constraints.
public struct SchemaObjectProperty {
let schema: Schema
let nullability: Nullability? // Nullability does not apply for primitive types
init(schema aSchema: Schema, nullability aNullability: Nullability?) {
schema = aSchema
nullability = aNullability
}
init(schema: Schema) {
self.init(schema: schema, nullability: nil)
}
}
extension Schema {
func nonnullProperty() -> SchemaObjectProperty {
return SchemaObjectProperty(schema: self, nullability: .nonnull)
}
func nullableProperty() -> SchemaObjectProperty {
return SchemaObjectProperty(schema: self, nullability: .nullable)
}
func unknownNullabilityProperty() -> SchemaObjectProperty {
return SchemaObjectProperty(schema: self, nullability: nil)
}
}
public struct SchemaObjectRoot: Hashable {
let name: String
let properties: [String: SchemaObjectProperty]
let extends: URLSchemaReference?
let algebraicTypeIdentifier: String?
var typeIdentifier: String {
return algebraicTypeIdentifier ?? name
}
public func hash(into hasher: inout Hasher) {
hasher.combine(typeIdentifier)
}
}
public func == (lhs: SchemaObjectRoot, rhs: SchemaObjectRoot) -> Bool {
return lhs.name == rhs.name
}
extension SchemaObjectRoot: CustomDebugStringConvertible {
public var debugDescription: String {
return (["\(name)\n extends from \(String(describing: extends.map { $0.force()?.debugDescription }))\n"] + properties.map { key, value in "\t\(key): \(value.schema.debugDescription)\n" }).reduce("", +)
}
}
public indirect enum Schema {
case object(SchemaObjectRoot)
case array(itemType: Schema?)
case set(itemType: Schema?)
case map(valueType: Schema?) // TODO: Should we have an option to specify the key type? (probably yes)
case integer
case float
case boolean
case string(format: StringFormatType?)
case oneOf(types: [Schema]) // ADT
case enumT(EnumType)
case reference(with: URLSchemaReference)
var isPrimitiveType: Bool {
switch self {
case .boolean, .integer, .enumT, .float:
return true
default:
return false
}
}
}
typealias Property = (Parameter, SchemaObjectProperty)
extension Schema: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case let .array(itemType: itemType):
return "Array: \(itemType.debugDescription)"
case let .set(itemType: itemType):
return "Set: \(itemType.debugDescription)"
case let .object(root):
return "Object: \(root.debugDescription)"
case let .map(valueType: valueType):
return "Map: \(valueType as Optional)"
case .integer:
return "Integer"
case .float:
return "Float"
case .boolean:
return "Boolean"
case .string(format: .none),
.string(format: .some(.email)),
.string(format: .some(.hostname)),
.string(format: .some(.ipv4)),
.string(format: .some(.ipv6)):
return "String"
case .string(format: .some(.dateTime)):
return "String: DateTime"
case .string(format: .some(.uri)):
return "String: URI"
case let .oneOf(types: types):
return (["OneOf"] + types.map { value in "\t\(value.debugDescription)\n" }).reduce("", +)
case let .enumT(enumType):
return "Enum: \(enumType)"
case let .reference(with: ref):
return "Reference to \(ref.url)"
}
}
}
extension Schema {
// Computed Properties
var title: String? {
switch self {
case let .object(rootObject):
return rootObject.name
default:
return nil
}
}
func extends() -> Schema? {
switch self {
case let .object(rootObject):
return rootObject.extends.flatMap { $0.force() }
default:
return nil
}
}
func deps() -> Set<URL> {
switch self {
case let .object(rootObject):
let url: URL? = rootObject.extends?.url
return (url.map { Set([$0]) } ?? Set()).union(
Set(
rootObject.properties.values.flatMap { (prop: SchemaObjectProperty) -> Set<URL> in
prop.schema.deps()
}
)
)
case let .array(itemType: itemType), let .set(itemType: itemType):
return itemType?.deps() ?? []
case let .map(valueType: valueType):
return valueType?.deps() ?? []
case .integer, .float, .boolean, .string, .enumT:
return []
case let .oneOf(types: types):
return types.map { type in type.deps() }.reduce([]) { $0.union($1) }
case let .reference(with: ref):
return [ref.url]
}
}
func objectRoots() -> Set<SchemaObjectRoot> {
switch self {
case let .object(rootObject):
return Set([rootObject]).union(rootObject.properties.values.flatMap { $0.schema.objectRoots() })
case let .array(itemType: itemType), let .set(itemType: itemType):
return itemType?.objectRoots() ?? []
case let .map(valueType: valueType):
return valueType?.objectRoots() ?? []
case let .oneOf(types: types):
return types.map { type in type.objectRoots() }.reduce([]) { $0.union($1) }
default:
return []
}
}
}
extension Schema {
static func propertyFunctionForType(loader: SchemaLoader) -> (JSONObject, URL) -> Schema? {
func propertyForType(propertyInfo: JSONObject, source: URL) -> Schema? {
let title = propertyInfo["title"] as? String
// Check for "type"
guard let propType = JSONType.typeFromProperty(prop: propertyInfo) else { return nil }
switch propType {
case JSONType.string:
if let enumValues = propertyInfo["enum"] as? [JSONObject], let defaultValue = propertyInfo["default"] as? String {
let enumVals = enumValues.map { EnumValue<String>(withObject: $0) }
let defaultVal = enumVals.first(where: { $0.defaultValue == defaultValue })
let maybeEnumVals: [EnumValue<String>]? = .some(enumVals)
return maybeEnumVals
.flatMap { (values: [EnumValue<String>]) in defaultVal.map { ($0, values) } }
.map { defaultVal, enumVals in
Schema.enumT(EnumType.string(enumVals, defaultValue: defaultVal))
}
} else {
return Schema.string(format: (propertyInfo["format"] as? String).flatMap(StringFormatType.init))
}
case JSONType.array:
if let unique = propertyInfo["unique"] as? String, unique == "true" {
return .set(itemType: (propertyInfo["items"] as? JSONObject)
.flatMap { propertyForType(propertyInfo: $0, source: source) })
}
return .array(itemType: (propertyInfo["items"] as? JSONObject)
.flatMap { propertyForType(propertyInfo: $0, source: source) })
case JSONType.integer:
if let enumValues = propertyInfo["enum"] as? [JSONObject] {
return Schema.enumT(EnumType.integer(enumValues.map { EnumValue<Int>(withObject: $0) }))
} else {
return .integer
}
case JSONType.number:
return .float
case JSONType.boolean:
return .boolean
case JSONType.pointer:
return (propertyInfo["$ref"] as? String).map { refStr in
let refUrl = decodeRef(from: source, with: refStr)
return .reference(with: URLSchemaReference(url: refUrl, force: { () -> Schema? in
loader.loadSchema(refUrl)
}))
}
case JSONType.object:
let requiredProps = Set(propertyInfo["required"] as? [String] ?? [])
if let propMap = propertyInfo["properties"] as? JSONObject, let objectTitle = title {
// Class
let optTuples: [Property?] = propMap.map { (key, value) -> (String, Schema?) in
let schemaOpt = (value as? JSONObject).flatMap {
propertyForType(propertyInfo: $0, source: source)
}
return (key, schemaOpt)
}.map { name, optSchema in optSchema.map {
(name, SchemaObjectProperty(schema: $0, nullability: $0.isPrimitiveType ? nil : requiredProps.contains(name) ? .nonnull : .nullable))
}
}
let lifted: [Property]? = optTuples.reduce([]) { (build: [Property]?, tupleOption: Property?) -> [Property]? in
build.flatMap { (bld: [Property]) -> [Property]? in tupleOption.map { bld + [$0] } }
}
let extendsDict: JSONObject? = propertyInfo["extends"] as? JSONObject
let extends: URLSchemaReference? = extendsDict
.flatMap { (obj: JSONObject) in
let refStr = obj["$ref"] as? String
return refStr.map { refStr in
let refUrl = decodeRef(from: source, with: refStr)
return URLSchemaReference(url: refUrl, force: {
loader.loadSchema(refUrl)
})
}
}
return lifted.map { Schema.object(SchemaObjectRoot(name: objectTitle,
properties: Dictionary(elements: $0),
extends: extends,
algebraicTypeIdentifier: propertyInfo["algebraicDataTypeIdentifier"] as? String)) }
} else {
// Map type
return Schema.map(valueType: (propertyInfo["additionalProperties"] as? JSONObject)
.flatMap { propertyForType(propertyInfo: $0, source: source) })
}
case JSONType.polymorphic:
return (propertyInfo["oneOf"] as? [JSONObject]) // [JSONObject]
.map { jsonObjs in jsonObjs.map { propertyForType(propertyInfo: $0, source: source) } } // [Schema?]?
.flatMap { schemas in schemas.reduce([]) { (build: [Schema]?, tupleOption: Schema?) -> [Schema]? in
build.flatMap { (bld: [Schema]) -> [Schema]? in tupleOption.map { bld + [$0] } }
} }
.map { Schema.oneOf(types: $0) }
}
}
return propertyForType
}
}
extension Schema {
func isBoolean() -> Bool {
switch self {
case .boolean:
return true
default:
return false
}
}
}
| 011696352206ea10c3a46de8b97a6654 | 37.072727 | 209 | 0.563788 | false | false | false | false |
xwu/swift | refs/heads/master | validation-test/compiler_crashers_2_fixed/rdar70144083.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -emit-ir %s -enable-experimental-concurrency
// REQUIRES: concurrency
@available(SwiftStdlib 5.5, *)
public protocol AsyncIteratorProtocol {
associatedtype Element
associatedtype Failure: Error
mutating func nextResult() async -> Result<Element, Failure>?
mutating func cancel()
}
@available(SwiftStdlib 5.5, *)
public protocol AsyncSequence {
associatedtype Element
associatedtype Failure: Error
associatedtype AsyncIterator: AsyncIteratorProtocol where AsyncIterator.Element == Element, AsyncIterator.Failure == Failure
func makeAsyncIterator() -> AsyncIterator
}
@available(SwiftStdlib 5.5, *)
struct Just<Element>: AsyncSequence {
typealias Failure = Never
struct AsyncIterator: AsyncIteratorProtocol {
var value: Element?
mutating func nextResult() async -> Result<Element, Never>? {
defer { value = nil }
return value.map { .success($0) }
}
mutating func cancel() {
value = nil
}
}
var value: Element
func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(value: value)
}
}
| b50f613bb4bac215032262c953dac2c9 | 26.928571 | 128 | 0.677749 | false | false | false | false |
Knowinnovation/kitime | refs/heads/master | KITime WatchKit Extension/InterfaceController.swift | gpl-2.0 | 1 | //
// InterfaceController.swift
// KITime
//
// Created by Drew Dunne on 7/7/15.
// Copyright (c) 2015 Know Innovation. All rights reserved.
//
import WatchKit
import Foundation
enum TimerState: String {
case Stopped = "stopped"
case Paused = "paused"
case Running = "running"
case Finished = "finished"
case None = "none"
}
class InterfaceController: WKInterfaceController {
@IBOutlet weak var startStopButton: WKInterfaceButton!
@IBOutlet weak var cancelButton: WKInterfaceButton!
var timerIsSelected: Bool = false
var inControl: Bool = false
//Local references to the values online in Firebase
var clockState: TimerState = .None
var timerIsRuning: Bool = false
@IBAction func startStopPressed() {
//Check the state and see how to handle the press
if clockState == .Stopped {
WKInterfaceController.openParentApplication(["action": "running"], reply: nil)
} else if clockState == .Paused {
WKInterfaceController.openParentApplication(["action": "running"], reply: nil)
} else {
WKInterfaceController.openParentApplication(["action": "paused"], reply: nil)
}
}
@IBAction func cancelPressed() {
WKInterfaceController.openParentApplication(["action": "stopped"], reply: nil)
}
func updateButtons() {
if inControl && timerIsSelected {
if clockState != .None {
startStopButton.setEnabled(true)
if clockState == .Running {
startStopButton.setTitle("Pause")
cancelButton.setEnabled(false)
} else if clockState == .Stopped {
startStopButton.setTitle("Start")
cancelButton.setEnabled(false)
} else if clockState == .Paused {
startStopButton.setTitle("Resume")
cancelButton.setEnabled(true)
} else if clockState == .Finished {
startStopButton.setTitle("Start")
startStopButton.setEnabled(false)
cancelButton.setEnabled(true)
} else {
startStopButton.setEnabled(false)
cancelButton.setEnabled(false)
}
} else {
startStopButton.setEnabled(true)
cancelButton.setEnabled(false)
}
} else {
startStopButton.setEnabled(false)
cancelButton.setEnabled(false)
}
}
func requestTimerInfo() {
WKInterfaceController.openParentApplication(["action": "getWatchInfo"], reply: { (replyInfo, error) -> Void in
if let replyInfo = replyInfo, let replyInfoType = replyInfo["replyInfoType"] as? String {
if replyInfoType == "watchInfo" {
var key = replyInfo["timerSelected"] as! Bool
if key == false {
//no timer selected
self.timerIsSelected = false
self.updateButtons()
} else {
self.inControl = replyInfo["inControl"] as! Bool
let clockVal = replyInfo["clockState"] as! String
switch clockVal {
case "stopped":
self.clockState = .Stopped
case "paused":
self.clockState = .Paused
case "running":
self.clockState = .Running
case "finished":
self.clockState = .Finished
default:
self.clockState = .None
}
println("ready")
self.timerIsSelected = true
self.updateButtons()
}
}
} else {
//no timer selected
self.timerIsSelected = false
self.updateButtons()
}
NSLog("Reply: \(replyInfo)")
})
}
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
startStopButton.setEnabled(false)
cancelButton.setEnabled(false)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("requestTimerInfo"), name: "com.knowinnovation.kitime-watchkit.secondRequestData", object: nil)
let darwinNotificationCenter = WatchDarwinNotifier.sharedInstance()
darwinNotificationCenter.registerForNotificationName("com.knowinnovation.kitime-watchkit.requestData")
self.requestTimerInfo()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| d09bba357b46d68b9f036a391933fcbb | 34.141026 | 177 | 0.516235 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripePayments/StripePayments/API Bindings/Models/STPConnectAccountAddress.swift | mit | 1 | //
// STPConnectAccountAddress.swift
// StripePayments
//
// Created by Yuki Tokuhiro on 8/2/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
import Foundation
/// An address to use with `STPConnectAccountParams`.
public class STPConnectAccountAddress: NSObject {
/// City, district, suburb, town, or village.
/// For addresses in Japan: City or ward.
@objc public var city: String?
/// Two-letter country code (ISO 3166-1 alpha-2).
/// - seealso: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
@objc public var country: String?
/// Address line 1 (e.g., street, PO Box, or company name).
/// For addresses in Japan: Block or building number.
@objc public var line1: String?
/// Address line 2 (e.g., apartment, suite, unit, or building).
/// For addresses in Japan: Building details.
@objc public var line2: String?
/// ZIP or postal code.
@objc public var postalCode: String?
/// State, county, province, or region.
/// For addresses in Japan: Prefecture.
@objc public var state: String?
/// Town or cho-me.
/// This property only applies to Japanese addresses.
@objc public var town: String?
/// :nodoc:
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
/// :nodoc:
@objc public override var description: String {
let props = [
// Object
String(format: "%@: %p", NSStringFromClass(STPConnectAccountAddress.self), self),
// Properties
"line1 = \(String(describing: line1))",
"line2 = \(String(describing: line2))",
"town = \(String(describing: town))",
"city = \(String(describing: city))",
"state = \(String(describing: state))",
"postalCode = \(String(describing: postalCode))",
"country = \(String(describing: country))",
]
return "<\(props.joined(separator: "; "))>"
}
}
// MARK: - STPFormEncodable
extension STPConnectAccountAddress: STPFormEncodable {
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:line1)): "line1",
NSStringFromSelector(#selector(getter:line2)): "line2",
NSStringFromSelector(#selector(getter:town)): "town",
NSStringFromSelector(#selector(getter:city)): "city",
NSStringFromSelector(#selector(getter:country)): "country",
NSStringFromSelector(#selector(getter:state)): "state",
NSStringFromSelector(#selector(getter:postalCode)): "postal_code",
]
}
@objc
public class func rootObjectName() -> String? {
return nil
}
}
| 36ce36e68ab6af290b8526b31bab0309 | 32.597561 | 93 | 0.619964 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-duplicates/04121-swift-parser-skipsingle.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let v: a<b: String {
struct B<T where S.c : A<T where f: a : a {
struct A<T where B : String {
func a
if true {
var b { func a
protocol c : A {
class d<T : a() -> Bool {
() {
() {
class C<T : A<T where f: String {
struct B<T) {
[Void{
if true {
if true {
protocol A {
private let v: A {
struct A {
[Void{
class A {
class A {
[Void{
func a(""""""
class A : String {
struct B<T where f: A<T where B : (""""""""
private let b { func a
class A {
func a<T : a = {
typealias e = {
class C<h : Int -> V {
protocol A {
func b: String {
class C<T where S.c : b { func g: Int = 1)
func g: A<T where B : () -> V {
private let v: (f: T where B : A {
protocol c {
struct A {
struct B<A? {
struct A? {
class A : Int -> V {
if true {
private let b = [Void{
struct A, A {
class C<T where f: A : Int -> Bool {
struct A {
let v: A.c : (f: String {
private let v: (f: A<T where f: A? = [Void{
func b: T, A {
struct B<h : Int = Swift.e = c() -> Bool {
struct A? {
if true {
func g: () -> Bool {
struct A<h : Int = [Void{
var b { func a
| 6a3bdf64bc804e91d58e4245d77876ec | 19.431034 | 87 | 0.591561 | false | false | false | false |
vrisch/Starburst | refs/heads/master | Sources/Starburst/Internals.swift | mit | 1 | import Foundation
final class Box {
init<T>(value: T) {
self.value = value
}
func wrap<T>(value: T) {
self.value = value
}
func unwrap<T>() -> T? {
return value as? T
}
private var value: Any
}
final class ReducerBox {
init<S: State, A: Action>(reducer: @escaping Reducer<S, A>) {
box = Box(value: reducer)
perform = { box, state, action, observe in
guard let reducer: Reducer<S, A> = box.unwrap() else { return [] }
guard var state = state as? S else { return [] }
guard let action = action as? A else { return [] }
var effects: [Action] = []
switch try reducer(&state, action) {
case .unmodified:
break
case let .modified(newState):
try observe(newState)
case let .effect(newState, action):
try observe(newState)
effects.append(action)
case let .effects(newState, actions):
try observe(newState)
effects += actions
}
return effects
}
}
func apply(state: State, action: Action, observe: (State) throws -> Void) throws -> [Action] {
return try perform(box, state, action, observe)
}
private let box: Box
private let perform: (Box, State, Action, (State) throws -> Void) throws -> [Action]
}
final class StateBox {
init<S: State>(state: S) {
box = Box(value: state)
perform = { box, action, reducers, observers, middlewares in
guard let state: S = box.unwrap() else { return [] }
var effects: [Action] = []
for reducer in reducers {
effects += try reducer.apply(state: state, action: action) { newState in
guard var newState = newState as? S else { return }
// State has changed
box.wrap(value: newState)
// Notify observers
try observers.forEach {
try $0.apply(state: newState, reason: .modified)
}
// Notify middlewares
var changes = false
try middlewares.forEach {
if let state = try $0.apply(state: newState) {
// State has changed again
box.wrap(value: state)
newState = state
changes = true
}
}
if changes {
// Notify observers
try observers.forEach { try $0.apply(state: newState, reason: .middleware) }
}
}
}
return effects
}
}
func apply(action: Action, reducers: [ReducerBox], observers: [ObserverBox], middlewares: [MiddlewareBox]) throws -> [Action] {
return try perform(box, action, reducers, observers, middlewares)
}
func apply<S: State>(observer: Observer<S>) throws {
guard let state: S = box.unwrap() else { return }
try observer(state, .subscribed)
}
private var box: Box
private var perform: (Box, Action, [ReducerBox], [ObserverBox], [MiddlewareBox]) throws -> [Action]
}
/*
final class MiddlewareBox {
init(middleware: Middleware) {
box = Box(value: middleware)
}
func apply(action: Action) throws {
guard let middleware: Middleware = box.unwrap() else { return }
if case let .action(f) = middleware {
try f(action)
}
}
func apply(state: State) throws -> State? {
guard let middleware: Middleware = box.unwrap() else { return nil }
if case let .state(f) = middleware {
return try f(state)
}
return nil
}
private var box: Box
}
*/
final class MiddlewareBox {
init(_ f: @escaping (Action) throws -> [Action]) {
perform = { action, _ in
guard let action = action else { return (nil, nil) }
return (nil, try f(action))
}
}
init<S: State>(_ f: @escaping (inout S) throws -> Reduction<S>) {
perform = { action, state in
guard var newState = state as? S else { return (nil, nil) }
switch try f(&newState) {
case .unmodified: return (nil, nil)
case let .effect(newState, _): return (newState, nil)
case let .modified(newState): return (newState, nil)
case let .effects(newState, _): return (newState, nil)
}
}
}
func apply(action: Action) throws -> [Action] {
guard let actions = try perform(action, nil).1 else { return [] }
return actions
}
func apply<S: State>(state: S) throws -> S? {
guard let state = try perform(nil, state).0 as? S else { return nil }
return state
}
private var perform: (Action?, State?) throws -> (State?, [Action]?)
}
final class ObserverBox {
let priority: Priority
init<S: State>(priority: Priority, observer: @escaping Observer<S>) {
self.priority = priority
box = Box(value: observer)
}
func apply<S: State>(state: S, reason: Reason) throws {
guard let observer: Observer<S> = box.unwrap() else { return }
try observer(state, reason)
}
func apply<S: State>(state: S) throws {
guard let observer: Observer<S> = box.unwrap() else { return }
try observer(state, .subscribed)
}
private var box: Box
}
| 7a779d6f909a54b7660288df63d5b027 | 31.47486 | 131 | 0.511612 | false | false | false | false |
inacioferrarini/York | refs/heads/master | Classes/Extensions/UIImageExtensions.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import Foundation
public extension UIImage {
public class func circularScaleAndCropImage(_ image: UIImage, frame: CGRect) -> UIImage {
let size = CGSize(width: frame.size.width, height: frame.size.height)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
let imageWidth = image.size.width
let imageHeight = image.size.height
let rectWidth = frame.size.width
let rectHeight = frame.size.height
let scaleFactorX = rectWidth / imageWidth
let scaleFactorY = rectHeight / imageHeight
let imageCenterX = rectWidth / 2
let imageCenterY = rectHeight / 2
let radius = rectWidth / 2
if let context = context {
context.beginPath()
let center = CGPoint(x: imageCenterX, y: imageCenterY)
context.addArc(center: center, radius: radius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: false)
context.closePath()
context.clip()
context.scaleBy (x: scaleFactorX, y: scaleFactorY)
let myRect = CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight)
image.draw(in: myRect)
}
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return croppedImage!
}
public class func imageFromColor(_ color: UIColor, withSize size: CGSize, withCornerRadius cornerRadius: CGFloat) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIGraphicsBeginImageContext(size)
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
image?.draw(in: rect)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
public class func maskedImageNamed(_ image: UIImage, color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, image.scale)
let context = UIGraphicsGetCurrentContext()
image.draw(in: rect)
context?.setFillColor(color.cgColor)
context?.setBlendMode(.sourceAtop)
context?.fill(rect)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
}
| 0ade4cbd34a164d3e0e8ea7b6dca94b3 | 36.59434 | 130 | 0.679046 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | refs/heads/develop | Aztec/Classes/Renderers/CommentAttachmentRenderer.swift | gpl-2.0 | 2 | import Foundation
import UIKit
// MARK: - CommentAttachmentRenderer: Renders HTML Comments!
//
final public class CommentAttachmentRenderer {
/// Comment Attachment Text
///
let defaultText = NSLocalizedString("[COMMENT]", comment: "Comment Attachment Label")
/// Text Color
///
var textColor = UIColor.gray
/// Text Font
///
var textFont: UIFont
/// Default Initializer
///
public init(font: UIFont) {
self.textFont = font
}
}
// MARK: - TextViewCommentsDelegate Methods
//
extension CommentAttachmentRenderer: TextViewAttachmentImageProvider {
public func textView(_ textView: TextView, shouldRender attachment: NSTextAttachment) -> Bool {
return attachment is CommentAttachment
}
public func textView(_ textView: TextView, imageFor attachment: NSTextAttachment, with size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
// Either this is a comment attachment, or the logic is broken.
let commentAttachment = attachment as! CommentAttachment
guard !isGutenbergComment(commentAttachment) else {
return nil
}
let message = messageAttributedString()
let targetRect = boundingRect(for: message, size: size)
message.draw(in: targetRect)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
public func textView(_ textView: TextView, boundsFor attachment: NSTextAttachment, with lineFragment: CGRect) -> CGRect {
let message = messageAttributedString()
// Either this is a comment attachment, or the logic is broken.
let commentAttachment = attachment as! CommentAttachment
guard !isGutenbergComment(commentAttachment) else {
return .zero
}
let size = CGSize(width: lineFragment.size.width, height: lineFragment.size.height)
var rect = boundingRect(for: message, size: size)
rect.origin.y = textFont.descender
return rect.integral
}
}
// MARK: - Private Methods
//
private extension CommentAttachmentRenderer {
func boundingRect(for message: NSAttributedString, size: CGSize) -> CGRect {
let targetBounds = message.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
let targetPosition = CGPoint(x: ((size.width - targetBounds.width) * 0.5), y: ((size.height - targetBounds.height) * 0.5))
return CGRect(origin: targetPosition, size: targetBounds.size)
}
func messageAttributedString() -> NSAttributedString {
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: textColor,
.font: textFont
]
return NSAttributedString(string: defaultText, attributes: attributes)
}
func isGutenbergComment(_ comment: CommentAttachment) -> Bool {
let openingGutenbergTag = "wp:"
let closingGutenbergTag = "/wp:"
let text = comment.text.trimmingCharacters(in: .whitespacesAndNewlines)
return verify(text, startsWith: openingGutenbergTag) || verify(text, startsWith: closingGutenbergTag)
}
func verify(_ text: String, startsWith string: String) -> Bool {
guard let endIndex = text.index(text.startIndex, offsetBy: string.count, limitedBy: text.endIndex) else {
return false
}
let testRange = text.startIndex ..< endIndex
let testString = String(text[testRange])
return testString == string
}
}
| 87adeb289d71a0b75ede8db11ec80307 | 29.285714 | 130 | 0.674251 | false | false | false | false |
qichen0401/QCUtilitySwift | refs/heads/master | QCUtilitySwift/Classes/Common/CGRect+QC.swift | mit | 1 | //
// File.swift
// Pods
//
// Created by Qi Chen on 6/17/17.
//
//
import Foundation
extension CGRect {
public var center: CGPoint {
set {
self.origin = CGPoint(x: center.x - self.size.width/2, y: center.y - self.size.height/2)
}
get {
return CGPoint(x: self.origin.x + self.size.width/2, y: self.origin.y + self.size.height/2)
}
}
public init(center: CGPoint, size: CGSize) {
let origin = CGPoint(x: center.x - size.width / 2, y: center.y - size.height / 2)
self.init(origin: origin, size: size)
}
public func ellipseContains(_ point: CGPoint) -> Bool {
let x = point.x
let y = point.y
let h = self.center.x
let k = self.center.y
let a = self.width/2
let b = self.height/2
let result = (x - h)*(x - h)/(a*a) + (y-k)*(y-k)/(b*b)
return result <= 1
}
}
| c630a9d97561b76659c6da61ac31a866 | 24.216216 | 103 | 0.525188 | false | false | false | false |
devpunk/velvet_room | refs/heads/master | Source/Controller/Abstract/AppDelegate.swift | mit | 1 | import UIKit
@UIApplicationMain
final class AppDelegate:UIResponder, UIApplicationDelegate
{
var window:UIWindow?
func application(
_ application:UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey:Any]?) -> Bool
{
let window:UIWindow = UIWindow(frame:UIScreen.main.bounds)
window.backgroundColor = UIColor.white
window.makeKeyAndVisible()
self.window = window
let parent:ControllerParent = ControllerParent()
window.rootViewController = parent
return true
}
}
| 6cc7ffa754c7be88e35dbab996d8c6df | 25.956522 | 66 | 0.670968 | false | false | false | false |
cocoaheadsru/server | refs/heads/develop | Sources/App/Models/Client/Client.swift | mit | 1 | import Vapor
import FluentProvider
import HTTP
// sourcery: AutoModelGeneratable
// sourcery: fromJSON, toJSON, Preparation, Updateable, ResponseRepresentable, Timestampable
final class Client: Model {
let storage = Storage()
var userId: Identifier?
var pushToken: String
init(pushToken: String, userId: Identifier?) {
self.pushToken = pushToken
self.userId = userId
}
// sourcery:inline:auto:Client.AutoModelGeneratable
init(row: Row) throws {
userId = try? row.get(Keys.userId)
pushToken = try row.get(Keys.pushToken)
}
func makeRow() throws -> Row {
var row = Row()
try? row.set(Keys.userId, userId)
try row.set(Keys.pushToken, pushToken)
return row
}
// sourcery:end
}
extension Client {
convenience init(request: Request) throws {
self.init(
pushToken: try request.json!.get(Keys.pushToken),
userId: try request.user().id
)
}
static func returnIfExists(request: Request) throws -> Client? {
return try Client.makeQuery()
.filter(Keys.userId, try request.user().id)
.first()
}
}
| 2aa38b0716708d96d828d2a2d1e8ca13 | 21.791667 | 92 | 0.680987 | false | false | false | false |
10686142/eChance | refs/heads/master | eChance/RegisterVC.swift | mit | 1 | //
// RegisterVC.swift
// Iraffle
//
// Created by Vasco Meerman on 03/05/2017.
// Copyright © 2017 Vasco Meerman. All rights reserved.
//
import Alamofire
import UIKit
class RegisterVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
// Outlets
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var genderTextField: UITextField!
@IBOutlet weak var dateOfBirthTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
// Models
let user = UsersModel()
let date = TimerCall()
let datePicker = UIDatePicker()
// Constants and Variables
let defaults = UserDefaults.standard
let URL_USER_REGISTER = "https://echance.nl/SwiftToSQL_API/v1/register.php"
var dateSend: String!
var pickOption = ["", "Man", "Vrouw", "Onzijdig"]
override func viewDidLoad() {
super.viewDidLoad()
let pickerView = UIPickerView()
pickerView.delegate = self
genderTextField.inputView = pickerView
createGenderPicker()
createDatePicker()
}
func createGenderPicker() {
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneGenderPickerPressed))
toolbar.setItems([doneButton], animated: false)
genderTextField.inputAccessoryView = toolbar
}
func createDatePicker() {
// Format datepicker to D M Y
datePicker.locale = NSLocale.init(localeIdentifier: "en_GB") as Locale
//Format for picker to date with years
datePicker.datePickerMode = .date
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePickerPressed))
toolbar.setItems([doneButton], animated: false)
dateOfBirthTextField.inputAccessoryView = toolbar
dateOfBirthTextField.inputView = datePicker
}
func doneGenderPickerPressed() {
self.view.endEditing(true)
}
func donePickerPressed() {
// format picker output to date with years
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "dd-MM-yyyy"
dateOfBirthTextField.text = dateFormatter.string(from: datePicker.date)
let dateCheck = datePicker.date
let eligebleAge = date.checkAgeUnder18(date: dateCheck)
if eligebleAge == true {
let dateFormatterSend = DateFormatter()
dateFormatterSend.dateStyle = .short
dateFormatterSend.timeStyle = .none
dateFormatterSend.dateFormat = "yyyy-MM-dd"
dateSend = dateFormatterSend.string(from: datePicker.date)
self.view.endEditing(true)
}
else{
self.registerErrorAlert(title: "Oeps!", message: "Je moet 18 jaar of ouder zijn om je in te schrijven..")
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickOption.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickOption[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
genderTextField.text = pickOption[row]
}
@IBAction func submitPressed(_ sender: Any) {
let userFName = firstNameTextField.text
let userLName = lastNameTextField.text
let userBDate = dateSend
let userGender = genderTextField.text
let userPassword = passwordTextField.text
let confirmPassword = confirmPasswordTextField.text
let userEmail = emailTextField.text
if userFName != "" && userLName != "" && userBDate != "" && userGender != "" && userPassword != "" && confirmPassword != "" && userEmail != ""{
let parameters: Parameters=[
"first_name":userFName!,
"last_name":userLName!,
"password":userPassword!,
"birth_date":userBDate!,
"email":userEmail!,
"gender":userGender!
]
Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
{
response in
//printing response
print(response)
if let result = response.result.value {
let jsonData = result as! NSDictionary
let message = jsonData.value(forKey: "message") as! String?
if message == "User already exist"{
self.registerErrorAlert(title: "Oeps!", message: "Deze email is al een keer geregistreerd")
self.emailTextField.text = ""
}
else{
// Save the userID from the registered user
let uid = jsonData.value(forKey: "uid") as! Int?
let userDict = ["userID": uid!, "userFN": userFName!, "userLN": userLName!, "userBD": userBDate!, "userE": userEmail!, "userP": userPassword!, "userG": userGender!] as [String : Any]
self.defaults.set(userDict, forKey: "user")
self.defaults.set("1", forKey: "fromRegister")
self.performSegue(withIdentifier: "toExplanation", sender: nil)
}
}
}
}
else{
self.registerErrorAlert(title: "Oeps!", message: "Zorg dat alle velden ingevuld zijn;)")
}
}
func registerErrorAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
| e6a7fb16b37f019b10c1120f6f1a4056 | 36.048913 | 210 | 0.580167 | false | false | false | false |
chenyun122/StepIndicator | refs/heads/master | StepIndicatorDemo/ViewController.swift | mit | 1 | //
// ViewController.swift
// StepIndicator
//
// Created by Yun Chen on 2017/7/14.
// Copyright © 2017 Yun CHEN. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
@IBOutlet weak var stepIndicatorView:StepIndicatorView!
@IBOutlet weak var scrollView:UIScrollView!
private var isScrollViewInitialized = false
override func viewDidLoad() {
super.viewDidLoad()
// In this demo, the customizations have been done in Storyboard.
// Customization by coding:
//self.stepIndicatorView.numberOfSteps = 5
//self.stepIndicatorView.currentStep = 0
//self.stepIndicatorView.circleColor = UIColor(red: 179.0/255.0, green: 189.0/255.0, blue: 194.0/255.0, alpha: 1.0)
//self.stepIndicatorView.circleTintColor = UIColor(red: 0.0/255.0, green: 180.0/255.0, blue: 124.0/255.0, alpha: 1.0)
//self.stepIndicatorView.circleStrokeWidth = 3.0
//self.stepIndicatorView.circleRadius = 10.0
//self.stepIndicatorView.lineColor = self.stepIndicatorView.circleColor
//self.stepIndicatorView.lineTintColor = self.stepIndicatorView.circleTintColor
//self.stepIndicatorView.lineMargin = 4.0
//self.stepIndicatorView.lineStrokeWidth = 2.0
//self.stepIndicatorView.displayNumbers = false //indicates if it displays numbers at the center instead of the core circle
//self.stepIndicatorView.direction = .leftToRight
//self.stepIndicatorView.showFlag = true
// Example for apply constraints programmatically, enable it for test.
//self.applyNewConstraints()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !isScrollViewInitialized {
isScrollViewInitialized = true
self.initScrollView()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func initScrollView() {
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.width * CGFloat(self.stepIndicatorView.numberOfSteps + 1), height: self.scrollView.frame.height)
let labelHeight = self.scrollView.frame.height / 2.0
let halfScrollViewWidth = self.scrollView.frame.width / 2.0
for i in 1 ... self.stepIndicatorView.numberOfSteps + 1 {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 100))
if i<=self.stepIndicatorView.numberOfSteps {
label.text = "\(i)"
}
else{
label.text = "You're done!"
}
label.textAlignment = NSTextAlignment.center
label.font = UIFont.systemFont(ofSize: 35)
label.textColor = UIColor.lightGray
label.center = CGPoint(x: halfScrollViewWidth * (CGFloat(i - 1) * 2.0 + 1.0), y:labelHeight)
self.scrollView.addSubview(label)
}
}
// MARK: - UIScrollViewDelegate
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageIndex = scrollView.contentOffset.x / scrollView.frame.size.width
stepIndicatorView.currentStep = Int(pageIndex)
}
// MARK: - More Examples
// Example for applying constraints programmatically
func applyNewConstraints() {
// Hold the weak object
guard let stepIndicatorView = self.stepIndicatorView else {
return
}
// Remove the constraints made in Storyboard before
stepIndicatorView.removeFromSuperview()
stepIndicatorView.removeConstraints(stepIndicatorView.constraints)
self.view.addSubview(stepIndicatorView)
// Add new constraints programmatically
stepIndicatorView.widthAnchor.constraint(equalToConstant: 263.0).isActive = true
stepIndicatorView.heightAnchor.constraint(equalToConstant: 80.0).isActive = true
stepIndicatorView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stepIndicatorView.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor, constant:30.0).isActive = true
self.scrollView.topAnchor.constraint(equalTo: stepIndicatorView.bottomAnchor, constant: 8.0).isActive = true
}
}
| 74e292f3b3aba65f8a0e7d2431c496d5 | 39.880734 | 170 | 0.665395 | false | false | false | false |
Zewo/SQL | refs/heads/master | Sources/SQL/Model/TableProtocol.swift | mit | 2 | public protocol TableField: RawRepresentable, Hashable, ParameterConvertible {
static var tableName: String { get }
}
public extension TableField {
public var sqlParameter: Parameter {
return .field(qualifiedField)
}
public var qualifiedField: QualifiedField {
return QualifiedField("\(Self.tableName).\(self.rawValue)")
}
}
public protocol TableProtocol {
associatedtype Field: TableField
}
public extension TableProtocol where Self.Field.RawValue == String {
public static func select(_ fields: Field...) -> Select {
return Select(fields.map { $0.qualifiedField }, from: [Field.tableName])
}
public static func select(where predicate: Predicate) -> Select {
return select.filtered(predicate)
}
public static var select: Select {
return Select("*", from: Field.tableName)
}
public static func update(_ dict: [Field: ValueConvertible?], where predicate: Predicate? = nil) -> Update {
var translated = [QualifiedField: ValueConvertible?]()
for (key, value) in dict {
translated[key.qualifiedField] = value
}
var update = Update(Field.tableName)
update.set(translated)
if let predicate = predicate {
update.filter(predicate)
}
return update
}
public static func insert(_ dict: [Field: ValueConvertible?]) -> Insert {
var translated = [QualifiedField: ValueConvertible?]()
for (key, value) in dict {
translated[key.qualifiedField] = value
}
return Insert(Field.tableName, values: translated)
}
public static func delete(where predicate: Predicate) -> Delete {
return Delete(from: Field.tableName).filtered(predicate)
}
public static var delete: Delete {
return Delete(from: Field.tableName)
}
}
| 0d52daf3b271214ac7b33989ac8d9431 | 26.617647 | 112 | 0.647497 | false | false | false | false |
lhx931119/DouYuTest | refs/heads/master | DouYu/DouYu/Classes/Home/View/RecommendGameView.swift | mit | 1 |
//
// RecommendGameView.swift
// DouYu
//
// Created by 李宏鑫 on 17/1/19.
// Copyright © 2017年 hongxinli. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
private let kEdgeInsetMargin: CGFloat = -15
class RecommendGameView: UIView {
//控件属性
@IBOutlet weak var collectionView: UICollectionView!
//定义属性
var group: [AnchorGroup]?{
didSet{
//移除前两个
group?.removeFirst()
group?.removeFirst()
//添加更多
let moreGroup = AnchorGroup()
group?.append(moreGroup)
//刷新collectionView
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
//设置不随父空间拉伸而拉伸
autoresizingMask = .None
// 注册cell
collectionView.registerNib(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
//设置collectionView内边距
collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin)
}
}
// Mark:-快速创建的类方法
extension RecommendGameView{
class func recommendGameView() -> RecommendGameView{
return NSBundle.mainBundle().loadNibNamed("RecommendGameView", owner: nil, options: nil).first as! RecommendGameView
}
}
// Mark:-遵守collectionViewDataSource
extension RecommendGameView: UICollectionViewDataSource{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return group?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kGameCellID, forIndexPath: indexPath) as! CollectionGameCell
cell.group = group?[indexPath.item]
return cell
}
}
| 7854afcdd7cf00da9c738c6633c870f5 | 24.025316 | 133 | 0.657056 | false | false | false | false |
chquanquan/AreaPickerView_swift | refs/heads/master | AreaPickerViewDemo/AreaPickerViewDemo/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// test
//
// Created by quan on 2017/1/11.
// Copyright © 2017年 langxi.Co.Ltd. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
var areaPickerView: AreaPickerView?
override func viewDidLoad() {
super.viewDidLoad()
//初始化地址(如果有),方便弹出pickerView后能够主动选中,这时候还没有区域代码信息,但是只要一划动并确定就有了.理论上进入地址控制器时候,要么全部信息有,要么全部信息没有....我先赋值只是为了演示功能.
myLocate.province = "广东省"
myLocate.city = "广州市"
myLocate.area = "天河区"
setAreaText(locate: myLocate)
//areaPickerView.有控制器在的时候,不会被销毁.跟控制器时间销毁...没关系吧?
areaPickerView = AreaPickerView.picker(for: self, textField: textField)
textField.delegate = self //也个也最好实现.因为可以在将要显示PickerView的时候,主动选中一个地区.
//为了点击空白的时候能够退键盘
let tapGR = UITapGestureRecognizer(target: self, action: #selector(viewDidTap(tapGR:)))
tapGR.cancelsTouchesInView = false
view.addGestureRecognizer(tapGR)
}
func viewDidTap(tapGR: UITapGestureRecognizer) {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - lazy
lazy var myLocate: Location = {
return Location()
}()
}
extension ViewController: UITextFieldDelegate {
//主动选择某一个地区,主动弹出某个区域以选中....
func textFieldDidBeginEditing(_ textField: UITextField) {
areaPickerView?.shouldSelected(proName: myLocate.province, cityName: myLocate.city, areaName: myLocate.area)
}
}
extension ViewController: AreaPickerDelegate {
internal func cancel(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) {
print("点击了取消")
//还原原来的值......
myLocate.decription()
setAreaText(locate: myLocate)
}
internal func sure(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) {
print("点击了确定")
//当picker定住的时候,就有会值.**********但是******************
//picker还有转动的时候有些值是空的........取值前一定要判断是否为空.否则crash.....
//赋值新地址......
print("最后的值是\n")
locate.decription()
// myLocate = locate //不能直接赋值地址,这个是引用来的
myLocate.province = locate.province
myLocate.provinceCode = locate.provinceCode
myLocate.city = locate.city
myLocate.cityCode = locate.cityCode
myLocate.area = locate.area
myLocate.areaCode = locate.areaCode
}
internal func statusChanged(areaPickerView: AreaPickerView, pickerView: UIPickerView, textField: UITextField, locate: Location) {
//立即显示新值
print("转到的值:\n")
locate.decription()
if !locate.area.isEmpty {
textField.text = "\(locate.province) \(locate.city) \(locate.area)"
} else {
textField.text = "\(locate.province) \(locate.city)"
}
}
func setAreaText(locate: Location) {
var areaText = ""
if locate.city.isEmpty {
areaText = locate.province
} else if locate.area.isEmpty {
areaText = "\(locate.province) \(locate.city)"
} else {
areaText = "\(locate.province) \(locate.city) \(locate.area)"
}
textField.text = areaText
}
}
| b15216a25643450687ba39bbe9dd3398 | 28.86087 | 133 | 0.624345 | false | false | false | false |
proversity-org/edx-app-ios | refs/heads/master | Source/DiscussionNewPostViewController.swift | apache-2.0 | 1 | //
// DiscussionNewPostViewController.swift
// edX
//
// Created by Tang, Jeff on 6/1/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
struct DiscussionNewThread {
let courseID: String
let topicID: String
let type: DiscussionThreadType
let title: String
let rawBody: String
}
protocol DiscussionNewPostViewControllerDelegate : class {
func newPostController(controller : DiscussionNewPostViewController, addedPost post: DiscussionThread)
}
public class DiscussionNewPostViewController: UIViewController, UITextViewDelegate, MenuOptionsViewControllerDelegate, InterfaceOrientationOverriding {
public typealias Environment = DataManagerProvider & NetworkManagerProvider & OEXRouterProvider & OEXAnalyticsProvider
private let minBodyTextHeight : CGFloat = 66 // height for 3 lines of text
private let environment: Environment
private let growingTextController = GrowingTextViewController()
private let insetsController = ContentInsetsController()
@IBOutlet private var scrollView: UIScrollView!
@IBOutlet private var backgroundView: UIView!
@IBOutlet private var contentTextView: OEXPlaceholderTextView!
@IBOutlet private var titleTextField: UITextField!
@IBOutlet private var discussionQuestionSegmentedControl: UISegmentedControl!
@IBOutlet private var bodyTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private var topicButton: UIButton!
@IBOutlet private var postButton: SpinnerButton!
@IBOutlet weak var contentTitleLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
private let loadController = LoadStateViewController()
private let courseID: String
fileprivate let topics = BackedStream<[DiscussionTopic]>()
private var selectedTopic: DiscussionTopic?
private var optionsViewController: MenuOptionsViewController?
weak var delegate: DiscussionNewPostViewControllerDelegate?
private let tapButton = UIButton()
var titleTextStyle: OEXTextStyle {
return OEXTextStyle(weight : .normal, size: .small, color: OEXStyles.shared().neutralDark())
}
private var selectedThreadType: DiscussionThreadType = .Discussion {
didSet {
switch selectedThreadType {
case .Discussion:
self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [titleTextStyle.attributedString(withText: Strings.Dashboard.courseDiscussion), titleTextStyle.attributedString(withText: Strings.asteric)])
postButton.applyButtonStyle(style: OEXStyles.shared().filledPrimaryButtonStyle,withTitle: Strings.postDiscussion)
contentTextView.accessibilityLabel = Strings.Dashboard.courseDiscussion
case .Question:
self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [titleTextStyle.attributedString(withText: Strings.question), titleTextStyle.attributedString(withText: Strings.asteric)])
postButton.applyButtonStyle(style: OEXStyles.shared().filledPrimaryButtonStyle, withTitle: Strings.postQuestion)
contentTextView.accessibilityLabel = Strings.question
}
}
}
public init(environment: Environment, courseID: String, selectedTopic : DiscussionTopic?) {
self.environment = environment
self.courseID = courseID
super.init(nibName: "DiscussionNewPostViewController", bundle: nil)
let stream = environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID: courseID).topics
topics.backWithStream(stream.map {
return DiscussionTopic.linearizeTopics(topics: $0)
}
)
self.selectedTopic = selectedTopic
}
private var firstSelectableTopic : DiscussionTopic? {
let selectablePredicate = { (topic : DiscussionTopic) -> Bool in
topic.isSelectable
}
guard let topics = self.topics.value, let selectableTopicIndex = topics.firstIndexMatching(selectablePredicate) else {
return nil
}
return topics[selectableTopicIndex]
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBAction func postTapped(sender: AnyObject) {
postButton.isEnabled = false
postButton.showProgress = true
// create new thread (post)
if let topic = selectedTopic, let topicID = topic.id {
let newThread = DiscussionNewThread(courseID: courseID, topicID: topicID, type: selectedThreadType , title: titleTextField.text ?? "", rawBody: contentTextView.text)
let apiRequest = DiscussionAPI.createNewThread(newThread: newThread)
environment.networkManager.taskForRequest(apiRequest) {[weak self] result in
self?.postButton.isEnabled = true
self?.postButton.showProgress = false
if let post = result.data {
self?.delegate?.newPostController(controller: self!, addedPost: post)
self?.dismiss(animated: true, completion: nil)
}
else {
DiscussionHelper.showErrorMessage(controller: self, error: result.error)
}
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = Strings.post
let cancelItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)
cancelItem.oex_setAction { [weak self]() -> Void in
self?.dismiss(animated: true, completion: nil)
}
self.navigationItem.leftBarButtonItem = cancelItem
contentTitleLabel.isAccessibilityElement = false
titleLabel.isAccessibilityElement = false
titleLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [titleTextStyle.attributedString(withText: Strings.title), titleTextStyle.attributedString(withText: Strings.asteric)])
contentTextView.textContainer.lineFragmentPadding = 0
contentTextView.applyStandardBorderStyle()
contentTextView.delegate = self
titleTextField.accessibilityLabel = Strings.title
self.view.backgroundColor = OEXStyles.shared().neutralXXLight()
configureSegmentControl()
titleTextField.defaultTextAttributes = OEXStyles.shared().textAreaBodyStyle.attributes.attributedKeyDictionary()
setTopicsButtonTitle()
let insets = OEXStyles.shared().standardTextViewInsets
topicButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: insets.left, bottom: 0, right: insets.right)
topicButton.accessibilityHint = Strings.accessibilityShowsDropdownHint
topicButton.applyBorderStyle(style: OEXStyles.shared().entryFieldBorderStyle)
topicButton.localizedHorizontalContentAlignment = .Leading
let dropdownLabel = UILabel()
dropdownLabel.attributedText = Icon.Dropdown.attributedTextWithStyle(style: titleTextStyle)
topicButton.addSubview(dropdownLabel)
dropdownLabel.snp.makeConstraints { make in
make.trailing.equalTo(topicButton).offset(-insets.right)
make.top.equalTo(topicButton).offset(topicButton.frame.size.height / 2.0 - 5.0)
}
topicButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in
self?.showTopicPicker()
}, for: UIControl.Event.touchUpInside)
postButton.isEnabled = false
titleTextField.oex_addAction({[weak self] _ in
self?.validatePostButton()
}, for: .editingChanged)
self.growingTextController.setupWithScrollView(scrollView: scrollView, textView: contentTextView, bottomView: postButton)
self.insetsController.setupInController(owner: self, scrollView: scrollView)
// Force setting it to call didSet which is only called out of initialization context
self.selectedThreadType = .Question
loadController.setupInController(controller: self, contentView: self.scrollView)
topics.listen(self, success : {[weak self]_ in
self?.loadedData()
}, failure : {[weak self] error in
self?.loadController.state = LoadState.failed(error: error)
})
backgroundView.addSubview(tapButton)
backgroundView.sendSubviewToBack(tapButton)
tapButton.backgroundColor = UIColor.clear
tapButton.frame = CGRect(x: 0, y: 0, width: backgroundView.frame.size.width, height: backgroundView.frame.size.height)
tapButton.isAccessibilityElement = false
tapButton.accessibilityLabel = Strings.accessibilityHideKeyboard
tapButton.oex_addAction({[weak self] (sender) in
self?.view.endEditing(true)
}, for: .touchUpInside)
}
private func configureSegmentControl() {
discussionQuestionSegmentedControl.removeAllSegments()
let questionIcon = Icon.Question.attributedTextWithStyle(style: titleTextStyle)
let questionTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [questionIcon,
titleTextStyle.attributedString(withText: Strings.question)])
let discussionIcon = Icon.Comments.attributedTextWithStyle(style: titleTextStyle)
let discussionTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [discussionIcon,
titleTextStyle.attributedString(withText: Strings.discussion)])
let segmentOptions : [(title : NSAttributedString, value : DiscussionThreadType)] = [
(title : questionTitle, value : .Question),
(title : discussionTitle, value : .Discussion),
]
for i in 0..<segmentOptions.count {
discussionQuestionSegmentedControl.insertSegmentWithAttributedTitle(title: segmentOptions[i].title, index: i, animated: false)
discussionQuestionSegmentedControl.subviews[i].accessibilityLabel = segmentOptions[i].title.string
}
discussionQuestionSegmentedControl.oex_addAction({ [weak self] (control:AnyObject) -> Void in
if let segmentedControl = control as? UISegmentedControl {
let index = segmentedControl.selectedSegmentIndex
let threadType = segmentOptions[index].value
self?.selectedThreadType = threadType
self?.updateSelectedTabColor()
}
else {
assert(true, "Invalid Segment ID, Remove this segment index OR handle it in the ThreadType enum")
}
}, for: UIControl.Event.valueChanged)
discussionQuestionSegmentedControl.tintColor = OEXStyles.shared().neutralDark()
discussionQuestionSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: OEXStyles.shared().neutralWhite()], for: UIControl.State.selected)
discussionQuestionSegmentedControl.selectedSegmentIndex = 0
updateSelectedTabColor()
}
private func updateSelectedTabColor() {
// //UIsegmentControl don't Multiple tint color so updating tint color of subviews to match desired behaviour
let subViews:NSArray = discussionQuestionSegmentedControl.subviews as NSArray
for i in 0..<subViews.count {
if (subViews.object(at: i) as AnyObject).isSelected ?? false {
let view = subViews.object(at: i) as! UIView
view.tintColor = OEXStyles.shared().primaryBaseColor()
}
else {
let view = subViews.object(at: i) as! UIView
view.tintColor = OEXStyles.shared().neutralDark()
}
}
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.environment.analytics.trackDiscussionScreen(withName: AnalyticsScreenName.CreateTopicThread, courseId: self.courseID, value: selectedTopic?.name, threadId: nil, topicId: selectedTopic?.id, responseID: nil)
}
override public var shouldAutorotate: Bool {
return true
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
private func loadedData() {
loadController.state = topics.value?.count == 0 ? LoadState.empty(icon: .NoTopics, message : Strings.unableToLoadCourseContent) : .Loaded
if selectedTopic == nil {
selectedTopic = firstSelectableTopic
}
setTopicsButtonTitle()
}
private func setTopicsButtonTitle() {
if let topic = selectedTopic, let name = topic.name {
let title = Strings.topic(topic: name)
topicButton.setAttributedTitle(OEXTextStyle(weight : .normal, size: .small, color: OEXStyles.shared().neutralDark()).attributedString(withText: title), for: .normal)
}
}
func showTopicPicker() {
if self.optionsViewController != nil {
return
}
view.endEditing(true)
self.optionsViewController = MenuOptionsViewController()
self.optionsViewController?.delegate = self
guard let courseTopics = topics.value else {
//Don't need to configure an empty state here because it's handled in viewDidLoad()
return
}
self.optionsViewController?.options = courseTopics.map {
return MenuOptionsViewController.MenuOption(depth : $0.depth, label : $0.name ?? "")
}
self.optionsViewController?.selectedOptionIndex = self.selectedTopicIndex()
self.view.addSubview(self.optionsViewController!.view)
self.optionsViewController!.view.snp.makeConstraints { make in
make.trailing.equalTo(self.topicButton)
make.leading.equalTo(self.topicButton)
make.top.equalTo(self.topicButton.snp.bottom).offset(-3)
make.bottom.equalTo(safeBottom)
}
self.optionsViewController?.view.alpha = 0.0
UIView.animate(withDuration: 0.3) {
self.optionsViewController?.view.alpha = 1.0
}
}
private func selectedTopicIndex() -> Int? {
guard let selected = selectedTopic else {
return 0
}
return self.topics.value?.firstIndexMatching {
return $0.id == selected.id
}
}
public func textViewDidChange(_ textView: UITextView) {
validatePostButton()
growingTextController.handleTextChange()
}
public func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index : Int) -> Bool {
return self.topics.value?[index].isSelectable ?? false
}
private func validatePostButton() {
self.postButton.isEnabled = !(titleTextField.text ?? "").isEmpty && !contentTextView.text.isEmpty && self.selectedTopic != nil
}
func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int) {
selectedTopic = self.topics.value?[index]
if let topic = selectedTopic, topic.id != nil {
setTopicsButtonTitle()
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: titleTextField);
UIView.animate(withDuration: 0.3, animations: {
self.optionsViewController?.view.alpha = 0.0
}, completion: {[weak self](finished: Bool) in
self?.optionsViewController?.view.removeFromSuperview()
self?.optionsViewController = nil
})
}
}
public override func viewDidLayoutSubviews() {
self.insetsController.updateInsets()
growingTextController.scrollToVisible()
}
private func textFieldDidBeginEditing(textField: UITextField) {
tapButton.isAccessibilityElement = true
}
private func textFieldDidEndEditing(textField: UITextField) {
tapButton.isAccessibilityElement = false
}
public func textViewDidBeginEditing(_ textView: UITextView) {
tapButton.isAccessibilityElement = true
}
public func textViewDidEndEditing(_ textView: UITextView) {
tapButton.isAccessibilityElement = false
}
}
extension UISegmentedControl {
//UIsegmentControl didn't support attributedTitle by default
func insertSegmentWithAttributedTitle(title: NSAttributedString, index: NSInteger, animated: Bool) {
let segmentLabel = UILabel()
segmentLabel.backgroundColor = UIColor.clear
segmentLabel.textAlignment = .center
segmentLabel.attributedText = title
segmentLabel.sizeToFit()
self.insertSegment(with: segmentLabel.toImage(), at: 1, animated: false)
}
}
extension UILabel {
func toImage()-> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image;
}
}
// For use in testing only
extension DiscussionNewPostViewController {
public func t_topicsLoaded() -> OEXStream<[DiscussionTopic]> {
return topics
}
}
| a516df64b9c06b1f9190d779ff7028a1 | 42.883375 | 254 | 0.676562 | false | false | false | false |
NordicSemiconductor/IOS-Pods-DFU-Library | refs/heads/master | Example/Pods/ZIPFoundation/Sources/ZIPFoundation/Data+Serialization.swift | bsd-3-clause | 1 | //
// Data+Serialization.swift
// ZIPFoundation
//
// Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors.
// Released under the MIT License.
//
// See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information.
//
import Foundation
protocol DataSerializable {
static var size: Int { get }
init?(data: Data, additionalDataProvider: (Int) throws -> Data)
var data: Data { get }
}
extension Data {
enum DataError: Error {
case unreadableFile
case unwritableFile
}
func scanValue<T>(start: Int) -> T {
let subdata = self.subdata(in: start..<start+MemoryLayout<T>.size)
#if swift(>=5.0)
return subdata.withUnsafeBytes { $0.load(as: T.self) }
#else
return subdata.withUnsafeBytes { $0.pointee }
#endif
}
static func readStruct<T>(from file: UnsafeMutablePointer<FILE>, at offset: Int) -> T? where T: DataSerializable {
fseek(file, offset, SEEK_SET)
guard let data = try? self.readChunk(of: T.size, from: file) else {
return nil
}
let structure = T(data: data, additionalDataProvider: { (additionalDataSize) -> Data in
return try self.readChunk(of: additionalDataSize, from: file)
})
return structure
}
static func consumePart(of size: Int, chunkSize: Int, skipCRC32: Bool = false,
provider: Provider, consumer: Consumer) throws -> CRC32 {
let readInOneChunk = (size < chunkSize)
var chunkSize = readInOneChunk ? size : chunkSize
var checksum = CRC32(0)
var bytesRead = 0
while bytesRead < size {
let remainingSize = size - bytesRead
chunkSize = remainingSize < chunkSize ? remainingSize : chunkSize
let data = try provider(bytesRead, chunkSize)
try consumer(data)
if !skipCRC32 {
checksum = data.crc32(checksum: checksum)
}
bytesRead += chunkSize
}
return checksum
}
static func readChunk(of size: Int, from file: UnsafeMutablePointer<FILE>) throws -> Data {
let alignment = MemoryLayout<UInt>.alignment
#if swift(>=4.1)
let bytes = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: alignment)
#else
let bytes = UnsafeMutableRawPointer.allocate(bytes: size, alignedTo: alignment)
#endif
let bytesRead = fread(bytes, 1, size, file)
let error = ferror(file)
if error > 0 {
throw DataError.unreadableFile
}
#if swift(>=4.1)
return Data(bytesNoCopy: bytes, count: bytesRead, deallocator: .custom({ buf, _ in buf.deallocate() }))
#else
let deallocator = Deallocator.custom({ buf, _ in buf.deallocate(bytes: size, alignedTo: 1) })
return Data(bytesNoCopy: bytes, count: bytesRead, deallocator: deallocator)
#endif
}
static func write(chunk: Data, to file: UnsafeMutablePointer<FILE>) throws -> Int {
var sizeWritten = 0
chunk.withUnsafeBytes { (rawBufferPointer) in
if let baseAddress = rawBufferPointer.baseAddress, rawBufferPointer.count > 0 {
let pointer = baseAddress.assumingMemoryBound(to: UInt8.self)
sizeWritten = fwrite(pointer, 1, chunk.count, file)
}
}
let error = ferror(file)
if error > 0 {
throw DataError.unwritableFile
}
return sizeWritten
}
}
| 03bed5267c95e76604a6ba9469ed5b12 | 35.693878 | 118 | 0.615128 | false | false | false | false |
balafd/SAC_iOS | refs/heads/master | SAC/Pods/SwiftForms/SwiftForms/cells/FormLabelCell.swift | mit | 1 | //
// FormTextFieldCell.swift
// SwiftForms
//
// Created by Miguel Ángel Ortuño Ortuño on 20/08/14.
// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
class FormLabelCell: FormValueCell {
/// MARK: FormBaseCell
override func configure() {
super.configure()
accessoryType = .none
titleLabel.translatesAutoresizingMaskIntoConstraints = false
valueLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
valueLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
valueLabel.textColor = UIColor.lightGray
valueLabel.textAlignment = .right
contentView.addSubview(titleLabel)
contentView.addSubview(valueLabel)
titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
// apply constant constraints
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0))
}
override func update() {
super.update()
titleLabel.text = rowDescriptor?.title
valueLabel.text = rowDescriptor?.configuration.cell.placeholder
}
}
| 42b810e2f29933c1229b07cb85486ac8 | 42.270833 | 185 | 0.702937 | false | true | false | false |
janukobytsch/cardiola | refs/heads/master | Carthage/Checkouts/Swinject/Swinject/Assembler.swift | mit | 2 | //
// Assembler.swift
// Swinject
//
// Created by mike.owens on 12/9/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
/// The `Assembler` provides a means to build a container via `AssemblyType` instances.
public class Assembler {
/// the container that each assembly will build its `Service` definitions into
private let container: Container
/// expose the container as a resolver so `Service` registration only happens within an assembly
public var resolver: ResolverType {
return container
}
/// Will create an empty `Assembler`
///
/// - parameter container: the baseline container
///
public init(container: Container? = Container()) {
self.container = container!
}
/// Will create a new `Assembler` with the given `AssemblyType` instances to build a `Container`
///
/// - parameter assemblies: the list of assemblies to build the container from
/// - parameter propertyLoaders: a list of property loaders to apply to the container
/// - parameter container: the baseline container
///
public init(assemblies: [AssemblyType], propertyLoaders: [PropertyLoaderType]? = nil, container: Container? = Container()) throws {
self.container = container!
if let propertyLoaders = propertyLoaders {
for propertyLoader in propertyLoaders {
try self.container.applyPropertyLoader(propertyLoader)
}
}
runAssemblies(assemblies)
}
/// Will apply the assembly to the container. This is useful if you want to lazy load an assembly into the assembler's
/// container.
///
/// If this assembly type is load aware, the loaded hook will be invoked right after the container has assembled
/// since after each call to `addAssembly` the container is fully loaded in its current state. If you wish to
/// lazy load several assemblies that have interdependencies between each other use `appyAssemblies`
///
/// - parameter assembly: the assembly to apply to the container
///
public func applyAssembly(assembly: AssemblyType) {
runAssemblies([assembly])
}
/// Will apply the assemblies to the container. This is useful if you want to lazy load several assemblies into the assembler's
/// container
///
/// If this assembly type is load aware, the loaded hook will be invoked right after the container has assembled
/// since after each call to `addAssembly` the container is fully loaded in its current state.
///
/// - parameter assemblies: the assemblies to apply to the container
///
public func applyAssemblies(assemblies: [AssemblyType]) {
runAssemblies(assemblies)
}
/// Will apply a property loader to the container. This is useful if you want to lazy load your assemblies or build
/// your assembler manually
///
/// - parameter propertyLoader: the property loader to apply to the assembler's container
///
/// - throws: PropertyLoaderError
///
public func applyPropertyLoader(propertyLoader: PropertyLoaderType) throws {
try self.container.applyPropertyLoader(propertyLoader)
}
// MARK: Private
private func runAssemblies(assemblies: [AssemblyType]) {
// build the container from each assembly
for assembly in assemblies {
assembly.assemble(self.container)
}
// inform all of the assemblies that the container is loaded
for assembly in assemblies {
assembly.loaded(self.resolver)
}
}
}
| f1e5e627a9b850a55cd16b891e719ffa | 38.042553 | 135 | 0.66703 | false | false | false | false |
svdo/swift-SelfSignedCert | refs/heads/master | SelfSignedCert/CertificateName.swift | mit | 1 | // Copyright © 2016 Stefan van den Oord. All rights reserved.
import Foundation
class CertificateName : NSObject {
private(set) var components: [ Set<NSMutableArray> ]
var commonName: String {
get { return string(for: OID.commonName) }
set { setString(newValue, forOid:OID.commonName) }
}
var emailAddress: String {
get { return string(for: OID.email) }
set { setString(newValue, forOid:OID.email) }
}
override init() {
components = []
super.init()
}
func string(for oid:OID) -> String {
guard let pair = pair(for: oid), let str = pair[1] as? String else {
return ""
}
return str
}
func setString(_ string:String, forOid oid:OID) {
if let pair = pair(for: oid) {
pair[1] = string
}
else {
components.append([[oid, string]])
}
}
private func pair(for oid:OID) -> NSMutableArray? {
let filtered = components.filter { set in
guard let array = set.first, let filteredOid = array[0] as? OID else {
return false
}
return filteredOid == oid
}
if filtered.count == 1 {
return filtered[0].first
}
else {
return nil
}
}
}
| 46e206caa816bdcab3174bc5b0b90e8f | 25.076923 | 82 | 0.525074 | false | false | false | false |
Tricertops/YAML | refs/heads/master | Sources/Utilities.swift | mit | 1 | //
// Utilities.swift
// YAML.framework
//
// Created by Martin Kiss on 14 May 2016.
// https://github.com/Tricertops/YAML
//
// The MIT License (MIT)
// Copyright © 2016 Martin Kiss
//
extension String {
/// Creates String from mutable libyaml char array.
init(_ string: UnsafeMutablePointer<yaml_char_t>?) {
guard let string = string else {
self.init()
return
}
let casted = UnsafePointer<CChar>(OpaquePointer(string))
self.init(cString: casted)
}
/// Convenience function for obtaining indexes.
func index(_ offset: Int) -> String.Index {
return self.index(self.startIndex, offsetBy: offset)
}
/// Convenience function for obtaining indexes from the end.
func index(backwards offset: Int) -> String.Index {
return self.index(self.endIndex, offsetBy: -offset)
}
/// Substring from a native String.Index.
func substring(from offset: Int) -> String {
return String(self[self.index(offset) ..< self.endIndex])
}
/// Substring to a native String.Index.
func substring(to offset: Int) -> String {
return String(self[self.startIndex ..< self.index(backwards: offset)])
}
/// Invoke block on the contents of this string, represented as a nul-terminated array of char, ensuring the array's lifetime until return.
func withMutableCString<Result>(_ block: @escaping (UnsafeMutablePointer<UInt8>) throws -> Result) rethrows -> Result {
var array = self.utf8CString
return try array.withUnsafeMutableBufferPointer { buffer in
let casted = UnsafeMutablePointer<UInt8>(OpaquePointer(buffer.baseAddress!))
return try block(casted)
}
}
}
extension Array {
/// Creates array from libyaml array of arbitrary type.
init(start: UnsafeMutablePointer<Element>?, end: UnsafeMutablePointer<Element>?) {
self.init()
guard let start = start else { return }
guard let end = end else { return }
var current = start
while current < end {
self.append(current.pointee)
current += 1
}
}
}
extension Int32 {
init(_ bool: Bool) {
self.init(bool ? 1 : 0)
}
}
| 1392f4b8cbf7a0aafca63119421ad242 | 26.411765 | 143 | 0.611588 | false | false | false | false |
johnno1962/Dynamo | refs/heads/master | Sources/Servers.swift | mit | 1 | //
// Servers.swift
// Dynamo
//
// Created by John Holdsworth on 11/06/2015.
// Copyright (c) 2015 John Holdsworth. All rights reserved.
//
// $Id: //depot/Dynamo/Sources/Servers.swift#24 $
//
// Repo: https://github.com/johnno1962/Dynamo
//
import Foundation
#if os(Linux)
import Dispatch
import Glibc
#endif
// MARK: Private queues and missing IP functions
let dynamoRequestQueue = DispatchQueue( label: "DynamoRequestThread", attributes: DispatchQueue.Attributes.concurrent )
// MARK: Basic http: Web server
/**
Basic http protocol web server running on the specified port. Requests are presented to each of a set
of swiftlets provided in a connecton thread until one is encountered that has processed the request.
*/
open class DynamoWebServer: _NSObject_ {
fileprivate let swiftlets: [DynamoSwiftlet]
fileprivate let serverSocket: Int32
/** port allocated for server if specified as 0 */
open var serverPort: UInt16 = 0
/** basic initialiser for Swift web server processing using array of swiftlets */
@objc public convenience init?( portNumber: UInt16, swiftlets: [DynamoSwiftlet], localhostOnly: Bool = false ) {
self.init( portNumber, swiftlets: swiftlets, localhostOnly: localhostOnly )
DispatchQueue.global(qos: .default).async(execute: {
self.runConnectionHandler( self.httpConnectionHandler )
} )
}
@objc init?( _ portNumber: UInt16, swiftlets: [DynamoSwiftlet], localhostOnly: Bool ) {
#if os(Linux)
signal( SIGPIPE, SIG_IGN )
#endif
self.swiftlets = swiftlets
var ip4addr = sockaddr_in()
#if !os(Linux)
ip4addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
#endif
ip4addr.sin_family = sa_family_t(AF_INET)
ip4addr.sin_port = htons( portNumber )
ip4addr.sin_addr = in_addr( s_addr: INADDR_ANY )
if localhostOnly {
inet_aton( "127.0.0.1", &ip4addr.sin_addr )
}
serverSocket = socket( Int32(ip4addr.sin_family), sockType, 0 )
var yes: u_int = 1, yeslen = socklen_t(MemoryLayout<u_int>.size)
var addrLen = socklen_t(MemoryLayout<sockaddr_in>.size)
super.init()
if serverSocket < 0 {
dynamoStrerror( "Could not get server socket" )
}
else if setsockopt( serverSocket, SOL_SOCKET, SO_REUSEADDR, &yes, yeslen ) < 0 {
dynamoStrerror( "Could not set SO_REUSEADDR" )
}
else if bind( serverSocket, sockaddr_cast(&ip4addr), addrLen ) < 0 {
dynamoStrerror( "Could not bind service socket on port \(portNumber)" )
}
else if listen( serverSocket, 100 ) < 0 {
dynamoStrerror( "Server socket would not listen" )
}
else if getsockname( serverSocket, sockaddr_cast(&ip4addr), &addrLen ) == 0 {
serverPort = ntohs( ip4addr.sin_port )
#if os(Linux)
let s = ""
#else
let s = type(of: self) === DynamoSSLWebServer.self ? "s" : ""
#endif
dynamoLog( "Server available on http\(s)://localhost:\(serverPort)" )
return
}
return nil
}
func runConnectionHandler( _ connectionHandler: @escaping (Int32) -> Void ) {
while self.serverSocket >= 0 {
let clientSocket = accept( self.serverSocket, nil, nil )
if clientSocket >= 0 {
dynamoRequestQueue.async(execute: {
connectionHandler( clientSocket )
} )
}
else {
Thread.sleep( forTimeInterval: 0.5 )
}
}
}
func wrapConnection( _ clientSocket: Int32 ) -> DynamoHTTPConnection? {
return DynamoHTTPConnection( clientSocket: clientSocket )
}
open func httpConnectionHandler( _ clientSocket: Int32 ) {
if let httpClient = wrapConnection( clientSocket ) {
while httpClient.readHeaders() {
var processed = false
for swiftlet in swiftlets {
switch swiftlet.present( httpClient: httpClient ) {
case .notProcessed:
continue
case .processed:
return
case .processedAndReusable:
httpClient.flush()
processed = true
}
break
}
if !processed {
httpClient.status = 400
httpClient.response( text: "Invalid request: \(httpClient.method) \(httpClient.path) \(httpClient.version)" )
return
}
}
}
}
}
#if os(Linux)
/**
Pre-forked worker model version e.g. https://github.com/kylef/Curassow
*/
public class DynamoWorkerServer : DynamoWebServer {
public init?( portNumber: UInt16, swiftlets: [DynamoSwiftlet], workers: Int, localhostOnly: Bool = false ) {
super.init( portNumber, swiftlets: swiftlets, localhostOnly: localhostOnly )
DispatchQueue.global(qos: .default).async {
var wcount = 0, status: Int32 = 0
while true {
if (wcount < workers || wait( &status ) != 0) && fork() == 0 {
self.runConnectionHandler( self.httpConnectionHandler )
}
wcount += 1
}
}
}
}
#else
// MARK: SSL https: Web Server
/**
Subclass of DynamoWebServer for accepting https: SSL encoded requests. Create a proxy on the provided
port to a surrogate DynamoWebServer on a random port on the localhost to actually process the requests.
*/
open class DynamoSSLWebServer: DynamoWebServer {
fileprivate let certs: [AnyObject]
/**
default initialiser for SSL server. Can proxy a "surrogate" non-SSL server given it's URL
*/
@objc public init?( portNumber: UInt16, swiftlets: [DynamoSwiftlet] = [], certs: [AnyObject], surrogate: String? = nil ) {
self.certs = certs
super.init( portNumber, swiftlets: swiftlets, localhostOnly: false )
DispatchQueue.global(qos: .default).async(execute: {
if surrogate == nil {
self.runConnectionHandler( self.httpConnectionHandler )
}
else if let surrogateURL = URL( string: surrogate! ) {
self.runConnectionHandler( {
(clientSocket: Int32) in
if let sslConnection = self.wrapConnection( clientSocket ),
let surrogateConnection = DynamoHTTPConnection( url: surrogateURL ) {
DynamoSelector.relay( "surrogate", from: sslConnection, to: surrogateConnection, dynamoTrace )
}
} )
}
else {
dynamoLog( "Invalid surrogate URL: \(String(describing: surrogate))" )
}
} )
}
override func wrapConnection( _ clientSocket: Int32 ) -> DynamoHTTPConnection? {
return DynamoSSLConnection( sslSocket: clientSocket, certs: certs )
}
}
class DynamoSSLConnection: DynamoHTTPConnection {
let inputStream: InputStream
let outputStream: OutputStream
init?( sslSocket: Int32, certs: [AnyObject]? ) {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocket( nil, sslSocket, &readStream, &writeStream )
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
inputStream.open()
outputStream.open()
super.init(clientSocket: sslSocket,
readFP: funopen(readStream!.toOpaque(), {
(cookie, buffer, count) in
let inputStream = Unmanaged<InputStream>
.fromOpaque(cookie!).takeUnretainedValue()
// Swift.print("READ", count)
return Int32(inputStream.read( buffer!.withMemoryRebound(to: UInt8.self, capacity: Int(count)) {$0}, maxLength: Int(count) ))
}, nil, nil, {cookie -> Int32 in
Unmanaged<InputStream>.fromOpaque(cookie!)
.takeUnretainedValue().close()
return 0
}),
writeFP: funopen(writeStream!.toOpaque(), nil, {
(cookie, buffer, count) in
let outputStream = Unmanaged<OutputStream>
.fromOpaque(cookie!).takeUnretainedValue()
// Swift.print("WRITE", count)
return Int32(outputStream.write( buffer!.withMemoryRebound(to: UInt8.self, capacity: Int(count)) {$0}, maxLength: Int(count) ))
}, nil, {cookie -> Int32 in
Unmanaged<OutputStream>.fromOpaque(cookie!)
.takeUnretainedValue().close()
return 0
}))
if certs != nil {
let sslSettings: [NSString:AnyObject] = [
kCFStreamSSLIsServer: NSNumber(value: true as Bool),
kCFStreamSSLLevel: kCFStreamSSLLevel,
kCFStreamSSLCertificates: certs! as AnyObject
]
CFReadStreamSetProperty( inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLSettings), sslSettings as CFTypeRef )
CFWriteStreamSetProperty( outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLSettings), sslSettings as CFTypeRef )
}
}
override var hasBytesAvailable: Bool {
return inputStream.hasBytesAvailable
}
override func _read( buffer: UnsafeMutableRawPointer, count: Int ) -> Int {
return inputStream.read( buffer.assumingMemoryBound(to: UInt8.self), maxLength: count )
}
override func _write( buffer: UnsafeRawPointer, count: Int ) -> Int {
return outputStream.write( buffer.assumingMemoryBound(to: UInt8.self), maxLength: count )
}
override func receive( buffer: UnsafeMutableRawPointer, count: Int ) -> Int? {
return inputStream.hasBytesAvailable ? _read( buffer: buffer, count: count ) : nil
}
override func forward( buffer: UnsafeRawPointer, count: Int ) -> Int? {
return outputStream.hasSpaceAvailable ? _write( buffer: buffer, count: count ) : nil
}
}
#endif
| ccb7e52536cbe0b48a76d4226f9a97bc | 33.386667 | 139 | 0.599651 | false | false | false | false |
natemann/PlaidClient | refs/heads/master | PlaidClient/PlaidURL.swift | mit | 1 | //
// PlaidURL.swift
// PlaidClient
//
// Created by Nathan Mann on 8/14/16.
// Copyright © 2016 Nathan Mann. All rights reserved.
//
import Foundation
internal struct PlaidURL {
init(environment: Environment) {
switch environment {
case .development:
baseURL = "https://tartan.plaid.com"
case .production:
baseURL = "https://api.plaid.com"
}
}
let baseURL: String
func institutions(id: String? = nil) -> URLRequest {
var url = baseURL + "/institutions"
if let id = id {
url += "/\(id)"
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
return request
}
func intuit(clientID: String, secret: String, count: Int, skip: Int) -> URLRequest {
let bodyObject = ["client_id" : clientID,
"secret" : secret,
"count" : "\(count)",
"offset" : "\(skip)"]
return URLRequest("POST", url: URL(string: baseURL + "/institutions/longtail")!, body: bodyObject)
}
func connect(clientID: String, secret: String, institution: PlaidInstitution, username: String, password: String, pin: String? = nil) -> URLRequest {
let bodyObject = ["client_id" : clientID,
"secret" : secret,
"type" : institution.type,
"username" : username,
"password" : password,
"pin" : pin ?? "0"]
return URLRequest("POST", url: URL(string: baseURL + "/connect")!, body: bodyObject)
}
func step(clientID: String, secret: String, institution: PlaidInstitution, username: String, password: String, pin: String? = nil) -> URLRequest {
var request = connect(clientID: clientID, secret: secret, institution: institution, username: username, password: password)
request.url = request.url?.appendingPathComponent("/step")
return request
}
func mfaResponse(clientID: String, secret: String, institution: PlaidInstitution, accessToken: String, response: String) -> URLRequest {
let bodyObject = ["client_id" : "test_id",
"secret" : "test_secret",
"mfa" : response,
"type" : institution.type,
"access_token" : accessToken]
return URLRequest("POST", url: URL(string: baseURL + "/connect/step")!, body: bodyObject)
}
func patchConnect(clientID: String, secret: String, accessToken: String, username: String, password: String, pin: String? = nil) -> URLRequest {
let bodyObject = ["client_id" : clientID,
"secret" : secret,
"access_token" : accessToken,
"username" : username,
"password" : password,
"pin" : pin ?? "0"]
return URLRequest("PATCH", url: URL(string: baseURL + "/connect")!, body: bodyObject)
}
func patchMFAResponse(clientID: String, secret: String, accessToken: String, response: String) -> URLRequest {
let bodyObject = ["client_id" : "test_id",
"secret" : "test_secret",
"mfa" : response,
"access_token" : accessToken]
return URLRequest("PATCH", url: URL(string: baseURL + "/connect/step")!, body: bodyObject)
}
func transactions(clientID: String, secret: String, accessToken: String, accountID: String?, pending: Bool?, fromDate: Date?, toDate: Date?) -> URLRequest {
var options: [String : Any] = [:]
if let accountID = accountID {
options["account"] = accountID
}
if let pending = pending {
options["pending"] = pending
}
if let fromDate = fromDate {
options["gte"] = DateFormatter.plaidDate(fromDate)
}
if let toDate = toDate {
options["lte"] = DateFormatter.plaidDate(toDate)
}
let bodyObject: [String: Any] = ["client_id" : clientID,
"secret" : secret,
"access_token" : accessToken,
"options" : options]
return URLRequest("POST", url: URL(string: baseURL + "/connect/get")!, body: bodyObject)
}
}
fileprivate extension URLRequest {
init(_ method: String, url: URL, body: [String : Any]) {
self.init(url: url)
self.httpMethod = method
self.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
self.httpBody = try! JSONSerialization.data(withJSONObject: body, options: [])
}
}
| 54a47a7bf832a19c35c2cbdb72e10546 | 32.782313 | 160 | 0.529199 | false | false | false | false |
alblue/swift | refs/heads/master | test/SILGen/dynamic_lookup.swift | apache-2.0 | 2 | // RUN: %target-swift-emit-silgen -module-name dynamic_lookup -enable-objc-interop -parse-as-library -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -module-name dynamic_lookup -enable-objc-interop -parse-as-library -disable-objc-attr-requires-foundation-module %s | %FileCheck %s --check-prefix=GUARANTEED
class X {
@objc func f() { }
@objc class func staticF() { }
@objc var value: Int {
return 17
}
@objc subscript (i: Int) -> Int {
get {
return i
}
set {}
}
}
@objc protocol P {
func g()
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F
func direct_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = objc_method [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign : (X) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
obj.f!()
}
// CHECK: } // end sil function '$s14dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @$s14dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F
func direct_to_protocol(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = objc_method [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #P.g!1.foreign : <Self where Self : P> (Self) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
obj.g!()
}
// CHECK: } // end sil function '$s14dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @$s14dynamic_lookup23direct_to_static_method{{[_0-9a-zA-Z]*}}F
func direct_to_static_method(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
var obj = obj
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: end_access [[READ]]
// CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened([[UUID:".*"]]) AnyObject).Type
// CHECK-NEXT: [[METHOD:%[0-9]+]] = objc_method [[OPENMETA]] : $@thick (@opened([[UUID]]) AnyObject).Type, #X.staticF!1.foreign : (X.Type) -> () -> (), $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: apply [[METHOD]]([[OPENMETA]]) : $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: destroy_value [[OBJBOX]]
type(of: obj).staticF!()
}
// } // end sil function '_TF14dynamic_lookup23direct_to_static_method{{.*}}'
// CHECK-LABEL: sil hidden @$s14dynamic_lookup12opt_to_class{{[_0-9a-zA-Z]*}}F
func opt_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
var obj = obj
// CHECK: [[EXISTBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[EXISTBOX]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]]
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: [[PBOPT:%.*]] = project_box [[OPTBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[EXISTVAL:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_SELF:%[0-9]*]] = open_existential_ref [[EXISTVAL]]
// CHECK: [[OPT_TMP:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// CHECK: dynamic_method_br [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign, [[HASBB:[a-zA-z0-9]+]], [[NOBB:[a-zA-z0-9]+]]
// Has method BB:
// CHECK: [[HASBB]]([[UNCURRIED:%[0-9]+]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()):
// CHECK: [[OBJ_SELF_COPY:%.*]] = copy_value [[OBJ_SELF]]
// CHECK: [[PARTIAL:%[0-9]+]] = partial_apply [callee_guaranteed] [[UNCURRIED]]([[OBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: [[THUNK_PAYLOAD:%.*]] = init_enum_data_addr [[OPT_TMP]]
// CHECK: store [[PARTIAL]] to [init] [[THUNK_PAYLOAD]]
// CHECK: inject_enum_addr [[OPT_TMP]] : $*Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt.1
// CHECK: br [[CONTBB:[a-zA-Z0-9]+]]
// No method BB:
// CHECK: [[NOBB]]:
// CHECK: inject_enum_addr [[OPT_TMP]] : {{.*}}, #Optional.none!enumelt
// CHECK: br [[CONTBB]]
// Continuation block
// CHECK: [[CONTBB]]:
// CHECK: [[OPT:%.*]] = load [take] [[OPT_TMP]]
// CHECK: store [[OPT]] to [init] [[PBOPT]] : $*Optional<@callee_guaranteed () -> ()>
// CHECK: dealloc_stack [[OPT_TMP]]
var of: (() -> ())! = obj.f
// Exit
// CHECK: destroy_value [[OBJ_SELF]] : $@opened({{".*"}}) AnyObject
// CHECK: destroy_value [[OPTBOX]] : ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: destroy_value [[EXISTBOX]] : ${ var AnyObject }
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup20forced_without_outer{{[_0-9a-zA-Z]*}}F
func forced_without_outer(_ obj: AnyObject) {
// CHECK: dynamic_method_br
var f = obj.f!
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup20opt_to_static_method{{[_0-9a-zA-Z]*}}F
func opt_to_static_method(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: [[PBO:%.*]] = project_box [[OPTBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJCOPY:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened
// CHECK: [[OBJCMETA:%[0-9]+]] = thick_to_objc_metatype [[OPENMETA]]
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// CHECK: dynamic_method_br [[OBJCMETA]] : $@objc_metatype (@opened({{".*"}}) AnyObject).Type, #X.staticF!1.foreign, [[HASMETHOD:[A-Za-z0-9_]+]], [[NOMETHOD:[A-Za-z0-9_]+]]
var optF: (() -> ())! = type(of: obj).staticF
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F
func opt_to_property(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: project_box [[INT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2
// CHECK: bb1([[METHOD:%[0-9]+]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// CHECK: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]]
// CHECK: [[BOUND_METHOD:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[RAWOBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[BOUND_METHOD]]
// CHECK: [[VALUE:%[0-9]+]] = apply [[B]]() : $@callee_guaranteed () -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[VALUE]] to [trivial] [[VALUETEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: destroy_value [[BOUND_METHOD]]
// CHECK: br bb3
var i: Int = obj.value!
}
// CHECK: } // end sil function '$s14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F'
// GUARANTEED-LABEL: sil hidden @$s14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F
// GUARANTEED: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// GUARANTEED: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// GUARANTEED: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// GUARANTEED: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// GUARANTEED: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// GUARANTEED: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int }
// GUARANTEED: project_box [[INT_BOX]]
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// GUARANTEED: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// GUARANTEED: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// GUARANTEED: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// GUARANTEED: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2
// GUARANTEED: bb1([[METHOD:%[0-9]+]] : @trivial $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// GUARANTEED: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]]
// GUARANTEED: [[BOUND_METHOD:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[RAWOBJ_SELF_COPY]])
// GUARANTEED: [[BEGIN_BORROW:%.*]] = begin_borrow [[BOUND_METHOD]]
// GUARANTEED: [[VALUE:%[0-9]+]] = apply [[BEGIN_BORROW]]
// GUARANTEED: end_borrow [[BEGIN_BORROW]]
// GUARANTEED: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// GUARANTEED: store [[VALUE]] to [trivial] [[VALUETEMP]]
// GUARANTEED: inject_enum_addr [[OPTTEMP]]{{.*}}some
// GUARANTEED: destroy_value [[BOUND_METHOD]]
// GUARANTEED: br bb3
// CHECK-LABEL: sil hidden @$s14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F
func direct_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject, [[I:%[0-9]+]] : @trivial $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: alloc_box ${ var Int }
// CHECK: project_box
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : @trivial $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// CHECK: [[RESULT:%[0-9]+]] = apply [[B]]([[I]]) : $@callee_guaranteed (Int) -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: destroy_value [[GETTER_WITH_SELF]]
// CHECK: br bb3
var x: Int = obj[i]!
}
// CHECK: } // end sil function '$s14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F'
// GUARANTEED-LABEL: sil hidden @$s14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F
// GUARANTEED: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject, [[I:%[0-9]+]] : @trivial $Int):
// GUARANTEED: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// GUARANTEED: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// GUARANTEED: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// GUARANTEED: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// GUARANTEED: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// GUARANTEED: [[PBI:%.*]] = project_box [[I_BOX]]
// GUARANTEED: store [[I]] to [trivial] [[PBI]] : $*Int
// GUARANTEED: alloc_box ${ var Int }
// GUARANTEED: project_box
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// GUARANTEED: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// GUARANTEED: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// GUARANTEED: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// GUARANTEED: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// GUARANTEED: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// GUARANTEED: bb1([[GETTER:%[0-9]+]] : @trivial $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// GUARANTEED: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// GUARANTEED: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]])
// GUARANTEED: [[BORROW:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// GUARANTEED: [[RESULT:%[0-9]+]] = apply [[BORROW]]([[I]])
// GUARANTEED: end_borrow [[BORROW]]
// GUARANTEED: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// GUARANTEED: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// GUARANTEED: inject_enum_addr [[OPTTEMP]]{{.*}}some
// GUARANTEED: destroy_value [[GETTER_WITH_SELF]]
// GUARANTEED: br bb3
// CHECK-LABEL: sil hidden @$s14dynamic_lookup16opt_to_subscript{{[_0-9a-zA-Z]*}}F
func opt_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject, [[I:%[0-9]+]] : @trivial $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : @trivial $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// CHECK: [[RESULT:%[0-9]+]] = apply [[B]]([[I]]) : $@callee_guaranteed (Int) -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]
// CHECK: destroy_value [[GETTER_WITH_SELF]]
// CHECK: br bb3
obj[i]
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup8downcast{{[_0-9a-zA-Z]*}}F
func downcast(_ obj: AnyObject) -> X {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[X:%[0-9]+]] = unconditional_checked_cast [[OBJ]] : $AnyObject to $X
// CHECK: destroy_value [[OBJ_BOX]] : ${ var AnyObject }
// CHECK: return [[X]] : $X
return obj as! X
}
@objc class Juice { }
@objc protocol Fruit {
@objc optional var juice: Juice { get }
}
// CHECK-LABEL: sil hidden @$s14dynamic_lookup7consumeyyAA5Fruit_pF
// CHECK: bb0(%0 : @guaranteed $Fruit):
// CHECK: [[BOX:%.*]] = alloc_stack $Optional<Juice>
// CHECK: dynamic_method_br [[SELF:%.*]] : $@opened("{{.*}}") Fruit, #Fruit.juice!getter.1.foreign, bb1, bb2
// CHECK: bb1([[FN:%.*]] : @trivial $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]([[SELF_COPY]]) : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice
// CHECK: [[B:%.*]] = begin_borrow [[METHOD]]
// CHECK: [[RESULT:%.*]] = apply [[B]]() : $@callee_guaranteed () -> @owned Juice
// CHECK: end_borrow [[B]]
// CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1
// CHECK: store [[RESULT]] to [init] [[PAYLOAD]]
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1
// CHECK: destroy_value [[METHOD]]
// CHECK: br bb3
// CHECK: bb2:
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.none!enumelt
// CHECK: br bb3
// CHECK: bb3:
// CHECK: return
func consume(_ fruit: Fruit) {
_ = fruit.juice
}
// rdar://problem/29249513 -- looking up an IUO member through AnyObject
// produces a Foo!? type. The SIL verifier did not correctly consider Optional
// to be the lowering of IUO (which is now eliminated by SIL lowering).
@objc protocol IUORequirement {
var iuoProperty: AnyObject! { get }
}
func getIUOPropertyDynamically(x: AnyObject) -> Any {
return x.iuoProperty
}
| 9bcec98088a683431e6b55b1006547eb | 53.994413 | 229 | 0.570398 | false | false | false | false |
vrace/stdstr | refs/heads/master | stdstr/stdstr.swift | mit | 1 | //
// stdstr.wift -- C++ 98 std::string port to Swift
//
// Copyright (c) 2016 LIU YANG
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public extension String {
static let npos: Int = Int.max
func begin() -> Index {
return startIndex
}
func end() -> Index {
return endIndex
}
func size() -> Int {
return length()
}
func length() -> Int {
return characters.count
}
mutating func resize(n: Int) {
self = substr(0, n)
}
mutating func resize(n: size_t, _ c: Character) {
if length() >= n {
self = substr(0, n)
}
else {
append(n - length(), c)
}
}
mutating func reserve(n: Int = 0) {
reserveCapacity(n)
}
mutating func clear() {
removeAll()
}
func empty() -> Bool {
return isEmpty
}
subscript(pos: Int) -> Character {
get {
return at(pos)
}
set(newValue) {
replace(pos, 1, String(newValue))
}
}
func at(pos: Int) -> Character {
return self[startIndex.advancedBy(pos)]
}
mutating func append(str: String) -> String {
appendContentsOf(str)
return self
}
mutating func append(str: String, _ subpos: Int, _ sublen: Int) -> String {
return append(str.substr(subpos, sublen))
}
mutating func append(s: String, _ n: Int) -> String {
return append(s.substr(0, n))
}
mutating func append(n: Int, _ c: Character) -> String {
self.append(String(count: n, repeatedValue: c))
return self
}
mutating func push_back(c: Character) {
self.append(c)
}
mutating func assign(str: String) -> String {
self = str
return self
}
mutating func assign(str: String, _ subpos: Int, _ sublen: Int) -> String {
return assign(str.substr(subpos, sublen))
}
mutating func assign(s: String, _ n: Int) -> String {
return assign(s.substr(0, n))
}
mutating func assign(n: Int, _ c: Character) -> String {
clear()
return append(n, c)
}
mutating func insert(pos: Int, _ str: String) -> String {
insertContentsOf(str.characters, at: startIndex.advancedBy(pos))
return self
}
mutating func insert(pos: Int, _ str: String, _ subpos: Int, _ sublen: Int) -> String {
return insert(pos, str.substr(subpos, sublen))
}
mutating func insert(pos: Int, _ s: String, _ n: Int) -> String {
return insert(pos, s.substr(0, n))
}
mutating func insert(pos: Int, _ n: Int, _ c: Character) -> String {
return insert(pos, String(count: n, repeatedValue: c))
}
mutating func insert(p: Index, _ n: Int, _ c: Character) {
insertContentsOf(String(count: n, repeatedValue: c).characters, at: p)
}
mutating func insert(p: Index, _ c: Character) -> Index {
let distance = begin().distanceTo(p)
insert(c, atIndex: p)
return begin().advancedBy(distance)
}
mutating func erase(pos: Int = 0, _ len: Int = String.npos) -> String {
return replace(pos, len, "")
}
mutating func erase(p: Index) -> Index {
let distance = begin().distanceTo(p)
replace(p, p.advancedBy(1), "")
return begin().advancedBy(distance)
}
mutating func erase(first: Index, _ last: Index) -> Index {
let distance = begin().distanceTo(first)
replace(first, last, "")
return begin().advancedBy(distance)
}
mutating func replace(pos: Int, _ len: Int, _ str: String) -> String {
let end = Int(min(UInt(pos) + UInt(len), UInt(length())))
return replace(startIndex.advancedBy(pos), startIndex.advancedBy(end), str)
}
mutating func replace(i1: Index, _ i2: Index, _ str: String) -> String {
replaceRange(i1 ..< i2, with: str)
return self
}
mutating func replace(pos: Int, _ len: Int, _ str: String, _ subpos: Int, _ sublen: Int) -> String {
return replace(pos, len, str.substr(subpos, sublen))
}
mutating func replace(pos: Int, _ len: Int, _ s: String, _ n: Int) -> String {
return replace(pos, len, s.substr(0, n))
}
mutating func replace(i1: Index, _ i2: Index, _ s: String, _ n: Int) -> String {
return replace(i1, i2, s.substr(0, n))
}
mutating func replace(pos: Int, _ len: Int, _ n: Int, _ c: Character) -> String {
return replace(pos, len, String(count: n, repeatedValue: c))
}
mutating func replace(i1: Index, _ i2: Index, _ n: Int, _ c: Character) -> String {
return replace(i1, i2, String(count: n, repeatedValue: c))
}
mutating func swap(inout str: String) {
let temp = self
self = str
str = temp
}
func copy(inout s: String, _ len: Int, _ pos: Int = 0) -> Int {
s.assign(self, pos, len)
return s.length()
}
func find(str: String, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
self.substr($0, str.length()) == str
}
}
func find(s: String, _ pos: Int, _ n: Int) -> Int {
return find(s.substr(0, n), pos)
}
func find(c: Character, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
self.at($0) == c
}
}
func rfind(str: String, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
self.substr($0, str.length()) == str
}
}
func rfind(s: String, _ pos: Int, _ n: Int) -> Int {
return rfind(s.substr(0, n), pos)
}
func rfind(c: Character, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
self.at($0) == c
}
}
func find_first_of(str: String, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
str.find(self.at($0)) != String.npos
}
}
func find_first_of(s: String, _ pos: Int, _ n: Int) -> Int {
return find_first_of(s.substr(0, n), pos)
}
func find_first_of(c: Character, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
self.at($0) == c
}
}
func find_last_of(str: String, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
str.find(self.at($0)) != String.npos
}
}
func find_last_of(s: String, _ pos: Int, _ n: Int) -> Int {
return find_last_of(s.substr(0, n), pos)
}
func find_last_of(c: Character, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
self.at($0) == c
}
}
func find_first_not_of(str: String, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
str.find(self.at($0)) == String.npos
}
}
func find_first_not_of(s: String, _ pos: Int, n: Int) -> Int {
return find_first_not_of(s.substr(0, n), pos)
}
func find_first_not_of(c: Character, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
self.at($0) != c
}
}
func find_last_not_of(str: String, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
str.find(self.at($0)) == String.npos
}
}
func find_last_not_of(s: String, _ pos: Int, n: Int) -> Int {
return find_last_not_of(s.substr(0, n), pos)
}
func find_last_not_of(c: Character, _ pos: Int = 0) -> Int {
return iterateBackward(pos) {
self.at($0) != c
}
}
func substr(pos: Int = 0, _ len: Int = String.npos) -> String {
let end = Int(min(UInt(pos) + UInt(len), UInt(length())))
return substringWithRange(startIndex.advancedBy(pos) ..< startIndex.advancedBy(end))
}
private func iterateForward(pos: Int, _ predicate: Int -> Bool) -> Int {
for index in pos.stride(to: length(), by: 1) {
if predicate(index) {
return index
}
}
return String.npos
}
private func iterateBackward(pos: Int, _ predicate: Int -> Bool) -> Int {
for index in min(length() - 1, pos).stride(through: 0, by: -1) {
if predicate(index) {
return index
}
}
return String.npos
}
}
// Not implemented methods
//
// Iterators
// =========
// reverse_iterator rbegin();
// const_reverse_iterator rbegin() const;
// reverse_iterator rend();
// const reverse_iterator rend() const;
//
// Capacity
// ========
// size_t max_size() const;
// size_t capacity() const;
//
// Element access
// ==============
// char& at(size_t pos);
//
// Modifiers
// =========
// template <class InputIterator> string& append(InputIterator first, InputIterator last);
// template <class InputIterator> string& assign(InputIterator first, InputIterator last);
// template <class InputIterator> void insert(iterator p, InputIterator first, InputIterator last);
// template <class InputIterator> string& replace(iterator i1, iterator i2, InputIterator first, InputIterator last);
//
// String operations
// =================
// const char* c_str() const;
// const char* data() const;
// allocator_type get_allocator() const;
// int compare(const string &str) const;
// int compare(size_t pos, size_t len, const string &str) const;
// int compare(size_t pos, size_t len, const string &str, size_t subpos, size_t sublen) const;
// int compare(const char *s) const;
// int compare(size_t pos, size_t len, const char *s) const;
// int compare(size_t pos, size_t len, const char *s, size_t n) const;
| 8a31c22d06a5c654d67df310d116feed | 29.101928 | 117 | 0.560813 | false | false | false | false |
Sherlouk/monzo-vapor | refs/heads/master | Sources/JSON+AssertValue.swift | mit | 1 | import Foundation
import JSON
extension JSON {
/// Obtain the value for a given key, throws if the value can not be found and casted
func value<T>(forKey key: String) throws -> T {
if T.self is String.Type, let value = self[key]?.string as? T { return value }
if T.self is Bool.Type, let value = self[key]?.bool as? T { return value }
if T.self is URL.Type, let value = self[key]?.url as? T { return value }
if T.self is Date.Type, let value = self[key]?.date as? T { return value }
if T.self is Int.Type, let value = self[key]?.int as? T { return value }
if self[key] != nil {
throw MonzoJSONError.unsupportedType(String(describing: T.self))
}
throw MonzoJSONError.missingKey(key)
}
}
| c436ae75d890f4c861085cdfb0bcdb8b | 38.9 | 89 | 0.606516 | false | false | false | false |
open-telemetry/opentelemetry-swift | refs/heads/main | Examples/Simple Exporter/main.swift | apache-2.0 | 1 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import JaegerExporter
import OpenTelemetryApi
import OpenTelemetrySdk
import ResourceExtension
import StdoutExporter
import ZipkinExporter
import SignPostIntegration
let sampleKey = "sampleKey"
let sampleValue = "sampleValue"
let resources = DefaultResources().get()
let instrumentationScopeName = "SimpleExporter"
let instrumentationScopeVersion = "semver:0.1.0"
var instrumentationScopeInfo = InstrumentationScopeInfo(name: instrumentationScopeName, version: instrumentationScopeVersion)
var tracer: TracerSdk
tracer = OpenTelemetrySDK.instance.tracerProvider.get(instrumentationName: instrumentationScopeName, instrumentationVersion: instrumentationScopeVersion) as! TracerSdk
func simpleSpan() {
let span = tracer.spanBuilder(spanName: "SimpleSpan").setSpanKind(spanKind: .client).startSpan()
span.setAttribute(key: sampleKey, value: sampleValue)
Thread.sleep(forTimeInterval: 0.5)
span.end()
}
func childSpan() {
let span = tracer.spanBuilder(spanName: "parentSpan").setSpanKind(spanKind: .client).setActive(true).startSpan()
span.setAttribute(key: sampleKey, value: sampleValue)
Thread.sleep(forTimeInterval: 0.2)
let childSpan = tracer.spanBuilder(spanName: "childSpan").setSpanKind(spanKind: .client).startSpan()
childSpan.setAttribute(key: sampleKey, value: sampleValue)
Thread.sleep(forTimeInterval: 0.5)
childSpan.end()
span.end()
}
let jaegerCollectorAdress = "localhost"
let jaegerExporter = JaegerSpanExporter(serviceName: "SimpleExporter", collectorAddress: jaegerCollectorAdress)
let stdoutExporter = StdoutExporter()
// let zipkinExporterOptions = ZipkinTraceExporterOptions()
// let zipkinExporter = ZipkinTraceExporter(options: zipkinExporterOptions)
let spanExporter = MultiSpanExporter(spanExporters: [jaegerExporter, stdoutExporter /* , zipkinExporter */ ])
let spanProcessor = SimpleSpanProcessor(spanExporter: spanExporter)
OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor)
if #available(macOS 10.14, *) {
OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(SignPostIntegration())
}
simpleSpan()
sleep(1)
childSpan()
sleep(1)
| 7c09789b595ca1de1e1ccfc6a230c55e | 33.584615 | 167 | 0.799822 | false | false | false | false |
jamesbond12/actor-platform | refs/heads/master | actor-apps/app-ios/ActorApp/Controllers/Contacts/Cells/ContactCell.swift | mit | 1 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
class ContactCell : UATableViewCell {
let avatarView = AvatarView(frameSize: 40, type: .Rounded);
let shortNameView = UILabel();
let titleView = UILabel();
init(reuseIdentifier:String) {
super.init(cellStyle: "cell", reuseIdentifier: reuseIdentifier)
titleView.font = UIFont.systemFontOfSize(18)
titleView.textColor = MainAppTheme.list.contactsTitle
shortNameView.font = UIFont.boldSystemFontOfSize(18)
shortNameView.textAlignment = NSTextAlignment.Center
shortNameView.textColor = MainAppTheme.list.contactsShortTitle
self.contentView.addSubview(avatarView);
self.contentView.addSubview(shortNameView);
self.contentView.addSubview(titleView);
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bindContact(contact: ACContact, shortValue: String?, isLast: Bool) {
avatarView.bind(contact.getName(), id: contact.getUid(), avatar: contact.getAvatar());
titleView.text = contact.getName();
if (shortValue == nil){
shortNameView.hidden = true;
} else {
shortNameView.text = shortValue!;
shortNameView.hidden = false;
}
topSeparatorVisible = false
bottomSeparatorVisible = true
bottomSeparatorLeftInset = isLast ? 0 : 80
}
override func layoutSubviews() {
super.layoutSubviews()
let width = self.contentView.frame.width;
shortNameView.frame = CGRectMake(0, 8, 30, 40);
avatarView.frame = CGRectMake(30, 8, 40, 40);
titleView.frame = CGRectMake(80, 8, width - 80 - 14, 40);
}
} | ebde996b4b2daf8c4c561f5abdb597fb | 31.206897 | 94 | 0.630959 | false | false | false | false |
CodaFi/swift | refs/heads/master | test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-enum-1argument-1distinct_use.swift | apache-2.0 | 2 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main9NamespaceO5ValueOySS_SiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main9NamespaceO5ValueOySS_SiGWV", i32 0, i32 0)
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main9NamespaceO5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSSN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Namespace<Arg> {
enum Value<First> {
case first(First)
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main9NamespaceO5ValueOySS_SiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Namespace<String>.Value.first(13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceO5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE_1]],
// CHECK-SAME: i8* [[ERASED_TYPE_2]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main9NamespaceO5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| 21a57880c8c14a79499a49b6c7c68f22 | 37.025316 | 157 | 0.59221 | false | false | false | false |
2h4u/Async | refs/heads/master | Carthage/Checkouts/SwiftTask/Carthage/Checkouts/Async/AsyncTest/Tests/AsyncTests.swift | mit | 2 | //
// AsyncExample_iOSTests.swift
// AsyncExample iOSTests
//
// Created by Tobias DM on 15/07/14.
// Copyright (c) 2014 Tobias Due Munk. All rights reserved.
//
import Foundation
import XCTest
import Async
extension qos_class_t: CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
class AsyncTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// Typical testing time delay. Must be bigger than `timeMargin`
let timeDelay = 0.3
// Allowed error for timeDelay
let timeMargin = 0.2
/* GCD */
func testGCD() {
let expectation = self.expectation(description: "Expected after time")
let qos: DispatchQoS.QoSClass = .background
let queue = DispatchQueue.global(qos: qos)
queue.async {
XCTAssertEqual(qos_class_self(), qos.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
/* dispatch_async() */
func testAsyncMain() {
let expectation = self.expectation(description: "Expected on main queue")
var calledStuffAfterSinceAsync = false
Async.main {
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
XCTAssert(calledStuffAfterSinceAsync, "Should be async")
expectation.fulfill()
}
calledStuffAfterSinceAsync = true
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncUserInteractive() {
let expectation = self.expectation(description: "Expected on user interactive queue")
Async.userInteractive {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncUserInitiated() {
let expectation = self.expectation(description: "Expected on user initiated queue")
Async.userInitiated {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncUtility() {
let expectation = self.expectation(description: "Expected on utility queue")
Async.utility {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncBackground() {
let expectation = self.expectation(description: "Expected on background queue")
Async.background {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncCustomQueueConcurrent() {
let expectation = self.expectation(description: "Expected custom queue")
let label = "CustomQueueLabel"
let customQueue = DispatchQueue(label: label, attributes: [.concurrent])
let key = DispatchSpecificKey<String>()
customQueue.setSpecific(key: key, value: label)
Async.custom(queue: customQueue) {
XCTAssertEqual(DispatchQueue.getSpecific(key: key), label)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncCustomQueueSerial() {
let expectation = self.expectation(description: "Expected custom queue")
let label = "CustomQueueLabel"
let customQueue = DispatchQueue(label: label, attributes: [])
let key = DispatchSpecificKey<String>()
customQueue.setSpecific(key: key, value: label)
Async.custom(queue: customQueue) {
XCTAssertEqual(DispatchQueue.getSpecific(key: key), label)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
/* Chaining */
func testAsyncBackgroundToMain() {
let expectation = self.expectation(description: "Expected on background to main queue")
var wasInBackground = false
Async.background {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
wasInBackground = true
}.main {
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
XCTAssert(wasInBackground, "Was in background first")
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin*2, handler: nil)
}
func testChaining() {
let expectation = self.expectation(description: "Expected On \(qos_class_self()) (expected \(DispatchQoS.QoSClass.userInitiated.rawValue))")
var id = 0
Async.main {
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
id += 1
XCTAssertEqual(id, 1, "Count main queue")
}.userInteractive {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
id += 1
XCTAssertEqual(id, 2, "Count user interactive queue")
}.userInitiated {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
id += 1
XCTAssertEqual(id, 3, "Count user initiated queue")
}.utility {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
id += 1
XCTAssertEqual(id, 4, "Count utility queue")
}.background {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
id += 1
XCTAssertEqual(id, 5, "Count background queue")
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin*5, handler: nil)
}
func testAsyncCustomQueueChaining() {
let expectation = self.expectation(description: "Expected custom queues")
var id = 0
let customQueue = DispatchQueue(label: "CustomQueueLabel", attributes: [.concurrent])
let otherCustomQueue = DispatchQueue(label: "OtherCustomQueueLabel", attributes: [])
Async.custom(queue: customQueue) {
id += 1
XCTAssertEqual(id, 1, "Count custom queue")
}.custom(queue: otherCustomQueue) {
id += 1
XCTAssertEqual(id, 2, "Count other custom queue")
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin*2, handler: nil)
}
/* dispatch_after() */
func testAfterGCD() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
let time = DispatchTime.now() + timeDelay
let qos = DispatchQoS.QoSClass.background
let queue = DispatchQueue.global(qos: qos)
queue.asyncAfter(deadline: time) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), qos.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterMain() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.main(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterUserInteractive() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.userInteractive(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterUserInitated() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.userInitiated(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterUtility() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.utility(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterBackground() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.background(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterCustomQueue() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let timeDelay = 1.0
let lowerTimeDelay = timeDelay - timeMargin
let label = "CustomQueueLabel"
let customQueue = DispatchQueue(label: label, attributes: [.concurrent])
let key = DispatchSpecificKey<String>()
customQueue.setSpecific(key: key, value: label)
Async.custom(queue: customQueue, after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(DispatchQueue.getSpecific(key: key), label)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterChainedMix() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.userInteractive(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed) >= \(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
date2 = Date() // Update
}.utility(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) + timeMargin*2, handler: nil)
}
func testAfterChainedUserInteractive() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.userInteractive(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed) >= \(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
date2 = Date() // Update
}.userInteractive(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) + timeMargin*2, handler: nil)
}
func testAfterChainedUserInitiated() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.userInitiated(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed) >= \(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
date2 = Date() // Update
}.userInitiated(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) + timeMargin*2, handler: nil)
}
func testAfterChainedUtility() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.utility(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed)>=\(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
date2 = Date() // Update
}.utility(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) * 2, handler: nil)
}
func testAfterChainedBackground() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.background(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed) >= \(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
date2 = Date() // Update
}.background(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) + timeMargin*2, handler: nil)
}
/* dispatch_block_cancel() */
func testCancel() {
let expectation = self.expectation(description: "Block1 should run")
let block1 = Async.background {
// Some work
Thread.sleep(forTimeInterval: 0.2)
expectation.fulfill()
}
let block2 = block1.background {
XCTFail("Shouldn't be reached, since cancelled")
}
Async.main(after: 0.1) {
block1.cancel() // First block is _not_ cancelled
block2.cancel() // Second block _is_ cancelled
}
waitForExpectations(timeout: 0.2 + 0.1 + timeMargin*3, handler: nil)
}
/* dispatch_wait() */
func testWait() {
var id = 0
let block = Async.background {
// Some work
Thread.sleep(forTimeInterval: 0.1)
id += 1
XCTAssertEqual(id, 1, "")
}
XCTAssertEqual(id, 0, "")
block.wait()
id += 1
XCTAssertEqual(id, 2, "")
}
func testWaitMax() {
var id = 0
let date = Date()
let upperTimeDelay = timeDelay + timeMargin
let block = Async.background {
id += 1
XCTAssertEqual(id, 1, "The id should be 1") // A
// Some work that takes longer than we want to wait for
Thread.sleep(forTimeInterval: self.timeDelay + self.timeMargin)
id += 1 // C
}
let idCheck = id // XCTAssertEqual is experienced to behave as a wait
XCTAssertEqual(idCheck, 0, "The id should be 0, since block is send to background")
// Wait
block.wait(seconds: timeDelay)
id += 1
XCTAssertEqual(id, 2, "The id should be 2, since the block has begun running") // B
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed < upperTimeDelay, "Shouldn't wait \(upperTimeDelay) seconds before firing")
}
/* Generics */
func testGenericsChain() {
let expectationBackground = self.expectation(description: "Expected on background queue")
let expectationMain = self.expectation(description: "Expected on main queue")
let testValue = 10
Async.background {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectationBackground.fulfill()
return testValue
}.main { (value: Int) in
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
expectationMain.fulfill()
XCTAssertEqual(value, testValue)
return
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testGenericsWait() {
let asyncBlock = Async.background {
return 10
}.utility {
return "T\($0)"
}
asyncBlock.wait()
XCTAssertEqual(asyncBlock.output, Optional("T10"))
}
func testGenericsWaitMax() {
var complete1 = false
var complete2 = false
let asyncBlock = Async.background {
complete1 = true
// Some work that takes longer than we want to wait for
Thread.sleep(forTimeInterval: self.timeDelay + self.timeMargin)
complete2 = true
return 10
}.utility { (_: Int) -> Void in }
asyncBlock.wait(seconds: timeMargin)
XCTAssertNil(asyncBlock.output)
XCTAssert(complete1, "Should have been set in background block")
XCTAssertFalse(complete2, "Should not have been set/reached in background block")
}
/* dispatch_apply() */
func testApplyUserInteractive() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
Apply.userInteractive(count) { i in
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testApplyUserInitiated() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
Apply.userInitiated(count) { i in
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testApplyUtility() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
Apply.utility(count) { i in
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testApplyBackground() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
Apply.background(count) { i in
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testApplyCustomQueueConcurrent() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
let label = "CustomQueueConcurrentLabel"
let customQueue = DispatchQueue(label: label, qos: .utility, attributes: [.concurrent])
Apply.custom(queue: customQueue, iterations: count) { i in
XCTAssertEqual(qos_class_self(), customQueue.qos.qosClass.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testApplyCustomQueueSerial() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
let label = "CustomQueueSerialLabel"
let customQueue = DispatchQueue(label: label, qos: .utility, attributes: [])
Apply.custom(queue: customQueue, iterations: count) { i in
XCTAssertEqual(qos_class_self(), customQueue.qos.qosClass.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
}
| 7da177ddcffe38c3a6c2a63b4e61665b | 39.72561 | 148 | 0.624644 | false | true | false | false |
qingpengchen2011/PageMenu | refs/heads/master | Demos/Demo 4/PageMenuDemoTabbar/PageMenuDemoTabbar/PageMenuOneViewController.swift | bsd-3-clause | 3 | //
// PageMenuOneViewController.swift
// PageMenuDemoTabbar
//
// Created by Niklas Fahl on 1/9/15.
// Copyright (c) 2015 Niklas Fahl. All rights reserved.
//
import UIKit
class PageMenuOneViewController: UIViewController {
var pageMenu : CAPSPageMenu?
@IBOutlet weak var userPhotoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
userPhotoImageView.layer.cornerRadius = 8
// MARK: - Scroll menu setup
// Initialize view controllers to display and place in array
var controllerArray : [UIViewController] = []
var controller1 : TestTableViewController = TestTableViewController(nibName: "TestTableViewController", bundle: nil)
controller1.title = "favorites"
controllerArray.append(controller1)
var controller2 : RecentsTableViewController = RecentsTableViewController(nibName: "RecentsTableViewController", bundle: nil)
controller2.title = "recents"
controllerArray.append(controller2)
var controller3 : ContactsTableViewController = ContactsTableViewController(nibName: "ContactsTableViewController", bundle: nil)
controller3.title = "contacts"
controllerArray.append(controller3)
for i in 0...10 {
var controller3 : ContactsTableViewController = ContactsTableViewController(nibName: "ContactsTableViewController", bundle: nil)
controller3.title = "contr\(i)"
// controller3.view.backgroundColor = getRandomColor()
controllerArray.append(controller3)
}
// Customize menu (Optional)
var parameters: [String: AnyObject] = ["scrollMenuBackgroundColor": UIColor.orangeColor(),
"viewBackgroundColor": UIColor.whiteColor(),
"selectionIndicatorColor": UIColor.whiteColor(),
"unselectedMenuItemLabelColor": UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 0.4),
"menuItemFont": UIFont(name: "HelveticaNeue", size: 35.0)!,
"menuHeight": 44.0,
"menuMargin": 20.0,
"selectionIndicatorHeight": 0.0,
"bottomMenuHairlineColor": UIColor.orangeColor(),
"menuItemWidthBasedOnTitleTextWidth": true,
"selectedMenuItemLabelColor": UIColor.whiteColor()]
// Initialize scroll menu
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 60.0, self.view.frame.width, self.view.frame.height - 60.0), options: parameters)
self.view.addSubview(pageMenu!.view)
}
func getRandomColor() -> UIColor{
var randomRed:CGFloat = CGFloat(drand48())
var randomGreen:CGFloat = CGFloat(drand48())
var randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
}
| 44595ea52dac96815486672c1fff8401 | 44.905405 | 170 | 0.573153 | false | false | false | false |
ichu501/FBSimulatorControl | refs/heads/master | fbsimctl/FBSimulatorControlKit/Sources/iOSRunner.swift | bsd-3-clause | 1 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Foundation
import FBSimulatorControl
import FBDeviceControl
extension CommandResultRunner {
static func unimplementedActionRunner(_ action: Action, target: FBiOSTarget, format: FBiOSTargetFormat) -> Runner {
let (eventName, maybeSubject) = action.reportable
var actionMessage = eventName.rawValue
if let subject = maybeSubject {
actionMessage += " \(subject.description)"
}
let message = "Action \(actionMessage) is unimplemented for target \(format.format(target))"
return CommandResultRunner(result: CommandResult.failure(message))
}
}
struct iOSActionProvider {
let context: iOSRunnerContext<(Action, FBiOSTarget, iOSReporter)>
func makeRunner() -> Runner? {
let (action, target, reporter) = self.context.value
switch action {
case .diagnose(let query, let format):
return DiagnosticsRunner(reporter, query, query, format)
case .install(let appPath):
return iOSTargetRunner(
reporter: reporter,
name: EventName.Install,
subject: ControlCoreSubject(appPath as NSString),
interaction: FBCommandInteractions.installApplication(withPath: appPath, command: target)
)
case .uninstall(let appBundleID):
return iOSTargetRunner(reporter, EventName.Uninstall,ControlCoreSubject(appBundleID as NSString)) {
try target.uninstallApplication(withBundleID: appBundleID)
}
case .launchApp(let appLaunch):
return iOSTargetRunner(
reporter: reporter,
name: EventName.Launch,
subject: ControlCoreSubject(appLaunch),
interaction: FBCommandInteractions.launchApplication(appLaunch, command: target)
)
case .listApps:
return iOSTargetRunner(reporter, nil, ControlCoreSubject(target as! ControlCoreValue)) {
let subject = ControlCoreSubject(target.installedApplications().map { $0.jsonSerializableRepresentation() } as NSArray)
reporter.reporter.reportSimple(EventName.ListApps, EventType.Discrete, subject)
}
case .record(let start):
return iOSTargetRunner(
reporter: reporter,
name: EventName.Record,
subject: start,
interaction: start ? FBCommandInteractions.startRecording(withCommand: target) : FBCommandInteractions.stopRecording(withCommand: target)
)
case .terminate(let bundleID):
return iOSTargetRunner(
reporter: reporter,
name: EventName.Terminate,
subject: ControlCoreSubject(bundleID as NSString),
interaction: FBCommandInteractions.killApplication(withBundleID: bundleID, command: target)
)
default:
return nil
}
}
}
struct iOSTargetRunner : Runner {
let reporter: iOSReporter
let name: EventName?
let subject: EventReporterSubject
let interaction: FBInteractionProtocol
init(reporter: iOSReporter, name: EventName?, subject: EventReporterSubject, interaction: FBInteractionProtocol) {
self.reporter = reporter
self.name = name
self.subject = subject
self.interaction = interaction
}
init(_ reporter: iOSReporter, _ name: EventName?, _ subject: EventReporterSubject, _ action: @escaping (Void) throws -> Void) {
self.init(reporter: reporter, name: name, subject: subject, interaction: Interaction(action))
}
func run() -> CommandResult {
do {
if let name = self.name {
self.reporter.report(name, EventType.Started, self.subject)
}
try self.interaction.perform()
if let name = self.name {
self.reporter.report(name, EventType.Ended, self.subject)
}
} catch let error as NSError {
return .failure(error.description)
} catch let error as JSONError {
return .failure(error.description)
} catch {
return .failure("Unknown Error")
}
return .success(nil)
}
}
private struct DiagnosticsRunner : Runner {
let reporter: iOSReporter
let subject: ControlCoreValue
let query: FBDiagnosticQuery
let format: DiagnosticFormat
init(_ reporter: iOSReporter, _ subject: ControlCoreValue, _ query: FBDiagnosticQuery, _ format: DiagnosticFormat) {
self.reporter = reporter
self.subject = subject
self.query = query
self.format = format
}
func run() -> CommandResult {
reporter.reportValue(EventName.Diagnose, EventType.Started, query)
let diagnostics = self.fetchDiagnostics()
reporter.reportValue(EventName.Diagnose, EventType.Ended, query)
let subjects: [EventReporterSubject] = diagnostics.map { diagnostic in
return SimpleSubject(
EventName.Diagnostic,
EventType.Discrete,
ControlCoreSubject(diagnostic)
)
}
return .success(CompositeSubject(subjects))
}
func fetchDiagnostics() -> [FBDiagnostic] {
let diagnostics = self.reporter.target.diagnostics
let format = self.format
return diagnostics.perform(query).map { diagnostic in
switch format {
case .CurrentFormat:
return diagnostic
case .Content:
return FBDiagnosticBuilder(diagnostic: diagnostic).readIntoMemory().build()
case .Path:
return FBDiagnosticBuilder(diagnostic: diagnostic).writeOutToFile().build()
}
}
}
}
| a43d3811bad1f8fcee1d861ae5991bfa | 33.772152 | 145 | 0.705497 | false | false | false | false |
kickstarter/ios-oss | refs/heads/main | Kickstarter-iOS/Features/Discovery/Views/Cells/ActivitySampleFollowCell.swift | apache-2.0 | 1 | import KsApi
import Library
import Prelude
import UIKit
internal protocol ActivitySampleFollowCellDelegate: AnyObject {
/// Call when should go to activity screen.
func goToActivity()
}
internal final class ActivitySampleFollowCell: UITableViewCell, ValueCell {
fileprivate let viewModel: ActivitySampleFollowCellViewModelType = ActivitySampleFollowCellViewModel()
internal weak var delegate: ActivitySampleFollowCellDelegate?
@IBOutlet fileprivate var activityStackView: UIStackView!
@IBOutlet fileprivate var activityTitleLabel: UILabel!
@IBOutlet fileprivate var cardView: UIView!
@IBOutlet fileprivate var friendFollowLabel: UILabel!
@IBOutlet fileprivate var friendImageAndFollowStackView: UIStackView!
@IBOutlet fileprivate var friendImageView: CircleAvatarImageView!
@IBOutlet fileprivate var seeAllActivityButton: UIButton!
internal override func awakeFromNib() {
super.awakeFromNib()
self.seeAllActivityButton.addTarget(
self,
action: #selector(self.seeAllActivityButtonTapped),
for: .touchUpInside
)
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> activitySampleCellStyle
|> \.backgroundColor .~ discoveryPageBackgroundColor()
_ = self.activityStackView
|> activitySampleStackViewStyle
_ = self.activityTitleLabel
|> activitySampleTitleLabelStyle
_ = self.cardView
|> dropShadowStyleMedium()
_ = self.friendFollowLabel
|> activitySampleFriendFollowLabelStyle
_ = self.friendImageAndFollowStackView
|> UIStackView.lens.spacing .~ Styles.grid(2)
_ = self.friendImageView
|> ignoresInvertColorsImageViewStyle
_ = self.seeAllActivityButton
|> activitySampleSeeAllActivityButtonStyle
}
internal override func bindViewModel() {
super.bindViewModel()
self.friendFollowLabel.rac.text = self.viewModel.outputs.friendFollowText
self.viewModel.outputs.friendImageURL
.observeForUI()
.on(event: { [weak self] _ in
self?.friendImageView.af.cancelImageRequest()
self?.friendImageView.image = nil
})
.skipNil()
.observeValues { [weak self] url in
self?.friendImageView.af.setImage(withURL: url)
}
self.viewModel.outputs.goToActivity
.observeForUI()
.observeValues { [weak self] _ in
self?.delegate?.goToActivity()
}
}
internal func configureWith(value: Activity) {
self.viewModel.inputs.configureWith(activity: value)
}
@objc fileprivate func seeAllActivityButtonTapped() {
self.viewModel.inputs.seeAllActivityTapped()
}
}
| 93f5f8b29eb42054322b2eb6a8be1e58 | 27.619565 | 104 | 0.729966 | false | false | false | false |
belatrix/iOSAllStars | refs/heads/master | AllStarsV2/AllStarsV2/CommonClasses/CoredataMedia/CDMKeyChain.swift | apache-2.0 | 1 | //
// CDMKeyChain.swift
// InicioSesion
//
// Created by Kenyi Rodriguez on 6/01/17.
// Copyright © 2017 Core Data Media. All rights reserved.
//
import UIKit
public class CDMKeyChain: NSObject {
//MARK: - Público
public class func dataDesdeKeychainConCuenta(_ cuenta : String, conServicio servicio : String) -> Data? {
let tienePermiso = self.dispositivoCorrecto()
if tienePermiso == true {
let data = self.keychainDataConCuenta(cuenta, conServicio: servicio)
return data
}else{
exit(-1)
}
return nil
}
@discardableResult public class func guardarDataEnKeychain(_ data : Data, conCuenta cuenta : String, conServicio servicio : String) -> Bool {
let tienePermiso = self.dispositivoCorrecto()
if tienePermiso == true {
let guardado = self.guardarEnKeychain(data, conCuenta: cuenta, conServicio: servicio)
return guardado
}else{
exit(-1)
}
return false
}
public class func eliminarKeychain(){
let arrayElementosSeguridad = [kSecClassGenericPassword,
kSecClassInternetPassword,
kSecClassCertificate,
kSecClassKey,
kSecClassIdentity]
for elementoSeguridad in arrayElementosSeguridad{
let query = [kSecClass as String : elementoSeguridad]
SecItemDelete(query as CFDictionary)
}
}
//MARK: - Privado
private class func dispositivoCorrecto() -> Bool {
//Descomentar para producción, ya que en el simulador tampoco deja ejecutar para evitar injections en el código.
/*
if FileManager.default.fileExists(atPath: "/Applications/Cydia.app") || FileManager.default.fileExists(atPath: "/Library/MobileSubstrate/MobileSubstrate.dylib") || FileManager.default.fileExists(atPath: "/bin/bash") || FileManager.default.fileExists(atPath: "/usr/sbin/sshd") || FileManager.default.fileExists(atPath: "/etc/apt") {
return false
}else{
let texto = "1234567890"
do{
try texto.write(toFile: "/private/cache.txt", atomically: true, encoding: String.Encoding.utf8)
return false
}catch{
if UIApplication.shared.canOpenURL(URL(string: "cydia://package/com.example.package")!) {
return false
}else{
return true
}
}
}*/
return true
}
private class func keychainDataConCuenta(_ cuenta : String, conServicio servicio : String) -> Data? {
let query : [String : Any] = [kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : cuenta,
kSecAttrService as String : servicio,
kSecMatchCaseInsensitive as String : kCFBooleanTrue,
kSecReturnData as String : kCFBooleanTrue]
var resultado : AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &resultado)
if status == noErr && resultado != nil {
return resultado as? Data
}
return nil
}
private class func guardarEnKeychain(_ data : Data, conCuenta cuenta : String, conServicio servicio : String) -> Bool {
let keychainData = data as CFData
let query : [String : Any] = [kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : cuenta,
kSecAttrService as String : servicio,
kSecValueData as String : keychainData as Data,
kSecAttrAccessible as String : kSecAttrAccessibleWhenUnlocked as String]
var keychainError = noErr
keychainError = SecItemAdd(query as CFDictionary, nil)
return keychainError == noErr ? true : false
}
}
| 54b2ad85eb9a283c24dd5336f4a2fa6a | 31.524138 | 339 | 0.511874 | false | false | false | false |
luisfcofv/rasgos-geometricos | refs/heads/master | rasgos-geometricos/Classes/Utilities/TanimotoDistance.swift | mit | 1 | //
// TanimotoDistance.swift
// rasgos-geometricos
//
// Created by Luis Flores on 3/7/15.
// Copyright (c) 2015 Luis Flores. All rights reserved.
//
import UIKit
class TanimotoDistance: NSObject {
class func tanimotoDistance(objectA:BinaryObject, objectB:BinaryObject) -> Double {
var sharedPixels = 0
var diff = Coordinate(x: objectB.centerOfMass.x - objectA.centerOfMass.x,
y: objectB.centerOfMass.y - objectA.centerOfMass.y)
for row in 0..<objectB.rows {
for col in 0..<objectB.columns {
if row - diff.y < 0 || row - diff.y >= objectA.rows
|| col - diff.x < 0 || col - diff.y >= objectA.columns {
continue
}
if objectA.grid[row - diff.y][col - diff.x] == 1
&& objectB.grid[row][col] == 1 {
sharedPixels++
}
}
}
var activePixels = objectA.activePixels + objectB.activePixels
return Double(activePixels - 2 * sharedPixels) / Double(activePixels - sharedPixels)
}
}
| 692846d07a35085f90153bc8b7ca989e | 30.972222 | 92 | 0.538662 | false | false | false | false |
bluelinelabs/Junction | refs/heads/master | Junction/Junction/StringSetting.swift | mit | 1 | //
// StringSetting.swift
// Junction
//
// Created by Jimmy McDermott on 7/5/16.
// Copyright © 2016 BlueLine Labs. All rights reserved.
//
import Foundation
import UIKit
public final class StringSetting: Setting {
public var placeholder: String?
public var defaultValue: String?
public var value: String
public var key: String
public init(placeholder: String?, defaultValue: String?, key: String, value: String, title: String?) {
self.placeholder = placeholder
self.defaultValue = defaultValue
self.key = key
self.value = value
super.init()
self.title = title
}
public override func configureCell(tableViewCell: UITableViewCell) {
super.configureCell(tableViewCell)
tableViewCell.textLabel!.text = "\(tableViewCell.textLabel!.text!) \(value)"
}
override public func store() {
JunctionKeeper.sharedInstance.addValueForKey(key, value: value)
}
}
| fa78d178eb14c331bdcfe1e2e8ff9c50 | 25.945946 | 106 | 0.654965 | false | true | false | false |
alvarozizou/Noticias-Leganes-iOS | refs/heads/develop | Pods/FeedKit/Sources/FeedKit/Parser/FeedDataType.swift | mit | 2 | //
// FeedDataType.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/// Types of data to determine how to parse a feed.
///
/// - xml: XML Data Type.
/// - json: JSON Data Type.
enum FeedDataType: String {
case xml
case json
}
fileprivate let inspectionPrefixLength = 200
extension FeedDataType {
/// A `FeedDataType` from the specified `Data` object
///
/// - Parameter data: The `Data` object.
init?(data: Data) {
// As a practical matter, the dispositive characters will be found near
// the start of the buffer. It's expensive to convert the entire buffer to
// a string because the conversion is not lazy. So inspect only a prefix
// of the buffer.
let string = String(decoding: data.prefix(inspectionPrefixLength), as: UTF8.self)
let dispositiveCharacters = CharacterSet.alphanumerics
.union(CharacterSet.punctuationCharacters)
.union(CharacterSet.symbols)
for scalar in string.unicodeScalars {
if !dispositiveCharacters.contains(scalar) { // Skip whitespace, BOM marker if present
continue
}
let char = Character(scalar)
switch char {
case "<":
self = .xml
return
case "{":
self = .json
return
default:
return nil
}
}
return nil
}
}
| eb201650a574f47ccead36c67ab65bba | 35.915493 | 98 | 0.644411 | false | false | false | false |
bingoogolapple/SwiftNote-PartTwo | refs/heads/master | CAAnimation-01基本动画/CAAnimation-01基本动画/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// CAAnimation-01基本动画
//
// Created by bingoogol on 14/10/25.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
/**
要实现简单动画,通过touchBegan方法来触发
1.平移动画
*/
class ViewController: UIViewController {
weak var myView:UIView!
override func viewDidLoad() {
super.viewDidLoad()
var myView = UIView(frame: CGRectMake(50, 50, 100, 100))
myView.backgroundColor = UIColor.redColor()
self.view.addSubview(myView)
self.myView = myView
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
var touch = touches.anyObject() as UITouch
var location = touch.locationInView(self.view)
// 将myView平移到手指触摸的目标点
// self.translationAnim(location)
if touch.view == self.myView {
println("点击myView")
}
// 苹果通过块代码封装后实现相同的效果
// UIView.animateWithDuration(1.0, animations: {
// self.myView.center = location
// },completion: { (finished:Bool) in
// println("结束动画 frame:\(self.myView.frame)")
// }
// )
}
///////////////////CABasic动画//////////////////
// 动画代理方法
// 动画开始(极少用)
override func animationDidStart(anim: CAAnimation!) {
println("开始动画")
}
// 动画结束(通常在动画结束后,做动画的后续处理)
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
var type = anim.valueForKey("animationType") as NSString
if type.isEqualToString("translationTo") {
// 通过键值取出需要移动到的目标点
var point = (anim.valueForKey("targetPoint") as NSValue).CGPointValue()
println("目标点:\(NSStringFromCGPoint(point))")
self.myView.center = point
}
println("结束动画 frame:\(self.myView.frame)")
}
// 平移动画到指定点
func translationAnim(point:CGPoint) {
// 1.实例化动画
// 注意:如果没有指定图层的锚点(定位点),position对应UIView的中心点
var anim = CABasicAnimation(keyPath: "position")
// 2.设置动画属性
// 1)fromValue(myView的当前坐标) & toValue
anim.toValue = NSValue(CGPoint: point)
// 2)动画的时长
anim.duration = 1.0
// 3)设置代理
anim.delegate = self
// 4)让动画停留在目标位置
/*
提示:通过设置动画在完成后不删除,以及向前填充,可以做到平移动画结束后
UIView看起来停留在目标位置,但是其本身的frame并不会发生变化
*/
// 5)注意:要修正坐标点的实际位置可以利用setValue方法,这里的key可以随意写
anim.setValue(NSValue(CGPoint: point), forKey: "targetPoint")
anim.setValue("translationTo", forKey: "animationType")
anim.removedOnCompletion = false
// forward逐渐逼近目标点
anim.fillMode = kCAFillModeForwards
// 3.将动画添加到图层
// 将动画添加到图层之后,系统会按照定义好的属性开始动画,通常程序员不在与动画进行交互
self.myView.layer.addAnimation(anim, forKey: nil)
}
} | d73232e876860150e35e425b49260cdb | 28.309278 | 83 | 0.590781 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.