repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Ramotion/showroom | Showroom/Utilities/Transitions/ZoomTransition.swift | 1 | 3350 | import UIKit
final class ZoomTransition: NSObject, UIViewControllerAnimatedTransitioning {
enum Direction { case presenting, dismissing }
private let originFrame: CGRect
private let direction: Direction
init(originFrame: CGRect, direction: Direction) {
self.originFrame = originFrame
self.direction = direction
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.33
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to)
else { return }
switch direction {
case .presenting: animatePresentation(from: fromVC, to: toVC, using: transitionContext)
case .dismissing: animateDismissal(from: fromVC, to: toVC, using: transitionContext)
}
}
private func animatePresentation(from sourceVC: UIViewController, to destinationVC: UIViewController, using transitionContext: UIViewControllerContextTransitioning) {
guard let snapshot = destinationVC.view.snapshotView(afterScreenUpdates: true) else { return }
let finalFrame = transitionContext.finalFrame(for: destinationVC)
snapshot.frame = originFrame
transitionContext.containerView.addSubview(destinationVC.view)
transitionContext.containerView.addSubview(snapshot)
destinationVC.view.isHidden = true
snapshot.alpha = 0
UIView.animate(
withDuration: transitionDuration(using: transitionContext),
delay: 0,
options: [.curveEaseInOut, .layoutSubviews],
animations: {
snapshot.frame = finalFrame
snapshot.alpha = 1
},
completion: { _ in
destinationVC.view.isHidden = false
snapshot.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
private func animateDismissal(from sourceVC: UIViewController, to destinationVC: UIViewController, using transitionContext: UIViewControllerContextTransitioning) {
guard let snapshot = sourceVC.view.snapshotView(afterScreenUpdates: false) else { return }
transitionContext.containerView.insertSubview(destinationVC.view, at: 0)
transitionContext.containerView.addSubview(snapshot)
sourceVC.view.isHidden = true
snapshot.alpha = 1
UIView.animate(
withDuration: transitionDuration(using: transitionContext),
delay: 0,
options: [.curveEaseIn, .layoutSubviews],
animations: { [weak self] in
snapshot.frame = self?.originFrame ?? .zero
snapshot.alpha = 0
},
completion: { _ in
sourceVC.view.isHidden = false
snapshot.removeFromSuperview()
if transitionContext.transitionWasCancelled { destinationVC.view.removeFromSuperview() }
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
| gpl-3.0 | 64d5f2d1d772a3ffb9c125d1549c2d2b | 40.875 | 170 | 0.657313 | 6.380952 | false | false | false | false |
blob8129/SequenceConverter | SequenceConverterTests/SequenceConverterTests.swift | 1 | 5631 | //
// SequenceConverterTests.swift
// SequenceConverterTests
//
// Created by Andrey Volobuev on 30/05/2017.
// Copyright © 2017 Andrey Volobuev. All rights reserved.
//
import XCTest
@testable import SequenceConverter
class SequenceConverterTests: XCTestCase {
// Comma space tests
func testFormatterBothItemsNotNil() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat("1", "2")
let expected = ", 1, 2"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when all items are not nil")
}
func testFormatterFirstItemIsNil() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat(nil, "2")
let expected = ", 2"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when first item is nil")
}
func testFormatterSecodItemIsNil() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat("1", nil)
let expected = ", 1"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when second item is nil")
}
func testFormatterBothItemsAreNil() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat(nil, nil)
let expected = ""
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when both item are nil")
}
func testFormatterTreeItems() {
let formatted = SequenceConverter.commaSpaceBeforeMiddleFormat("1", "2", "3")
let expected = ", 1, 2, 3"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when three item is not nil")
}
// Space tests
func testSpaceFormatterBothItemsNotNil() {
let formatted = SequenceConverter.middleSpaceFormat("1", "2")
let expected = "1 2"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when all items are not nil")
}
func testSpacFormatterFirstItemIsNil() {
let formatted = SequenceConverter.middleSpaceFormat(nil, "2")
let expected = "2"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when first item is nil")
}
func testSpacFormatterSecodItemIsNil() {
let formatted = SequenceConverter.middleSpaceFormat("1", nil)
let expected = "1"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when second item is nil")
}
func testSpacFormatterBothItemsAreNil() {
let formatted = SequenceConverter.middleSpaceFormat(nil, nil)
let expected = ""
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when both item are nil")
}
func testSpacFormatterTreeItems() {
let formatted = SequenceConverter.middleSpaceFormat("1", "2", "3")
let expected = "1 2 3"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when three item is not nil")
}
// Separator tests
func testThreeSeparartor() {
let arr: [CustomStringConvertible?] = ["1", "2", "3"]
let formatted = arr.toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1|2|3->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when three item is not nil")
}
func testOneSeparartor() {
let formatted = ["1"].toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when one item")
}
func testTwoSeparartor() {
let formatted = ["1", "2"].toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1|2->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when two items")
}
func testEmptySeparartor() {
let arr: [CustomStringConvertible?] = [String]()
let formatted = arr.toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = ""
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when empty")
}
func testNilSeparartor() {
let arr: [CustomStringConvertible?] = [nil]
let formatted = arr.toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = ""
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when nil")
}
func testMultipleEmptySeparartor() {
let formatted = ["1", "", "", "", "4", "5"].toStringWithSeparators(before: "<-", between: "|", after: "->")
let expected = "<-1|4|5->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when multiple are empty")
}
func testMultipleNilSeparartor() {
let formatted = ["1", nil, nil, nil, "4", "5"].toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1|4|5->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when multiple are nil")
}
func testMultipleEmptyAndNilSeparartor() {
let formatted = [nil, "1", "", nil, "", "4", nil, ""].toStringWithSeparators(before: "->", between: "|", after: "->")
let expected = "->1|4->"
XCTAssert(formatted == expected, "Expected result is \(expected) not \(formatted) when multiple are empty and nil")
}
}
| mit | 9e933cd7d0c0edf433f8bbda859d1f18 | 42.307692 | 125 | 0.62913 | 4.412226 | false | true | false | false |
EstefaniaGilVaquero/ciceIOS | App_MVC_Repaso/App_MVC_Repaso/DatosModel.swift | 1 | 932 | //
// DatosModel.swift
// App_MVC_Repaso
//
// Created by cice on 11/7/16.
// Copyright © 2016 cice. All rights reserved.
//
import UIKit
class DatosModel: NSObject {
var nombre : String?
var apellido : String?
var movil : Int?
var direccion : String?
var email : String?
var loremIpsum : String?
var fotoPerfil : UIImage?
var urlWebSite : NSURL?
init(pNombre : String,
pApellido : String,
pMovil : Int,
pDireccion : String,
pEmail : String,
pLoremIpsum : String,
pFotoPerfil : UIImage,
pUrlWebSite : NSURL) {
self.nombre = pNombre
self.apellido = pApellido
self.movil = pMovil
self.direccion = pDireccion
self.email = pEmail
self.loremIpsum = pLoremIpsum
self.fotoPerfil = pFotoPerfil
self.urlWebSite = pUrlWebSite
super.init()
}
}
| apache-2.0 | d1ebc91d43a0792ea63c1232fd692d20 | 21.166667 | 47 | 0.58217 | 3.56705 | false | false | false | false |
paulofaria/SwiftHTTPServer | Regular Expression/RegularExpression.swift | 3 | 11308 | // Regex.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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.
typealias CompiledRegex = regex_t
typealias RegexMatch = regmatch_t
struct RegularExpression {
enum CompileRegexResult {
case Success
case InvalidRepetitionCount
case InvalidRegularExpression
case InvalidRepetitionOperand
case InvalidCollatingElement
case InvalidCharacterClass
case TrailingBackslash
case InvalidBackreferenceNumber
case UnbalancedBrackets
case UnbalancedParentheses
case UnbalancedBraces
case InvalidCharacterRange
case OutOfMemory
case UnrecognizedError
init(code: Int32) {
switch code {
case 0: self = Success
case REG_BADBR: self = InvalidRepetitionCount
case REG_BADPAT: self = InvalidRegularExpression
case REG_BADRPT: self = InvalidRepetitionOperand
case REG_ECOLLATE: self = InvalidCollatingElement
case REG_ECTYPE: self = InvalidCharacterClass
case REG_EESCAPE: self = TrailingBackslash
case REG_ESUBREG: self = InvalidBackreferenceNumber
case REG_EBRACK: self = UnbalancedBrackets
case REG_EPAREN: self = UnbalancedParentheses
case REG_EBRACE: self = UnbalancedBraces
case REG_ERANGE: self = InvalidCharacterRange
case REG_ESPACE: self = OutOfMemory
default: self = UnrecognizedError
}
}
// better error with http://codepad.org/X1Qb8kfc
var failure: ErrorType? {
switch self {
case Success: return .None
case InvalidRepetitionCount: return Error.Generic("Could not compile regex", "Invalid Repetition Count")
case InvalidRegularExpression: return Error.Generic("Could not compile regex", "Invalid Regular Expression")
case InvalidRepetitionOperand: return Error.Generic("Could not compile regex", "Invalid Repetition Operand")
case InvalidCollatingElement: return Error.Generic("Could not compile regex", "Invalid Collating Element")
case InvalidCharacterClass: return Error.Generic("Could not compile regex", "Invalid Character Class")
case TrailingBackslash: return Error.Generic("Could not compile regex", "Trailing Backslash")
case InvalidBackreferenceNumber: return Error.Generic("Could not compile regex", "Invalid Backreference Number")
case UnbalancedBrackets: return Error.Generic("Could not compile regex", "Unbalanced Brackets")
case UnbalancedParentheses: return Error.Generic("Could not compile regex", "Unbalanced Parentheses")
case UnbalancedBraces: return Error.Generic("Could not compile regex", "Unbalanced Braces")
case InvalidCharacterRange: return Error.Generic("Could not compile regex", "Invalid Character Range")
case OutOfMemory: return Error.Generic("Could not compile regex", "Out Of Memory")
case UnrecognizedError: return Error.Generic("Could not compile regex", "Unrecognized Error")
}
}
}
struct CompileRegexOptions: OptionSetType {
let rawValue: Int32
static let Basic = CompileRegexOptions(rawValue: REG_BASIC)
static let Extended = CompileRegexOptions(rawValue: REG_EXTENDED)
static let CaseInsensitive = CompileRegexOptions(rawValue: REG_ICASE)
static let ResultOnly = CompileRegexOptions(rawValue: REG_NOSUB)
static let NewLineSensitive = CompileRegexOptions(rawValue: REG_NEWLINE)
}
enum MatchRegexResult {
case Success
case NoMatch
case OutOfMemory
init(code: Int32) {
switch code {
case 0: self = Success
case REG_NOMATCH: self = NoMatch
case REG_ESPACE: self = OutOfMemory
default: fatalError()
}
}
var failure: ErrorType? {
switch self {
case OutOfMemory: return Error.Generic("Could not match regex", "Out Of Memory")
default: return .None
}
}
var didMatch: Bool {
switch self {
case Success: return true
default: return false
}
}
}
struct MatchRegexOptions: OptionSetType {
let rawValue: Int32
static let FirstCharacterNotAtBeginningOfLine = CompileRegexOptions(rawValue: REG_NOTBOL)
static let LastCharacterNotAtEndOfLine = CompileRegexOptions(rawValue: REG_NOTEOL)
}
let pattern: String
let regex: CompiledRegex
init(pattern: String, options: CompileRegexOptions = [.Extended]) throws {
self.pattern = pattern
self.regex = try RegularExpression.compileRegex(pattern, options: options)
}
func groups(string: String) throws -> [String] {
return try RegularExpression.groups(regex, string: string)
}
func matches(string: String) throws -> Bool {
return try RegularExpression.matches(regex, string: string)
}
func replace(string: String, withTemplate template: String) throws -> String {
return try RegularExpression.replace(regex, string: string, template: template)
}
}
// MARK: Private
extension RegularExpression {
private static func compileRegex(pattern: String, options: CompileRegexOptions = [.Extended]) throws -> CompiledRegex {
var regex = CompiledRegex()
let result = CompileRegexResult(code: regcomp(®ex, pattern, options.rawValue))
if let error = result.failure {
throw error
} else {
return regex
}
}
private static func matches(regex: CompiledRegex, string: String, maxNumberOfMatches: Int = 10, options: MatchRegexOptions = []) throws -> Bool {
let firstMatch = try RegularExpression.firstMatch(regex, string: string, maxNumberOfMatches: maxNumberOfMatches, options: options)
if firstMatch != nil {
return true
}
return false
}
private static func groups(regex: CompiledRegex, var string: String, maxNumberOfMatches: Int = 10, options: MatchRegexOptions = []) throws -> [String] {
var allGroups: [String] = []
while let regexMatches = try RegularExpression.firstMatch(regex, string: string, maxNumberOfMatches: maxNumberOfMatches, options: options) {
allGroups += RegularExpression.getGroups(regexMatches, string: string)
let regexMatch = regexMatches.first!
let endOfMatchIndex = string.startIndex.advancedBy(Int(regexMatch.rm_eo))
string = string[endOfMatchIndex ..< string.endIndex]
}
return allGroups
}
private static func firstMatch(var regex: CompiledRegex, string: String, maxNumberOfMatches: Int = 10, options: MatchRegexOptions = []) throws -> [RegexMatch]? {
let regexMatches = [RegexMatch](count: maxNumberOfMatches, repeatedValue: RegexMatch())
let code = regexec(®ex, string, maxNumberOfMatches, UnsafeMutablePointer<RegexMatch>(regexMatches), options.rawValue)
let result = MatchRegexResult(code: code)
if let error = result.failure {
throw error
}
if result.didMatch {
return regexMatches
} else {
return .None
}
}
private static func getGroups(regexMatches: [RegexMatch], string: String) -> [String] {
var groups: [String] = []
if regexMatches.count <= 1 {
return []
}
for var index = 1; regexMatches[index].rm_so != -1; index++ {
let regexMatch = regexMatches[index]
let range = getRange(regexMatch, string: string)
let match = string[range]
groups.append(match)
}
return groups
}
// TODO: fix bug where it doesn't find a match
private static func replace(regex: CompiledRegex, var string: String, template: String, maxNumberOfMatches: Int = 10, options: MatchRegexOptions = []) throws -> String {
var totalReplacedString: String = ""
while let regexMatches = try RegularExpression.firstMatch(regex, string: string, maxNumberOfMatches: maxNumberOfMatches, options: options) {
let regexMatch = regexMatches.first!
let endOfMatchIndex = string.startIndex.advancedBy(Int(regexMatch.rm_eo))
var replacedString = RegularExpression.replaceMatch(regexMatch, string: string, withTemplate: template)
let templateDelta = template.utf8.count - (regexMatch.rm_eo - regexMatch.rm_so)
let templateDeltaIndex = replacedString.startIndex.advancedBy(Int(regexMatch.rm_eo + templateDelta))
replacedString = replacedString[replacedString.startIndex ..< templateDeltaIndex]
totalReplacedString += replacedString
string = string[endOfMatchIndex ..< string.endIndex]
}
return totalReplacedString + string
}
private static func replaceMatch(regexMatch: RegexMatch, var string: String, withTemplate template: String) -> String {
let range = getRange(regexMatch, string: string)
string.replaceRange(range, with: template)
return string
}
private static func getRange(regexMatch: RegexMatch, string: String) -> Range<String.Index> {
let start = string.startIndex.advancedBy(Int(regexMatch.rm_so))
let end = string.startIndex.advancedBy(Int(regexMatch.rm_eo))
return start ..< end
}
}
extension String {
func replaceOccurrencesOfString(string: String, withString replaceString: String) -> String {
do {
let regularExpression = try RegularExpression(pattern: string)
return try regularExpression.replace(self, withTemplate: replaceString)
} catch {
return self
}
}
} | mit | 5a716e3b21bb39e22ce6249412ed5d84 | 30.413889 | 173 | 0.65069 | 4.992494 | false | false | false | false |
apple/swift | test/Frontend/enforce-exclusivity.swift | 44 | 668 | // Test command-line flags for enforcement of the law of exclusivity.
// RUN: %target-swift-frontend -enforce-exclusivity=checked %s -emit-silgen
// RUN: %target-swift-frontend -enforce-exclusivity=unchecked %s -emit-silgen
// Staging flags; eventually these will not be accepted.
// RUN: %target-swift-frontend -enforce-exclusivity=dynamic-only %s -emit-silgen
// RUN: %target-swift-frontend -enforce-exclusivity=none %s -emit-silgen
// RUN: not %target-swift-frontend -enforce-exclusivity=other %s -emit-silgen 2>&1 | %FileCheck -check-prefix=EXCLUSIVITY_UNRECOGNIZED %s
// EXCLUSIVITY_UNRECOGNIZED: unsupported argument 'other' to option '-enforce-exclusivity='
| apache-2.0 | 424586c17bb9a1baac1f9de1e6629c6f | 59.727273 | 137 | 0.766467 | 3.650273 | false | true | false | false |
githubxiangdong/DouYuZB | DouYuZB/DouYuZB/Classes/Room/Controller/RoomNormalViewController.swift | 1 | 1710 | //
// RoomNormalViewController.swift
// DouYuZB
//
// Created by new on 2017/5/16.
// Copyright © 2017年 9-kylins. All rights reserved.
//
import UIKit
class RoomNormalViewController: UIViewController , UIGestureRecognizerDelegate{
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.green
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// navigationController?.navigationBar.isHidden = true // 这个方法可以利用拖动手势返回
navigationController?.setNavigationBarHidden(true, animated: true) // 此方法不可以
// 保持pop手势,需要签UIGestureRecognizerDelegate代理
// 在cunstonNavigation里面实现了全屏手势,所以这里的保持手势就屏蔽掉
// navigationController?.interactivePopGestureRecognizer?.delegate = self
// navigationController?.interactivePopGestureRecognizer?.isEnabled = true
// 隐藏掉分栏控制器的tabbar
// tabBarController?.tabBar.isHidden = true // 此方法会在pop回来时直接显示,没有动画,效果不是很好
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// navigationController?.navigationBar.isHidden = false
navigationController?.setNavigationBarHidden(false, animated: true)
// 隐藏掉分栏控制器的tabbar
// 此方法会在pop回来时直接显示,没有动画,效果不是很好
// 所以就在自定义的navigation里面隐藏掉tabbar
// tabBarController?.tabBar.isHidden = false
}
}
| mit | 0b14f49b4d2789effe26278d99056f98 | 32.511628 | 84 | 0.691187 | 4.66343 | false | false | false | false |
einsteinx2/iSub | Classes/Extensions/UIView.swift | 1 | 918 | //
// UIView.swift
// iSub
//
// Created by Benjamin Baron on 1/9/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import UIKit
extension UIView {
var screenshot: UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.layer.isOpaque, 0.0)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
func scaledFrame(x: CGFloat, y: CGFloat) -> CGRect {
var scaledFrame = self.frame
scaledFrame.size.width *= x
scaledFrame.size.height *= y
scaledFrame.origin.x = self.frame.origin.x - (((self.frame.size.width * x) - self.frame.size.width) / 2)
scaledFrame.origin.y = self.frame.origin.y - (((self.frame.size.height * y) - self.frame.size.height) / 2)
return scaledFrame
}
}
| gpl-3.0 | 1fe61f2673b69713ca000e6659f32122 | 31.75 | 114 | 0.654308 | 3.918803 | false | false | false | false |
aslanyanhaik/youtube-iOS | YouTube/Extensions/extensions.swift | 1 | 2878 | // MIT License
// Copyright (c) 2017 Haik Aslanyan
// 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
// uicolor init simplified
extension UIColor{
class func rbg(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
let color = UIColor.init(red: r/255, green: g/255, blue: b/255, alpha: 1)
return color
}
}
extension MutableCollection where Index == Int {
mutating func myShuffle() {
if count < 2 { return }
for i in startIndex ..< endIndex - 1 {
let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i
if i != j {
self.swapAt(i, j)
}
}
}
}
extension Int {
func secondsToFormattedString() -> String {
let hours = self / 3600
let minutes = (self % 3600) / 60
let second = (self % 3600) % 60
let hoursString: String = {
let hs = String(hours)
return hs
}()
let minutesString: String = {
var ms = ""
if (minutes <= 9 && minutes >= 0) {
ms = "0\(minutes)"
} else{
ms = String(minutes)
}
return ms
}()
let secondsString: String = {
var ss = ""
if (second <= 9 && second >= 0) {
ss = "0\(second)"
} else{
ss = String(second)
}
return ss
}()
var label = ""
if hours == 0 {
label = minutesString + ":" + secondsString
} else{
label = hoursString + ":" + minutesString + ":" + secondsString
}
return label
}
}
enum stateOfVC {
case minimized
case fullScreen
case hidden
}
enum Direction {
case up
case left
case none
}
| mit | 84b0e5ff8de3a811c20aa2211487dc1b | 28.979167 | 82 | 0.577484 | 4.354009 | false | false | false | false |
TG908/iOS | Pods/Sweeft/Sources/Sweeft/Graphs/Graph.swift | 1 | 8602 | //
// Graph.swift
// Pods
//
// Created by Mathias Quintero on 2/22/17.
//
import Foundation
public class Graph<Node: GraphNode>: NodeProvider {
public typealias Identifier = Node.Identifier
let nodes: [Identifier : Node]
init(from nodes: [Node] = .empty) {
self.nodes = nodes >>= { ($0.identifier, $0) }
}
public func node(for identifier: Identifier) -> Node? {
return self.nodes[identifier]
}
}
struct QueueEntry<T: GraphNode>: Hashable {
public var hashValue: Int {
return item.identifier.hashValue
}
let item: T
public static func ==(lhs: QueueEntry<T>, rhs: QueueEntry<T>) -> Bool {
return lhs.item.identifier == rhs.item.identifier
}
}
extension Graph {
fileprivate func computePath<V>(using prevs: [V:V], until last: V) -> [V] {
if let prev = prevs[last] {
return [last] + computePath(using: prevs, until: prev)
} else {
return [last]
}
}
private func iterate(queue: PriorityQueue<QueueEntry<Node>, Double>,
prevs: [Identifier : Identifier],
costs: [Identifier : Double],
source: Identifier,
euristic: @escaping (Identifier) -> Double,
isFinal: @escaping (Identifier) -> Bool) -> ResultPromise<[Identifier]?> {
var costs = costs
var prevs = prevs
return .new { promise in
if let current = queue.pop()?.item {
if isFinal(current.identifier) {
promise.success(with: <>computePath(using: prevs, until: current.identifier))
} else {
let cost = costs[current.identifier].?
current.neighbours(in: self).onSuccess { neighbours in
neighbours => { item in
let entry = QueueEntry(item: item.0)
let estimate = cost + item.1 + euristic(item.0.identifier)
if let priority = queue.priority(for: entry) {
if estimate < priority {
queue.update(entry, with: estimate)
prevs[item.0.identifier] = current.identifier
costs[item.0.identifier] = cost + item.1
}
} else if prevs[item.0.identifier] == nil, source != item.0.identifier {
queue.add(entry, with: estimate)
prevs[item.0.identifier] = current.identifier
costs[item.0.identifier] = cost + item.1
}
}
self.iterate(queue: queue, prevs: prevs, costs: costs,
source: source, euristic: euristic, isFinal: isFinal).nest(to: promise, using: id)
}
.onError { _ in
self.iterate(queue: queue, prevs: prevs, costs: costs,
source: source, euristic: euristic, isFinal: isFinal).nest(to: promise, using: id)
}
}
} else {
promise.success(with: nil)
}
}
}
public func shortestPath(from source: Node,
with euristic: @escaping (Identifier) -> Double = **{ 0 },
until isFinal: @escaping (Identifier) -> Bool) -> ResultPromise<[Identifier]?> {
let queue = PriorityQueue<QueueEntry<Node>, Double>()
queue.add(QueueEntry(item: source), with: 0)
return iterate(queue: queue, prevs: .empty, costs: .empty,
source: source.identifier, euristic: euristic, isFinal: isFinal)
}
}
extension Graph {
private func iterate(queue: [Node],
parents: [Identifier:Identifier],
source: Identifier,
isFinal: @escaping (Identifier) -> Bool) -> ResultPromise<[Identifier]?> {
var parents = parents
var queue = queue
return .new { promise in
if !queue.isEmpty {
let current = queue.remove(at: 0)
current.neighbours(in: self).onSuccess { neighbours in
if let item = neighbours.filter({ $0.0.identifier } >>> isFinal).first {
parents[item.0.identifier] = current.identifier
promise.success(with: <>self.computePath(using: parents, until: item.0.identifier))
} else {
neighbours => { item in
if parents[item.0.identifier] == nil, source != item.0.identifier {
parents[item.0.identifier] = current.identifier
queue.append(item.0)
}
}
self.iterate(queue: queue, parents: parents,
source: source, isFinal: isFinal).nest(to: promise, using: id)
}
}
.onError { _ in
self.iterate(queue: queue, parents: parents,
source: source, isFinal: isFinal).nest(to: promise, using: id)
}
} else {
promise.success(with: nil)
}
}
}
public func bfs(from source: Node,
until isFinal: @escaping (Identifier) -> Bool) -> ResultPromise<[Identifier]?> {
if isFinal(source.identifier) {
return .successful(with: [source.identifier])
}
let queue = [source]
return iterate(queue: queue, parents: .empty, source: source.identifier, isFinal: isFinal)
}
}
extension Graph {
private func iterate(nodes: [Node],
parents: [Identifier:Identifier],
source: Identifier,
until isFinal: @escaping (Identifier) -> Bool) -> ResultPromise<([Identifier:Identifier],Identifier?)> {
var parents = parents
var nodes = nodes
return .new { promise in
if !nodes.isEmpty {
let current = nodes.remove(at: 0)
current.neighbours(in: self).onSuccess { neighbours in
if let item = neighbours.filter({ $0.0.identifier } >>> isFinal).first {
parents[item.0.identifier] = current.identifier
promise.success(with: (parents, item.0.identifier))
} else {
let neighbours = neighbours => { $0.0 } |> { parents[$0.identifier] == nil && source != $0.identifier }
neighbours => {
parents[$0.identifier] = current.identifier
}
self.iterate(nodes: neighbours, parents: parents, source: source, until: isFinal).onSuccess { result in
parents = result.0
if let result = result.1 {
promise.success(with: (parents, result))
} else {
self.iterate(nodes: nodes, parents: parents, source: source, until: isFinal).nest(to: promise, using: id)
}
}
}
}
.onError { _ in
self.iterate(nodes: nodes, parents: parents, source: source, until: isFinal)
}
} else {
promise.success(with: (parents, nil))
}
}
}
public func dfs(from source: Node,
until isFinal: @escaping (Identifier) -> Bool) -> ResultPromise<[Identifier]?> {
if isFinal(source.identifier) {
return .successful(with: [source.identifier])
}
let promise = iterate(nodes: [source], parents: .empty, source: source.identifier, until: isFinal)
return promise.nested { (prevs, item) -> [Identifier]? in
guard let item = item else {
return nil
}
return <>self.computePath(using: prevs, until: item)
}
}
}
| gpl-3.0 | ba87832987a1c516222a58c237b8922a | 38.640553 | 137 | 0.47582 | 5.030409 | false | false | false | false |
mansoor92/MaksabComponents | MaksabComponents/Classes/Rides/RideOptionsLinearView.swift | 1 | 2598 | //
// RideOptionsLinearView.swift
// Pods
//
// Created by Incubasys on 04/08/2017.
//
//
import UIKit
import StylingBoilerPlate
public class RideOptionsLinearView: UIView , CustomView, NibLoadableView{
static let height:CGFloat = 39
static public func createInstance(x: CGFloat, y: CGFloat, width:CGFloat) -> RideOptionsLinearView{
let inst = RideOptionsLinearView(frame: CGRect(x: x, y: y, width: width, height: RideOptionsLinearView.height))
return inst
}
let bundle = Bundle(for: RideOptionsLinearView.classForCoder())
@IBOutlet weak public var btnMehramRide: ToggleButton!
@IBOutlet weak public var btnPayment: ToggleButton!
@IBOutlet weak public var btnNoOfPassegners: ToggleButton!
var view: UIView!
override public required init(frame: CGRect) {
super.init(frame: frame)
view = commonInit(bundle: bundle)
configView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
view = commonInit(bundle: bundle)
configView()
}
func configView() {
btnMehramRide.selectedStateImage = UIImage.image(named: "mehram-selected")
btnMehramRide.unSelectedStateImage = UIImage.image(named: "mehram")
// btnNoSmoking.selectedStateImage = UIImage.image(named: "smoking")
// btnNoSmoking.unSelectedStateImage = UIImage.image(named: "no-smoking")
btnPayment.selectedStateImage = UIImage.image(named: "cash-circle")
btnPayment.unSelectedStateImage = UIImage.image(named: "cash-circle")
btnNoOfPassegners.selectedStateImage = UIImage.image(named: "passengers")
btnNoOfPassegners.unSelectedStateImage = UIImage.image(named: "passengers")
btnMehramRide.setTitle("", for: .normal)
// btnNoSmoking.setTitle("", for: .normal)
btnPayment.setTitle("", for: .normal)
btnNoOfPassegners.setTitle("", for: .normal)
}
//MARK:- Setters
public func config(isMehram: Bool, paymentIcon: UIImage?){
btnMehramRide.stateSelected = isMehram
setPayment(icon: paymentIcon)
btnNoOfPassegners.stateSelected = btnNoOfPassegners.stateSelected
}
//Payment
public func setPayment(icon: UIImage?){
btnPayment.setImage(icon?.withRenderingMode(.alwaysOriginal), for: .normal)
}
//MARK:- Getters
/*
public func getRideOptions() -> RideOptions {
guard rideOptions != nil else {
return RideOptions()
}
return rideOptions!
}*/
}
| mit | 705dbbe2942f07fa0d24e35cba9f21db | 30.301205 | 119 | 0.665127 | 4.091339 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Preferences Window/Preferences.swift | 1 | 9447 | //
// Preferences.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
protocol PreferencesItem: class {
var identifier: NSToolbarItem.Identifier { get }
var toolbarItem: NSToolbarItem { get }
var view: PreferencesView { get }
}
protocol PreferencesView: class {
var height: CGFloat { get }
}
class PreferencesWindowController: NSWindowController {
// MARK: -
// MARK: Variables
let toolbar = NSToolbar(identifier: "PreferencesWindowToolbar")
let toolbarItemIdentifiers: [NSToolbarItem.Identifier] = [.preferencesGeneral,
.preferencesLibrary,
.preferencesEditor,
.preferencesProfileDefaults,
.preferencesPayloads,
//.preferencesMDM,
.preferencesAdvanced,
NSToolbarItem.Identifier.flexibleSpace]
var preferencesGeneral: PreferencesGeneral?
var preferencesEditor: PreferencesEditor?
var preferencesLibrary: PreferencesLibrary?
var preferencesMDM: PreferencesMDM?
var preferencesProfileDefaults: PreferencesProfileDefaults?
var preferencesPayloads: PreferencesPayloads?
var preferencesAdvanced: PreferencesAdvanced?
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
// ---------------------------------------------------------------------
// Setup preferences window
// ---------------------------------------------------------------------
let rect = NSRect(x: 0, y: 0, width: kPreferencesWindowWidth, height: 200)
let styleMask = NSWindow.StyleMask(rawValue: (
NSWindow.StyleMask.titled.rawValue |
NSWindow.StyleMask.closable.rawValue |
NSWindow.StyleMask.miniaturizable.rawValue
))
let window = NSWindow(contentRect: rect,
styleMask: styleMask,
backing: NSWindow.BackingStoreType.buffered,
defer: false)
window.isReleasedWhenClosed = false
window.isRestorable = true
window.center()
// ---------------------------------------------------------------------
// Initialize self after the class variables have been instantiated
// ---------------------------------------------------------------------
super.init(window: window)
// ---------------------------------------------------------------------
// Setup toolbar
// ---------------------------------------------------------------------
self.toolbar.isVisible = true
self.toolbar.showsBaselineSeparator = true
self.toolbar.allowsUserCustomization = false
self.toolbar.autosavesConfiguration = false
self.toolbar.sizeMode = .regular
self.toolbar.displayMode = .iconAndLabel
self.toolbar.delegate = self
// ---------------------------------------------------------------------
// Add toolbar to window
// ---------------------------------------------------------------------
self.window?.toolbar = self.toolbar
// ---------------------------------------------------------------------
// Show "General" Preferences
// ---------------------------------------------------------------------
self.showPreferencesView(identifier: .preferencesGeneral)
}
// MARK: -
// MARK: Public Functions
@objc public func toolbarItemSelected(_ toolbarItem: NSToolbarItem) {
self.showPreferencesView(identifier: toolbarItem.itemIdentifier)
}
// MARK: -
// MARK: Private Functions
private func showPreferencesView(identifier: NSToolbarItem.Identifier) {
if let window = self.window, let preferencesItem = preferencesItem(identifier: identifier) {
// -----------------------------------------------------------------
// Update window title
// -----------------------------------------------------------------
window.title = preferencesItem.toolbarItem.label
// -----------------------------------------------------------------
// Remove current view and animate the transition to the new view
// -----------------------------------------------------------------
if let windowContentView = window.contentView {
windowContentView.removeFromSuperview()
// -----------------------------------------------------------------
// Get new view height and current window frame
// -----------------------------------------------------------------
let viewFrameHeight = preferencesItem.view.height
var windowFrame = window.frame
// -----------------------------------------------------------------
// Calculate new frame size
// -----------------------------------------------------------------
windowFrame.origin.y += (windowContentView.frame.size.height - viewFrameHeight)
windowFrame.size.height = ((windowFrame.size.height - windowContentView.frame.size.height) + viewFrameHeight)
// -----------------------------------------------------------------
// Update window frame with animation
// -----------------------------------------------------------------
window.setFrame(windowFrame, display: true, animate: true)
}
// -----------------------------------------------------------------
// Add then new view
// -----------------------------------------------------------------
// FIXME: view is already nsview, should fix this
if let view = preferencesItem.view as? NSView {
window.contentView = view
}
// -----------------------------------------------------------------
// Add constraint to set window width
// -----------------------------------------------------------------
NSLayoutConstraint.activate([NSLayoutConstraint(item: window.contentView ?? preferencesItem.view,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: kPreferencesWindowWidth) ])
}
}
private func preferencesItem(identifier: NSToolbarItem.Identifier) -> PreferencesItem? {
switch identifier {
case .preferencesGeneral:
if self.preferencesGeneral == nil { self.preferencesGeneral = PreferencesGeneral(sender: self) }
return self.preferencesGeneral
case .preferencesLibrary:
if self.preferencesLibrary == nil { self.preferencesLibrary = PreferencesLibrary(sender: self) }
return self.preferencesLibrary
case .preferencesMDM:
if self.preferencesMDM == nil { self.preferencesMDM = PreferencesMDM(sender: self) }
return self.preferencesMDM
case .preferencesEditor:
if self.preferencesEditor == nil { self.preferencesEditor = PreferencesEditor(sender: self) }
return self.preferencesEditor
case .preferencesProfileDefaults:
if self.preferencesProfileDefaults == nil { self.preferencesProfileDefaults = PreferencesProfileDefaults(sender: self) }
return self.preferencesProfileDefaults
case .preferencesPayloads:
if self.preferencesPayloads == nil { self.preferencesPayloads = PreferencesPayloads(sender: self) }
return self.preferencesPayloads
case .preferencesAdvanced:
if self.preferencesAdvanced == nil { self.preferencesAdvanced = PreferencesAdvanced(sender: self) }
return self.preferencesAdvanced
default:
return nil
}
}
}
// MARK: -
// MARK: NSToolbarDelegate
extension PreferencesWindowController: NSToolbarDelegate {
func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
self.toolbarItemIdentifiers
}
func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] {
self.toolbarItemIdentifiers
}
func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
if let preferencesItem = preferencesItem(identifier: itemIdentifier) {
return preferencesItem.toolbarItem
}
return nil
}
}
| mit | f4f0fb819f4d5217fda90da5baca1e1c | 44.413462 | 160 | 0.474381 | 6.844928 | false | false | false | false |
kaideyi/KDYSample | LeetCode/LeetCode/14_LongestCommonPrefix.swift | 1 | 822 | //
// 14_LongestCommonPrefix.swift
// LeetCode
//
// Created by Mac on 2018/4/16.
// Copyright © 2018年 Mac. All rights reserved.
//
import Foundation
class LongestCommonPrefix {
func longestCommonPrefix(_ strs: [String]) -> String {
guard strs.count > 0 else {
return ""
}
var res = [Character](strs[0])
for str in strs {
var strContent = [Character](str)
if res.count > strContent.count {
res = Array(res[0..<strContent.count])
}
for i in 0..<res.count {
if res[i] != strContent[i] {
res = Array(res[0..<i])
break
}
}
}
return String(res)
}
}
| mit | 5d1f0834ed3f734d892334bf49a452fc | 21.75 | 58 | 0.448107 | 4.427027 | false | false | false | false |
zisko/swift | stdlib/public/core/Hashable.swift | 1 | 5717 | //===----------------------------------------------------------------------===//
//
// 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 type that provides an integer hash value.
///
/// You can use any type that conforms to the `Hashable` protocol in a set or
/// as a dictionary key. Many types in the standard library conform to
/// `Hashable`: Strings, integers, floating-point and Boolean values, and even
/// sets provide a hash value by default. Your own custom types can be
/// hashable as well. When you define an enumeration without associated
/// values, it gains `Hashable` conformance automatically, and you can add
/// `Hashable` conformance to your other custom types by adding a single
/// `hashValue` property.
///
/// A hash value, provided by a type's `hashValue` property, is an integer that
/// is the same for any two instances that compare equally. That is, for two
/// instances `a` and `b` of the same type, if `a == b`, then
/// `a.hashValue == b.hashValue`. The reverse is not true: Two instances with
/// equal hash values are not necessarily equal to each other.
///
/// - Important: Hash values are not guaranteed to be equal across different
/// executions of your program. Do not save hash values to use in a future
/// execution.
///
/// Conforming to the Hashable Protocol
/// ===================================
///
/// To use your own custom type in a set or as the key type of a dictionary,
/// add `Hashable` conformance to your type. The `Hashable` protocol inherits
/// from the `Equatable` protocol, so you must also satisfy that protocol's
/// requirements.
///
/// A custom type's `Hashable` and `Equatable` requirements are automatically
/// synthesized by the compiler when you declare `Hashable` conformance in the
/// type's original declaration and your type meets these criteria:
///
/// - For a `struct`, all its stored properties must conform to `Hashable`.
/// - For an `enum`, all its associated values must conform to `Hashable`. (An
/// `enum` without associated values has `Hashable` conformance even without
/// the declaration.)
///
/// To customize your type's `Hashable` conformance, to adopt `Hashable` in a
/// type that doesn't meet the criteria listed above, or to extend an existing
/// type to conform to `Hashable`, implement the `hashValue` property in your
/// custom type. To ensure that your type meets the semantic requirements of
/// the `Hashable` and `Equatable` protocols, it's a good idea to also
/// customize your type's `Equatable` conformance to match.
///
/// As an example, consider a `GridPoint` type that describes a location in a
/// grid of buttons. Here's the initial declaration of the `GridPoint` type:
///
/// /// A point in an x-y coordinate system.
/// struct GridPoint {
/// var x: Int
/// var y: Int
/// }
///
/// You'd like to create a set of the grid points where a user has already
/// tapped. Because the `GridPoint` type is not hashable yet, it can't be used
/// as the `Element` type for a set. To add `Hashable` conformance, provide an
/// `==` operator function and a `hashValue` property.
///
/// extension GridPoint: Hashable {
/// var hashValue: Int {
/// return x.hashValue ^ y.hashValue &* 16777619
/// }
///
/// static func == (lhs: GridPoint, rhs: GridPoint) -> Bool {
/// return lhs.x == rhs.x && lhs.y == rhs.y
/// }
/// }
///
/// The `hashValue` property in this example combines the hash value of a grid
/// point's `x` property with the hash value of its `y` property multiplied by
/// a prime constant.
///
/// - Note: The above example above is a reasonably good hash function for a
/// simple type. If you're writing a hash function for a custom type, choose
/// a hashing algorithm that is appropriate for the kinds of data your type
/// comprises. Set and dictionary performance depends on hash values that
/// minimize collisions for their associated element and key types,
/// respectively.
///
/// Now that `GridPoint` conforms to the `Hashable` protocol, you can create a
/// set of previously tapped grid points.
///
/// var tappedPoints: Set = [GridPoint(x: 2, y: 3), GridPoint(x: 4, y: 1)]
/// let nextTap = GridPoint(x: 0, y: 1)
/// if tappedPoints.contains(nextTap) {
/// print("Already tapped at (\(nextTap.x), \(nextTap.y)).")
/// } else {
/// tappedPoints.insert(nextTap)
/// print("New tap detected at (\(nextTap.x), \(nextTap.y)).")
/// }
/// // Prints "New tap detected at (0, 1).")
public protocol Hashable : Equatable {
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
var hashValue: Int { get }
}
// Called by the SwiftValue implementation.
@_silgen_name("_swift_stdlib_Hashable_isEqual_indirect")
internal func Hashable_isEqual_indirect<T : Hashable>(
_ lhs: UnsafePointer<T>,
_ rhs: UnsafePointer<T>
) -> Bool {
return lhs.pointee == rhs.pointee
}
// Called by the SwiftValue implementation.
@_silgen_name("_swift_stdlib_Hashable_hashValue_indirect")
internal func Hashable_hashValue_indirect<T : Hashable>(
_ value: UnsafePointer<T>
) -> Int {
return value.pointee.hashValue
}
| apache-2.0 | bd4c04feab95350034098d91f749c038 | 43.317829 | 80 | 0.661711 | 4.148766 | false | false | false | false |
sketchytech/SwiftFiles | FilesPlayground.playground/Pages/BackgroundDownload.xcplaygroundpage/Contents.swift | 1 | 2554 | //: [Previous](@previous)
import Foundation
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let downloadURL = FileDirectory.applicationDirectory(.DocumentDirectory)
let newLocation = downloadURL!.URLByAppendingPathComponent("PDF/my.pdf")
class SessionDelegate:NSObject, NSURLSessionDownloadDelegate {
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
defer {
XCPlaygroundPage.currentPage.finishExecution()
}
try? FileDelete.deleteFile(newLocation.path!, directory: .DocumentDirectory, subdirectory: "PDF")
do {
try NSFileManager.defaultManager().moveItemAtURL(location, toURL: newLocation)
}
catch {
print("error")
}
NSFileManager.defaultManager().subpathsAtPath(downloadURL!.URLByAppendingPathComponent("PDF").path!)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
print("did write data: \(bytesWritten)")
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
print("did resume data")
}
}
if let downloadURL = FileDirectory.applicationDirectory(.DocumentDirectory) {
let newLocation = downloadURL.URLByAppendingPathComponent("PDF") //
NSFileManager.defaultManager().subpathsAtPath(downloadURL.URLByDeletingLastPathComponent!.path!)
try? NSFileManager.defaultManager().createDirectoryAtURL(newLocation, withIntermediateDirectories: true, attributes: nil)
do {
try FileHelper.createSubDirectory(newLocation.path!)
}
catch {
print("create error")
}
}
// create a background session configuration with identifier
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("myConfig")
if let url = NSURL(string: "http://partners.adobe.com/public/developer/en/xml/AdobeXMLFormsSamples.pdf") {
let delegate = SessionDelegate()
// create session by instantiating with configuration and delegate
let session = NSURLSession(configuration: config, delegate: delegate, delegateQueue: NSOperationQueue.mainQueue())
let downloadTask = session.downloadTaskWithURL(url)
downloadTask.resume()
}
//: [Next](@next)
| mit | f98fd8e87e5f18f18a7f5c57ef6db445 | 38.292308 | 178 | 0.726703 | 5.857798 | false | true | false | false |
MaddTheSane/pcsxr | macosx/Source/CheatObject.swift | 1 | 1791 | //
// CheatObject.swift
// Pcsxr
//
// Created by C.W. Betts on 11/10/14.
//
//
import Cocoa
import SwiftAdditions
func ==(rhs: CheatObject, lhs: CheatObject) -> Bool {
return rhs.cheatName == lhs.cheatName && rhs.values == lhs.values
}
class CheatObject: NSObject, SequenceType {
var cheatName: String
var values: [CheatValue]
var enabled: Bool
init(cheat: Cheat) {
cheatName = String(UTF8String: cheat.Descr)!
enabled = cheat.Enabled == 0 ? false : true
values = [CheatValue]()
for i in 0..<cheat.n {
let aCheat = CheatValue(cheatCode: CheatCodes[Int(i + cheat.First)])
values.append(aCheat)
}
super.init()
}
func addValuesObject(aVal: CheatValue) {
values.append(aVal)
}
func addValueObject(aVal: CheatValue) {
addValuesObject(aVal)
}
var countOfValues: Int {
return values.count
}
subscript(index: Int) -> CheatValue {
get {
return values[index]
}
set {
values[index] = newValue
}
}
func generate() -> IndexingGenerator<[CheatValue]> {
return values.generate()
}
init(name: String, enabled: Bool = false) {
cheatName = name
self.enabled = enabled
values = [CheatValue()]
super.init()
}
override convenience init() {
self.init(name: "")
}
override var hashValue: Int {
return cheatName.hashValue ^ values.count
}
override var hash: Int {
return self.hashValue
}
override func isEqual(object: AnyObject?) -> Bool {
if object == nil {
return false
}
if let unwrapped = object as? CheatObject {
return self == unwrapped
} else {
return false
}
}
override var description: String {
var valueString = ""
for aCheat in values {
valueString += aCheat.description + "\n"
}
return "[" + (enabled ? "*" : "") + cheatName + "]\n" + valueString
}
}
| gpl-3.0 | 816062777dc5cae046c9c1db7c1b2bde | 17.463918 | 71 | 0.6488 | 2.989983 | false | false | false | false |
KrishMunot/swift | stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift | 1 | 4334 | //===--- SwiftPrivatePthreadExtras.swift ----------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file contains wrappers for pthread APIs that are less painful to use
// than the C APIs.
//
//===----------------------------------------------------------------------===//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD)
import Glibc
#endif
/// An abstract base class to encapsulate the context necessary to invoke
/// a block from pthread_create.
internal class PthreadBlockContext {
/// Execute the block, and return an `UnsafeMutablePointer` to memory
/// allocated with `UnsafeMutablePointer.alloc` containing the result of the
/// block.
func run() -> UnsafeMutablePointer<Void> { fatalError("abstract") }
}
internal class PthreadBlockContextImpl<Argument, Result>: PthreadBlockContext {
let block: (Argument) -> Result
let arg: Argument
init(block: (Argument) -> Result, arg: Argument) {
self.block = block
self.arg = arg
super.init()
}
override func run() -> UnsafeMutablePointer<Void> {
let result = UnsafeMutablePointer<Result>(allocatingCapacity: 1)
result.initialize(with: block(arg))
return UnsafeMutablePointer(result)
}
}
/// Entry point for `pthread_create` that invokes a block context.
internal func invokeBlockContext(
_ contextAsVoidPointer: UnsafeMutablePointer<Void>
) -> UnsafeMutablePointer<Void> {
// The context is passed in +1; we're responsible for releasing it.
let contextAsOpaque = OpaquePointer(contextAsVoidPointer)
let context = Unmanaged<PthreadBlockContext>.fromOpaque(contextAsOpaque)
.takeRetainedValue()
return context.run()
}
/// Block-based wrapper for `pthread_create`.
public func _stdlib_pthread_create_block<Argument, Result>(
_ attr: UnsafePointer<pthread_attr_t>,
_ start_routine: (Argument) -> Result,
_ arg: Argument
) -> (CInt, pthread_t?) {
let context = PthreadBlockContextImpl(block: start_routine, arg: arg)
// We hand ownership off to `invokeBlockContext` through its void context
// argument.
let contextAsOpaque = OpaquePointer(bitPattern: Unmanaged.passRetained(context))
let contextAsVoidPointer = UnsafeMutablePointer<Void>(contextAsOpaque)
var threadID: pthread_t = _make_pthread_t()
let result = pthread_create(&threadID, attr,
invokeBlockContext, contextAsVoidPointer)
if result == 0 {
return (result, threadID)
} else {
return (result, nil)
}
}
internal func _make_pthread_t() -> pthread_t {
#if os(Linux)
return pthread_t()
#else
return nil
#endif
}
/// Block-based wrapper for `pthread_join`.
public func _stdlib_pthread_join<Result>(
_ thread: pthread_t,
_ resultType: Result.Type
) -> (CInt, Result?) {
var threadResultPtr: UnsafeMutablePointer<Void> = nil
let result = pthread_join(thread, &threadResultPtr)
if result == 0 {
let threadResult = UnsafeMutablePointer<Result>(threadResultPtr).pointee
threadResultPtr.deinitialize()
threadResultPtr.deallocateCapacity(1)
return (result, threadResult)
} else {
return (result, nil)
}
}
public class _stdlib_Barrier {
var _pthreadBarrier: _stdlib_pthread_barrier_t
var _pthreadBarrierPtr: UnsafeMutablePointer<_stdlib_pthread_barrier_t> {
return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self))
}
public init(threadCount: Int) {
self._pthreadBarrier = _stdlib_pthread_barrier_t()
let ret = _stdlib_pthread_barrier_init(
_pthreadBarrierPtr, nil, CUnsignedInt(threadCount))
if ret != 0 {
fatalError("_stdlib_pthread_barrier_init() failed")
}
}
deinit {
_stdlib_pthread_barrier_destroy(_pthreadBarrierPtr)
}
public func wait() {
let ret = _stdlib_pthread_barrier_wait(_pthreadBarrierPtr)
if !(ret == 0 || ret == _stdlib_PTHREAD_BARRIER_SERIAL_THREAD) {
fatalError("_stdlib_pthread_barrier_wait() failed")
}
}
}
| apache-2.0 | 7d9ff63877a8baf232c5e7581ef97770 | 31.103704 | 82 | 0.684356 | 4.236559 | false | false | false | false |
sol/aeson | tests/JSONTestSuite/parsers/test_Freddy_20161018/test_Freddy/JSON.swift | 14 | 3142 | //
// JSON.swift
// Freddy
//
// Created by Matthew D. Mathias on 3/17/15.
// Copyright © 2015 Big Nerd Ranch. Licensed under MIT.
//
/// An enum to describe the structure of JSON.
public enum JSON {
/// A case for denoting an array with an associated value of `[JSON]`
case array([JSON])
/// A case for denoting a dictionary with an associated value of `[Swift.String: JSON]`
case dictionary([String: JSON])
/// A case for denoting a double with an associated value of `Swift.Double`.
case double(Double)
/// A case for denoting an integer with an associated value of `Swift.Int`.
case int(Int)
/// A case for denoting a string with an associated value of `Swift.String`.
case string(String)
/// A case for denoting a boolean with an associated value of `Swift.Bool`.
case bool(Bool)
/// A case for denoting null.
case null
}
// MARK: - Errors
extension JSON {
/// An enum to encapsulate errors that may arise in working with `JSON`.
public enum Error: Swift.Error {
/// The `index` is out of bounds for a JSON array
case indexOutOfBounds(index: Int)
/// The `key` was not found in the JSON dictionary
case keyNotFound(key: String)
/// The JSON is not subscriptable with `type`
case unexpectedSubscript(type: JSONPathType.Type)
/// Unexpected JSON `value` was found that is not convertible `to` type
case valueNotConvertible(value: JSON, to: Any.Type)
/// The JSON is not serializable to a `String`.
case stringSerializationError
}
}
// MARK: - Test Equality
/// Return `true` if `lhs` is equal to `rhs`.
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs, rhs) {
case (.array(let arrL), .array(let arrR)):
return arrL == arrR
case (.dictionary(let dictL), .dictionary(let dictR)):
return dictL == dictR
case (.string(let strL), .string(let strR)):
return strL == strR
case (.double(let dubL), .double(let dubR)):
return dubL == dubR
case (.double(let dubL), .int(let intR)):
return dubL == Double(intR)
case (.int(let intL), .int(let intR)):
return intL == intR
case (.int(let intL), .double(let dubR)):
return Double(intL) == dubR
case (.bool(let bL), .bool(let bR)):
return bL == bR
case (.null, .null):
return true
default:
return false
}
}
extension JSON: Equatable {}
// MARK: - Printing
extension JSON: CustomStringConvertible {
/// A textual representation of `self`.
public var description: Swift.String {
switch self {
case .array(let arr): return String(describing: arr)
case .dictionary(let dict): return String(describing: dict)
case .string(let string): return string
case .double(let double): return String(describing: double)
case .int(let int): return String(describing: int)
case .bool(let bool): return String(describing: bool)
case .null: return "null"
}
}
}
| bsd-3-clause | 4f9f73bdafd8d42c74c33d4f234c2f83 | 31.05102 | 91 | 0.612544 | 3.941029 | false | false | false | false |
Mark-SS/LayerPlayer | LayerPlayer/CAScrollLayerViewController.swift | 2 | 1718 | //
// CAScrollLayerViewController.swift
// LayerPlayer
//
// Created by Scott Gardner on 11/10/14.
// Copyright (c) 2014 Scott Gardner. All rights reserved.
//
import UIKit
class CAScrollLayerViewController: UIViewController {
@IBOutlet weak var scrollingView: ScrollingView!
@IBOutlet weak var horizontalScrollingSwitch: UISwitch!
@IBOutlet weak var verticalScrollingSwitch: UISwitch!
var scrollingViewLayer: CAScrollLayer {
return scrollingView.layer as! CAScrollLayer
}
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
scrollingViewLayer.scrollMode = kCAScrollBoth
}
// MARK: - IBActions
@IBAction func panRecognized(sender: UIPanGestureRecognizer) {
var newPoint = scrollingView.bounds.origin
newPoint.x -= sender.translationInView(scrollingView).x
newPoint.y -= sender.translationInView(scrollingView).y
sender.setTranslation(CGPointZero, inView: scrollingView)
scrollingViewLayer.scrollToPoint(newPoint)
if sender.state == .Ended {
UIView.animateWithDuration(0.3, delay: 0, options: .CurveEaseInOut, animations: {
[unowned self] in
self.scrollingViewLayer.scrollToPoint(CGPointZero)
}, completion: nil)
}
}
@IBAction func scrollingSwitchChanged(sender: UISwitch) {
switch (horizontalScrollingSwitch.on, verticalScrollingSwitch.on) {
case (true, true):
scrollingViewLayer.scrollMode = kCAScrollBoth
case (true, false):
scrollingViewLayer.scrollMode = kCAScrollHorizontally
case (false, true):
scrollingViewLayer.scrollMode = kCAScrollVertically
default:
scrollingViewLayer.scrollMode = kCAScrollNone
}
}
}
| mit | 7d07e2f7a589de2c4b9fd98f68e1c44b | 28.62069 | 87 | 0.72468 | 4.439276 | false | false | false | false |
weareyipyip/SwiftStylable | Sources/SwiftStylable/Classes/Style/Stylers/SpacingStyler.swift | 1 | 1150 | //
// Spacing.swift
// SwiftStylable
//
// Created by Rens Wijnmalen on 07/04/2020.
//
import Foundation
class SpacingStyler: Styler {
private weak var _view: SpacingStylable?
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: Initializers
//
// -----------------------------------------------------------------------------------------------------------------------
init(_ view: SpacingStylable) {
self._view = view
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: Public methods
//
// -----------------------------------------------------------------------------------------------------------------------
open func applyStyle(_ style: Style) {
guard let view = self._view else {
return
}
if let spacing = style.spacingStyle.spacing {
view.spacing = spacing
}
if let imagePadding = style.spacingStyle.imagePadding {
view.imagePadding = imagePadding
}
}
}
| mit | 202526adfa0f611ce9a10e2ff7e23d15 | 23.468085 | 123 | 0.333913 | 5.927835 | false | false | false | false |
xwu/swift | test/AutoDiff/SILGen/differentiability_witness_generic_signature.swift | 5 | 9166 | // RUN: %target-swift-emit-silgen -verify -module-name main %s | %FileCheck %s
// RUN: %target-swift-emit-sil -verify -module-name main %s
// NOTE(SR-11950): SILParser crashes for SILGen round-trip.
// This file tests:
// - The "derivative generic signature" of `@differentiable` and `@derivative`
// attributes.
// - The generic signature of lowered SIL differentiability witnesses.
// Context:
// - For `@differentiable` attributes: the derivative generic signature is
// resolved from the original declaration's generic signature and additional
// `where` clause requirements.
// - For `@derivative` attributes: the derivative generic signature is the
// attributed declaration's generic signature.
import _Differentiation
//===----------------------------------------------------------------------===//
// Same-type requirements
//===----------------------------------------------------------------------===//
// Test original declaration with a generic signature and derivative generic
// signature where all generic parameters are concrete (i.e. bound to concrete
// types via same-type requirements).
struct AllConcrete<T>: Differentiable {}
extension AllConcrete {
// Original generic signature: `<T>`
// Derivative generic signature: `<T where T == Float>`
// Witness generic signature: `<T where T == Float>`
@_silgen_name("allconcrete_where_gensig_constrained")
@differentiable(reverse where T == Float)
func whereClauseGenericSignatureConstrained() -> AllConcrete {
return self
}
}
extension AllConcrete where T == Float {
@derivative(of: whereClauseGenericSignatureConstrained)
func jvpWhereClauseGenericSignatureConstrained() -> (
value: AllConcrete, differential: (TangentVector) -> TangentVector
) {
(whereClauseGenericSignatureConstrained(), { $0 })
}
}
// CHECK-LABEL: // differentiability witness for allconcrete_where_gensig_constrained
// CHECK-NEXT: sil_differentiability_witness hidden [reverse] [parameters 0] [results 0] <T where T == Float> @allconcrete_where_gensig_constrained : $@convention(method) <T> (AllConcrete<T>) -> AllConcrete<T> {
// CHECK-NEXT: jvp: @allconcrete_where_gensig_constrainedSfRszlTJfSpSr : $@convention(method) (AllConcrete<Float>) -> (AllConcrete<Float>, @owned @callee_guaranteed (AllConcrete<Float>.TangentVector) -> AllConcrete<Float>.TangentVector)
// CHECK-NEXT: }
// If a `@differentiable` or `@derivative` attribute satisfies two conditions:
// 1. The derivative generic signature is equal to the original generic signature.
// 2. The derivative generic signature has *all concrete* generic parameters.
//
// Then the attribute should be lowered to a SIL differentiability witness with
// *no* derivative generic signature.
extension AllConcrete where T == Float {
// Original generic signature: `<T where T == Float>`
// Derivative generic signature: `<T where T == Float>`
// Witness generic signature: none
@_silgen_name("allconcrete_original_gensig")
@differentiable(reverse)
func originalGenericSignature() -> AllConcrete {
return self
}
@derivative(of: originalGenericSignature)
func jvpOriginalGenericSignature() -> (
value: AllConcrete, differential: (TangentVector) -> TangentVector
) {
(originalGenericSignature(), { $0 })
}
// CHECK-LABEL: // differentiability witness for allconcrete_original_gensig
// CHECK-NEXT: sil_differentiability_witness hidden [reverse] [parameters 0] [results 0] @allconcrete_original_gensig : $@convention(method) (AllConcrete<Float>) -> AllConcrete<Float> {
// CHECK-NEXT: jvp: @allconcrete_original_gensigTJfSpSr : $@convention(method) (AllConcrete<Float>) -> (AllConcrete<Float>, @owned @callee_guaranteed (AllConcrete<Float>.TangentVector) -> AllConcrete<Float>.TangentVector)
// CHECK-NEXT: }
// Original generic signature: `<T where T == Float>`
// Derivative generic signature: `<T where T == Float>` (explicit `where` clause)
// Witness generic signature: none
@_silgen_name("allconcrete_where_gensig")
@differentiable(reverse where T == Float)
func whereClauseGenericSignature() -> AllConcrete {
return self
}
@derivative(of: whereClauseGenericSignature)
func jvpWhereClauseGenericSignature() -> (
value: AllConcrete, differential: (TangentVector) -> TangentVector
) {
(whereClauseGenericSignature(), { $0 })
}
// CHECK-LABEL: // differentiability witness for allconcrete_where_gensig
// CHECK-NEXT: sil_differentiability_witness hidden [reverse] [parameters 0] [results 0] @allconcrete_where_gensig : $@convention(method) (AllConcrete<Float>) -> AllConcrete<Float> {
// CHECK-NEXT: jvp: @allconcrete_where_gensigTJfSpSr : $@convention(method) (AllConcrete<Float>) -> (AllConcrete<Float>, @owned @callee_guaranteed (AllConcrete<Float>.TangentVector) -> AllConcrete<Float>.TangentVector)
// CHECK-NEXT: }
}
// Test original declaration with a generic signature and derivative generic
// signature where *not* all generic parameters are concrete.
// types via same-type requirements).
struct NotAllConcrete<T, U>: Differentiable {}
extension NotAllConcrete {
// Original generic signature: `<T, U>`
// Derivative generic signature: `<T, U where T == Float>`
// Witness generic signature: `<T, U where T == Float>` (not all concrete)
@_silgen_name("notallconcrete_where_gensig_constrained")
@differentiable(reverse where T == Float)
func whereClauseGenericSignatureConstrained() -> NotAllConcrete {
return self
}
}
extension NotAllConcrete where T == Float {
@derivative(of: whereClauseGenericSignatureConstrained)
func jvpWhereClauseGenericSignatureConstrained() -> (
value: NotAllConcrete, differential: (TangentVector) -> TangentVector
) {
(whereClauseGenericSignatureConstrained(), { $0 })
}
}
// CHECK-LABEL: // differentiability witness for notallconcrete_where_gensig_constrained
// CHECK-NEXT: sil_differentiability_witness hidden [reverse] [parameters 0] [results 0] <T, U where T == Float> @notallconcrete_where_gensig_constrained : $@convention(method) <T, U> (NotAllConcrete<T, U>) -> NotAllConcrete<T, U> {
// CHECK-NEXT: jvp: @notallconcrete_where_gensig_constrainedSfRszr0_lTJfSpSr : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 == Float> (NotAllConcrete<Float, τ_0_1>) -> (NotAllConcrete<Float, τ_0_1>, @owned @callee_guaranteed @substituted <τ_0_0, τ_0_1> (τ_0_0) -> τ_0_1 for <NotAllConcrete<Float, τ_0_1>.TangentVector, NotAllConcrete<Float, τ_0_1>.TangentVector>)
// CHECK-NEXT: }
extension NotAllConcrete where T == Float {
// Original generic signature: `<T, U where T == Float>`
// Derivative generic signature: `<T, U where T == Float>`
// Witness generic signature: `<T, U where T == Float>` (not all concrete)
@_silgen_name("notallconcrete_original_gensig")
@differentiable(reverse)
func originalGenericSignature() -> NotAllConcrete {
return self
}
@derivative(of: originalGenericSignature)
func jvpOriginalGenericSignature() -> (
value: NotAllConcrete, differential: (TangentVector) -> TangentVector
) {
(originalGenericSignature(), { $0 })
}
// CHECK-LABEL: // differentiability witness for notallconcrete_original_gensig
// CHECK-NEXT: sil_differentiability_witness hidden [reverse] [parameters 0] [results 0] <T, U where T == Float> @notallconcrete_original_gensig : $@convention(method) <T, U where T == Float> (NotAllConcrete<Float, U>) -> NotAllConcrete<Float, U> {
// CHECK-NEXT: jvp: @notallconcrete_original_gensigSfRszr0_lTJfSpSr : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 == Float> (NotAllConcrete<Float, τ_0_1>) -> (NotAllConcrete<Float, τ_0_1>, @owned @callee_guaranteed @substituted <τ_0_0, τ_0_1> (τ_0_0) -> τ_0_1 for <NotAllConcrete<Float, τ_0_1>.TangentVector, NotAllConcrete<Float, τ_0_1>.TangentVector>)
// CHECK-NEXT: }
// Original generic signature: `<T, U where T == Float>`
// Derivative generic signature: `<T, U where T == Float>` (explicit `where` clause)
// Witness generic signature: `<T, U where T == Float>` (not all concrete)
@_silgen_name("notallconcrete_where_gensig")
@differentiable(reverse where T == Float)
func whereClauseGenericSignature() -> NotAllConcrete {
return self
}
@derivative(of: whereClauseGenericSignature)
func jvpWhereClauseGenericSignature() -> (
value: NotAllConcrete, differential: (TangentVector) -> TangentVector
) {
(whereClauseGenericSignature(), { $0 })
}
// CHECK-LABEL: // differentiability witness for notallconcrete_where_gensig
// CHECK-NEXT: sil_differentiability_witness hidden [reverse] [parameters 0] [results 0] <T, U where T == Float> @notallconcrete_where_gensig : $@convention(method) <T, U where T == Float> (NotAllConcrete<Float, U>) -> NotAllConcrete<Float, U> {
// CHECK-NEXT: jvp: @notallconcrete_where_gensigSfRszr0_lTJfSpSr : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 == Float> (NotAllConcrete<Float, τ_0_1>) -> (NotAllConcrete<Float, τ_0_1>, @owned @callee_guaranteed @substituted <τ_0_0, τ_0_1> (τ_0_0) -> τ_0_1 for <NotAllConcrete<Float, τ_0_1>.TangentVector, NotAllConcrete<Float, τ_0_1>.TangentVector>)
// CHECK-NEXT: }
}
| apache-2.0 | 912ab2635ed04f69f36b00c00bb44c2a | 50.59887 | 367 | 0.710719 | 3.802248 | false | false | false | false |
mxclove/compass | 毕业设计_指南针最新3.2/毕业设计_指南针/TWHReachability.swift | 2 | 2727 | //
// TWHReachability.swift
// Reachability1
//
// Created by Lxrent27 on 15/10/2.
// Copyright © 2015年 Lxrent27. All rights reserved.
//
import Foundation
import SystemConfiguration
public enum IJReachabilityType {
case WWAN,
WiFi,
NotConnected
}
public class IJReachability {
/**
:see: Original post - http://www.chrisdanielson.com/2009/07/22/iphone-network-connectivity-test-example/
*/
public class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = (flags.rawValue & (UInt32)(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
public class func isConnectedToNetworkOfType() -> IJReachabilityType {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return .NotConnected
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let isWWAN = (flags.rawValue & SCNetworkReachabilityFlags.IsWWAN.rawValue)
!= 0
// let isWifI = (flags & UInt32(kSCNetworkReachabilityFlagsReachable)) != 0
if(isReachable && isWWAN){
return .WWAN
}
if(isReachable && !isWWAN){
return .WiFi
}
return .NotConnected
//let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
//return (isReachable && !needsConnection) ? true : false
}
} | apache-2.0 | a7c7738530e1138ddf63e5cd8020c63e | 34.855263 | 143 | 0.628488 | 4.517413 | false | false | false | false |
mattrajca/swift-corelibs-foundation | TestFoundation/TestNSURLRequest.swift | 4 | 12177 | // 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
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSURLRequest : XCTestCase {
static var allTests: [(String, (TestNSURLRequest) -> () throws -> Void)] {
return [
("test_construction", test_construction),
("test_mutableConstruction", test_mutableConstruction),
("test_headerFields", test_headerFields),
("test_copy", test_copy),
("test_mutableCopy_1", test_mutableCopy_1),
("test_mutableCopy_2", test_mutableCopy_2),
("test_mutableCopy_3", test_mutableCopy_3),
("test_NSCoding_1", test_NSCoding_1),
("test_NSCoding_2", test_NSCoding_2),
("test_NSCoding_3", test_NSCoding_3),
("test_methodNormalization", test_methodNormalization),
("test_description", test_description),
]
}
let url = URL(string: "http://swift.org")!
func test_construction() {
let request = NSURLRequest(url: url)
// Match OS X Foundation responses
XCTAssertNotNil(request)
XCTAssertEqual(request.url, url)
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertNil(request.allHTTPHeaderFields)
XCTAssertNil(request.mainDocumentURL)
}
func test_mutableConstruction() {
let url = URL(string: "http://swift.org")!
let request = NSMutableURLRequest(url: url)
//Confirm initial state matches NSURLRequest responses
XCTAssertNotNil(request)
XCTAssertEqual(request.url, url)
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertNil(request.allHTTPHeaderFields)
XCTAssertNil(request.mainDocumentURL)
request.mainDocumentURL = url
XCTAssertEqual(request.mainDocumentURL, url)
request.httpMethod = "POST"
XCTAssertEqual(request.httpMethod, "POST")
let newURL = URL(string: "http://github.com")!
request.url = newURL
XCTAssertEqual(request.url, newURL)
}
func test_headerFields() {
let request = NSMutableURLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Accept")
XCTAssertNotNil(request.allHTTPHeaderFields)
XCTAssertEqual(request.allHTTPHeaderFields?["Accept"], "application/json")
// Setting "accept" should remove "Accept"
request.setValue("application/xml", forHTTPHeaderField: "accept")
XCTAssertNil(request.allHTTPHeaderFields?["Accept"])
XCTAssertEqual(request.allHTTPHeaderFields?["accept"], "application/xml")
// Adding to "Accept" should add to "accept"
request.addValue("text/html", forHTTPHeaderField: "Accept")
XCTAssertEqual(request.allHTTPHeaderFields?["accept"], "application/xml,text/html")
}
func test_copy() {
let mutableRequest = NSMutableURLRequest(url: url)
let urlA = URL(string: "http://swift.org")!
let urlB = URL(string: "http://github.com")!
mutableRequest.mainDocumentURL = urlA
mutableRequest.url = urlB
mutableRequest.httpMethod = "POST"
mutableRequest.setValue("application/json", forHTTPHeaderField: "Accept")
guard let requestCopy1 = mutableRequest.copy() as? NSURLRequest else {
XCTFail(); return
}
// Check that all attributes are copied and that the original ones are
// unchanged:
XCTAssertEqual(mutableRequest.mainDocumentURL, urlA)
XCTAssertEqual(requestCopy1.mainDocumentURL, urlA)
XCTAssertEqual(mutableRequest.httpMethod, "POST")
XCTAssertEqual(requestCopy1.httpMethod, "POST")
XCTAssertEqual(mutableRequest.url, urlB)
XCTAssertEqual(requestCopy1.url, urlB)
XCTAssertEqual(mutableRequest.allHTTPHeaderFields?["Accept"], "application/json")
XCTAssertEqual(requestCopy1.allHTTPHeaderFields?["Accept"], "application/json")
// Change the original, and check that the copy has unchanged
// values:
let urlC = URL(string: "http://apple.com")!
let urlD = URL(string: "http://ibm.com")!
mutableRequest.mainDocumentURL = urlC
mutableRequest.url = urlD
mutableRequest.httpMethod = "HEAD"
mutableRequest.addValue("text/html", forHTTPHeaderField: "Accept")
XCTAssertEqual(requestCopy1.mainDocumentURL, urlA)
XCTAssertEqual(requestCopy1.httpMethod, "POST")
XCTAssertEqual(requestCopy1.url, urlB)
XCTAssertEqual(requestCopy1.allHTTPHeaderFields?["Accept"], "application/json")
// Check that we can copy the copy:
guard let requestCopy2 = requestCopy1.copy() as? NSURLRequest else {
XCTFail(); return
}
XCTAssertEqual(requestCopy2.mainDocumentURL, urlA)
XCTAssertEqual(requestCopy2.httpMethod, "POST")
XCTAssertEqual(requestCopy2.url, urlB)
XCTAssertEqual(requestCopy2.allHTTPHeaderFields?["Accept"], "application/json")
}
func test_mutableCopy_1() {
let originalRequest = NSMutableURLRequest(url: url)
let urlA = URL(string: "http://swift.org")!
let urlB = URL(string: "http://github.com")!
originalRequest.mainDocumentURL = urlA
originalRequest.url = urlB
originalRequest.httpMethod = "POST"
originalRequest.setValue("application/json", forHTTPHeaderField: "Accept")
guard let requestCopy = originalRequest.mutableCopy() as? NSMutableURLRequest else {
XCTFail(); return
}
// Change the original, and check that the copy has unchanged values:
let urlC = URL(string: "http://apple.com")!
let urlD = URL(string: "http://ibm.com")!
originalRequest.mainDocumentURL = urlC
originalRequest.url = urlD
originalRequest.httpMethod = "HEAD"
originalRequest.addValue("text/html", forHTTPHeaderField: "Accept")
XCTAssertEqual(requestCopy.mainDocumentURL, urlA)
XCTAssertEqual(requestCopy.httpMethod, "POST")
XCTAssertEqual(requestCopy.url, urlB)
XCTAssertEqual(requestCopy.allHTTPHeaderFields?["Accept"], "application/json")
}
func test_mutableCopy_2() {
let originalRequest = NSMutableURLRequest(url: url)
let urlA = URL(string: "http://swift.org")!
let urlB = URL(string: "http://github.com")!
originalRequest.mainDocumentURL = urlA
originalRequest.url = urlB
originalRequest.httpMethod = "POST"
originalRequest.setValue("application/json", forHTTPHeaderField: "Accept")
guard let requestCopy = originalRequest.mutableCopy() as? NSMutableURLRequest else {
XCTFail(); return
}
// Change the copy, and check that the original has unchanged values:
let urlC = URL(string: "http://apple.com")!
let urlD = URL(string: "http://ibm.com")!
requestCopy.mainDocumentURL = urlC
requestCopy.url = urlD
requestCopy.httpMethod = "HEAD"
requestCopy.addValue("text/html", forHTTPHeaderField: "Accept")
XCTAssertEqual(originalRequest.mainDocumentURL, urlA)
XCTAssertEqual(originalRequest.httpMethod, "POST")
XCTAssertEqual(originalRequest.url, urlB)
XCTAssertEqual(originalRequest.allHTTPHeaderFields?["Accept"], "application/json")
}
func test_mutableCopy_3() {
let urlA = URL(string: "http://swift.org")!
let originalRequest = NSURLRequest(url: urlA)
guard let requestCopy = originalRequest.mutableCopy() as? NSMutableURLRequest else {
XCTFail(); return
}
// Change the copy, and check that the original has unchanged values:
let urlC = URL(string: "http://apple.com")!
let urlD = URL(string: "http://ibm.com")!
requestCopy.mainDocumentURL = urlC
requestCopy.url = urlD
requestCopy.httpMethod = "HEAD"
requestCopy.addValue("text/html", forHTTPHeaderField: "Accept")
XCTAssertNil(originalRequest.mainDocumentURL)
XCTAssertEqual(originalRequest.httpMethod, "GET")
XCTAssertEqual(originalRequest.url, urlA)
XCTAssertNil(originalRequest.allHTTPHeaderFields)
}
func test_NSCoding_1() {
let url = URL(string: "https://apple.com")!
let requestA = NSURLRequest(url: url)
let requestB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: requestA)) as! NSURLRequest
XCTAssertEqual(requestA, requestB, "Archived then unarchived url request must be equal.")
}
func test_NSCoding_2() {
let url = URL(string: "https://apple.com")!
let requestA = NSMutableURLRequest(url: url)
//Also checks crash on NSData.bytes
requestA.httpBody = Data()
let requestB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: requestA)) as! NSURLRequest
XCTAssertEqual(requestA, requestB, "Archived then unarchived url request must be equal.")
//Check `.httpBody` as it is not checked in `isEqual(_:)`
XCTAssertEqual(requestB.httpBody, requestA.httpBody)
}
func test_NSCoding_3() {
let url = URL(string: "https://apple.com")!
let urlForDocument = URL(string: "http://ibm.com")!
let requestA = NSMutableURLRequest(url: url)
requestA.mainDocumentURL = urlForDocument
//Also checks crash on NSData.bytes
requestA.httpBody = Data(bytes: [1, 2, 3])
let requestB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: requestA)) as! NSURLRequest
XCTAssertEqual(requestA, requestB, "Archived then unarchived url request must be equal.")
//Check `.httpBody` as it is not checked in `isEqual(_:)`
XCTAssertNotNil(requestB.httpBody)
XCTAssertEqual(3, requestB.httpBody!.count)
XCTAssertEqual(requestB.httpBody, requestA.httpBody)
}
func test_methodNormalization() {
let expectedNormalizations = [
"GET": "GET",
"get": "GET",
"gEt": "GET",
"HEAD": "HEAD",
"hEAD": "HEAD",
"head": "HEAD",
"HEAd": "HEAD",
"POST": "POST",
"post": "POST",
"pOST": "POST",
"POSt": "POST",
"PUT": "PUT",
"put": "PUT",
"PUt": "PUT",
"DELETE": "DELETE",
"delete": "DELETE",
"DeleTE": "DELETE",
"dELETe": "DELETE",
"CONNECT": "CONNECT",
"connect": "CONNECT",
"Connect": "CONNECT",
"cOnNeCt": "CONNECT",
"OPTIONS": "OPTIONS",
"options": "options",
"TRACE": "TRACE",
"trace": "trace",
"PATCH": "PATCH",
"patch": "patch",
"foo": "foo",
"BAR": "BAR",
]
let request = NSMutableURLRequest(url: url)
for n in expectedNormalizations {
request.httpMethod = n.key
XCTAssertEqual(request.httpMethod, n.value)
}
}
func test_description() {
let url = URL(string: "http://swift.org")!
let request = NSMutableURLRequest(url: url)
if request.description.range(of: "http://swift.org") == nil {
XCTFail("description should contain URL")
}
request.url = nil
if request.description.range(of: "(null)") == nil {
XCTFail("description of nil URL should contain (null)")
}
}
}
| apache-2.0 | 460485408ff10a9f8e7c84c04ef574fc | 39.45515 | 135 | 0.625113 | 4.933955 | false | true | false | false |
safarijv/Download-Indicator | RMDownloadIndicator-Swift/RMDownloadIndicator-Swift/RMDownloadIndicator.swift | 2 | 10019 | //
// RMDownloadIndicator.swift
// RMDownloadIndicator-Swift
//
// Created by Mahesh Shanbhag on 10/08/15.
// Copyright (c) 2015 Mahesh Shanbhag. All rights reserved.
//
import UIKit
enum RMIndicatorType: Int {
case kRMClosedIndicator = 0
case kRMFilledIndicator
case kRMMixedIndictor
}
class RMDownloadIndicator: UIView {
// this value should be 0 to 0.5 (default: (kRMFilledIndicator = 0.5), (kRMMixedIndictor = 0.4))
var radiusPercent: CGFloat = 0.5 {
didSet {
if type == RMIndicatorType.kRMClosedIndicator {
self.radiusPercent = 0.5
}
if radiusPercent > 0.5 || radiusPercent < 0 {
radiusPercent = oldValue
}
}
}
// used to fill the downloaded percent slice (default: (kRMFilledIndicator = white), (kRMMixedIndictor = white))
var fillColor: UIColor = UIColor.clearColor() {
didSet {
if type == RMIndicatorType.kRMClosedIndicator {
fillColor = UIColor.clearColor()
}
}
}
// used to stroke the covering slice (default: (kRMClosedIndicator = white), (kRMMixedIndictor = white))
var strokeColor: UIColor = UIColor.whiteColor()
// used to stroke the background path the covering slice (default: (kRMClosedIndicator = gray))
var closedIndicatorBackgroundStrokeColor: UIColor = UIColor.whiteColor()
// Private properties
private var paths: [CGPath] = []
private var indicateShapeLayer: CAShapeLayer!
private var coverLayer: CAShapeLayer!
private var animatingLayer: CAShapeLayer!
private var type: RMIndicatorType!
private var coverWidth: CGFloat = 0.0
private var lastUpdatedPath: UIBezierPath!
private var lastSourceAngle: CGFloat = 0.0
private var animationDuration: CGFloat = 0.0
// init with frame and type
// if() - (id)initWithFrame:(CGRect)frame is used the default type = kRMFilledIndicator
override init(frame:CGRect) {
super.init(frame:frame)
self.type = .kRMFilledIndicator
self.initAttributes()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(rectframe: CGRect, type: RMIndicatorType) {
super.init(frame: rectframe)
self.type = type
self.initAttributes()
}
func initAttributes() {
if type == RMIndicatorType.kRMClosedIndicator {
self.radiusPercent = 0.5
coverLayer = CAShapeLayer()
animatingLayer = coverLayer
fillColor = UIColor.clearColor()
strokeColor = UIColor.whiteColor()
closedIndicatorBackgroundStrokeColor = UIColor.grayColor()
coverWidth = 2.0
}
else {
if type == RMIndicatorType.kRMFilledIndicator {
indicateShapeLayer = CAShapeLayer()
animatingLayer = indicateShapeLayer
radiusPercent = 0.5
coverWidth = 2.0
closedIndicatorBackgroundStrokeColor = UIColor.clearColor()
}
else {
indicateShapeLayer = CAShapeLayer()
coverLayer = CAShapeLayer()
animatingLayer = indicateShapeLayer
coverWidth = 2.0
radiusPercent = 0.4
closedIndicatorBackgroundStrokeColor = UIColor.whiteColor()
}
fillColor = UIColor.whiteColor()
strokeColor = UIColor.whiteColor()
}
animatingLayer.frame = self.bounds
self.layer.addSublayer(animatingLayer)
animationDuration = 0.5
}
// prepare the download indicator
func loadIndicator() {
let center: CGPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2)
let initialPath: UIBezierPath = UIBezierPath.init()
if type == RMIndicatorType.kRMClosedIndicator {
initialPath.addArcWithCenter(center, radius: (fmin(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds))), startAngle: degreeToRadian(-90), endAngle: degreeToRadian(-90), clockwise: true)
}
else {
if type == RMIndicatorType.kRMMixedIndictor {
self.setNeedsDisplay()
}
let radius: CGFloat = (fmin(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) / 2) * self.radiusPercent
initialPath.addArcWithCenter(center, radius: radius, startAngle: degreeToRadian(-90), endAngle: degreeToRadian(-90), clockwise: true)
}
animatingLayer.path = initialPath.CGPath
animatingLayer.strokeColor = strokeColor.CGColor
animatingLayer.fillColor = fillColor.CGColor
animatingLayer.lineWidth = coverWidth
self.lastSourceAngle = degreeToRadian(-90)
}
func keyframePathsWithDuration(duration: CGFloat, lastUpdatedAngle: CGFloat, newAngle: CGFloat, radius: CGFloat, type: RMIndicatorType) -> [CGPath] {
let frameCount: Int = Int(ceil(duration * 60))
var array: [CGPath] = []
for var frame = 0; frame <= frameCount; frame++ {
let startAngle = degreeToRadian(-90)
let angleChange = ((newAngle - lastUpdatedAngle) * CGFloat(frame))
let endAngle = lastUpdatedAngle + (angleChange / CGFloat(frameCount))
array.append((self.pathWithStartAngle(startAngle, endAngle: endAngle, radius: radius, type: type).CGPath))
}
return array
}
func pathWithStartAngle(startAngle: CGFloat, endAngle: CGFloat, radius: CGFloat, type: RMIndicatorType) -> UIBezierPath {
let clockwise: Bool = startAngle < endAngle
let path: UIBezierPath = UIBezierPath()
let center: CGPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2)
if type == RMIndicatorType.kRMClosedIndicator {
path.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
}
else {
path.moveToPoint(center)
path.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
path.closePath()
}
return path
}
override func drawRect(rect: CGRect) {
if type == RMIndicatorType.kRMMixedIndictor {
let radius: CGFloat = fmin(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) / 2 - self.coverWidth
let center: CGPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2)
let coverPath: UIBezierPath = UIBezierPath()
coverPath.lineWidth = coverWidth
coverPath.addArcWithCenter(center, radius: radius, startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true)
closedIndicatorBackgroundStrokeColor.set()
coverPath.stroke()
}
else {
if type == RMIndicatorType.kRMClosedIndicator {
let radius: CGFloat = (fmin(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) / 2) - self.coverWidth
let center: CGPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2)
let coverPath: UIBezierPath = UIBezierPath()
coverPath.lineWidth = coverWidth
coverPath.addArcWithCenter(center, radius: radius, startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true)
closedIndicatorBackgroundStrokeColor.set()
coverPath.lineWidth = self.coverWidth
coverPath.stroke()
}
}
}
// update the downloadIndicator
func updateWithTotalBytes(bytes: CGFloat, downloadedBytes: CGFloat) {
lastUpdatedPath = UIBezierPath.init(CGPath: animatingLayer.path!)
paths.removeAll(keepCapacity: false)
let destinationAngle: CGFloat = self.destinationAngleForRatio((downloadedBytes / bytes))
let radius: CGFloat = (fmin(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) * radiusPercent) - self.coverWidth
paths = self.keyframePathsWithDuration(self.animationDuration, lastUpdatedAngle: self.lastSourceAngle, newAngle: destinationAngle, radius: radius, type: type)
animatingLayer.path = paths[(paths.count - 1)]
self.lastSourceAngle = destinationAngle
let pathAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "path")
pathAnimation.values = paths
pathAnimation.duration = CFTimeInterval(animationDuration)
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
pathAnimation.removedOnCompletion = true
animatingLayer.addAnimation(pathAnimation, forKey: "path")
if downloadedBytes >= bytes{
self.removeFromSuperview()
}
}
func destinationAngleForRatio(ratio: CGFloat) -> CGFloat {
return (degreeToRadian((360 * ratio) - 90))
}
func degreeToRadian(degree: CGFloat) -> CGFloat
{
return (CGFloat(degree) * CGFloat(M_PI)) / CGFloat(180.0);
}
//
// func setLayerFillColor(fillColor: UIColor) {
// if type == RMIndicatorType.kRMClosedIndicator {
// self.fillColor = UIColor.clearColor()
// }
// else {
// self.fillColor = fillColor
// }
// }
// func setLayerRadiusPercent(radiusPercent: CGFloat) {
// if type == RMIndicatorType.kRMClosedIndicator {
// self.radiusPercent = 0.5
// return
// }
// if radiusPercent > 0.5 || radiusPercent < 0 {
// return
// }
// else {
// self.radiusPercent = radiusPercent
// }
// }
// update the downloadIndicator
func setIndicatorAnimationDuration(duration: CGFloat) {
self.animationDuration = duration
}
}
| mit | a1705785d4082e6924ebf00763e1bd59 | 40.061475 | 204 | 0.632199 | 4.712606 | false | false | false | false |
kkolli/MathGame | client/Speedy/BoardController.swift | 1 | 20910 | //
// BoardController.swift
// Speedy
//
// Created by Tyler Levine on 2/12/15.
// Copyright (c) 2015 Krishna Kolli. All rights reserved.
//
import SpriteKit
enum BoardMode {
case SINGLE
case MULTI
}
class BoardController {
// defines board element positioning, in relative percents
struct BoardConstraints {
let header_height: CGFloat = 0.15
let long_col_vert_padding: CGFloat = 0.10
let short_col_vert_padding: CGFloat = 0.15
let col_horiz_padding: CGFloat = 0.15
}
let constraints = BoardConstraints()
// this is the number of NumberCircles in the long columns (# of numbers)
let longColNodes = 5
// this is the number of NumberCircles in the short columns (# of operators)
let shortColNodes = 4
// color to draw debug lines
let debugColor = UIColor.yellowColor()
let bgColor = SKColor.whiteColor()
let scene: GameScene
let frame: CGRect
let debug: Bool
let randomNumbers = RandomNumbers()
let randomOperators = RandomOperators()
//var circleList: [GameCircle] = []
var nodeRestPositions = [CGPoint]()
var gameCircles = [GameCircle?]()
let headerController: BoardHeaderController?
let mode: BoardMode?
var targetNumber: Int?
var score = 0
var operatorsUsed: [Operator]!
var notifyScoreChanged: (() -> ())!
init(mode m: BoardMode, scene s: GameScene, debug d: Bool) {
scene = s
frame = scene.frame
debug = d
mode = m;
if debug {
drawDebugLines()
//addDebugPhysBodies()
}
setUpScenePhysics()
setupBoard()
headerController = BoardHeaderController(mode: m, scene: s, frame: createHeaderFrame(), board: self)
addGameCircles()
operatorsUsed = []
}
func setTimeInHeader(time: Int) {
headerController?.setTimeRemaining(time)
}
func setOpponentScore(score: Int) {
println("SETTING OPPONENT SCORE")
headerController!.setOpponentScore(score)
}
func setOpponentName(opponent: String) {
headerController!.setOpponentName(opponent)
}
convenience init(scene: GameScene, mode: BoardMode) {
self.init(mode: mode, scene: scene, debug: false)
}
private func setupBoard() {
generateNewTargetNumber()
setupLongColFieldNodes()
setupShortColFieldNodes()
}
private func createHeaderFrame() -> CGRect {
let x = frame.origin.x
let y = frame.origin.y + frame.height * (1 - constraints.header_height)
let width = frame.width
let height = frame.height * constraints.header_height
return CGRect(x: x, y: y, width: width, height: height)
}
func handleMerge(leftNumberCircle: NumberCircle, rightNumberCircle: NumberCircle, opCircle: OperatorCircle) {
println("HANDLING MERGE...")
var result: Int
var nodeScore: Int
let op1 = leftNumberCircle.number!
let op2 = rightNumberCircle.number!
let oper = opCircle.op!
switch oper{
case .PLUS:
result = op1 + op2
case .MINUS:
result = op1 - op2
case .MULTIPLY:
result = op1 * op2
case .DIVIDE:
result = op1 / op2
}
nodeScore = leftNumberCircle.getScore() + rightNumberCircle.getScore() * ScoreMultiplier.getMultiplierFactor(oper)
nodeRemoved(leftNumberCircle.boardPos!)
nodeRemoved(opCircle.boardPos!)
// clear phys bodies so we don't get weird physics glitches
leftNumberCircle.physicsBody = nil
opCircle.physicsBody = nil
let mergeAction = actionAnimateNodeMerge(rightNumberCircle)
let removeAction = SKAction.runBlock {
leftNumberCircle.removeFromParent()
opCircle.removeFromParent()
}
let sequence = SKAction.sequence([mergeAction, removeAction])
leftNumberCircle.runAction(sequence)
opCircle.runAction(sequence)
if result == targetNumber {
println("TARGET NUMBER MATCHED: \(result)")
// update the score, update the target number, and notify changed
targetNumberMatched(nodeScore)
rightNumberCircle.physicsBody = nil
let waitAction = SKAction.waitForDuration(NSTimeInterval(sequence.duration + 0.1))
let scoreAction = actionAnimateNodeToScore(rightNumberCircle)
let removeAction = SKAction.runBlock {
rightNumberCircle.removeFromParent()
}
let sequence = SKAction.sequence([waitAction, scoreAction, removeAction])
rightNumberCircle.runAction(sequence)
nodeRemoved(rightNumberCircle.boardPos!)
}else if result == 0 {
let waitAction = SKAction.waitForDuration(NSTimeInterval(sequence.duration + 0.1))
let disappearAction = actionAnimateNodeDisappear(rightNumberCircle)
let removeAction = SKAction.runBlock {
rightNumberCircle.removeFromParent()
}
let sequence = SKAction.sequence([waitAction, disappearAction, removeAction])
rightNumberCircle.runAction(sequence)
rightNumberCircle.setNumber(result)
nodeRemoved(rightNumberCircle.boardPos!)
}
else {
rightNumberCircle.setScore(nodeScore)
rightNumberCircle.setNumber(result)
rightNumberCircle.neighbor = nil
}
operatorsUsed!.append(oper)
replaceMissingNodes()
}
func actionAnimateNodeToScore(node: SKNode) -> SKAction {
var targetPos = headerController!.getScorePosition()
targetPos.y = targetPos.y + frame.height * (1 - constraints.header_height)
let moveAction = SKAction.moveTo(targetPos, duration: NSTimeInterval(0.4))
let scaleAction = SKAction.scaleTo(0.0, duration: NSTimeInterval(0.4))
let actionGroup = SKAction.group([moveAction, scaleAction])
return actionGroup
}
func actionAnimateNodeMerge(nodeTarget: SKNode) -> SKAction {
let targetPos = nodeTarget.position
let moveAction = SKAction.moveTo(targetPos, duration: NSTimeInterval(0.2))
let scaleAction = SKAction.scaleTo(0.0, duration: NSTimeInterval(0.15))
let actionGroup = SKAction.group([moveAction, scaleAction])
return actionGroup
}
func actionAnimateNodeDisappear(node: SKNode) -> SKAction {
return SKAction.scaleTo(0.0, duration: NSTimeInterval(0.2))
}
func targetNumberMatched(nodeScore: Int) {
score += nodeScore
headerController!.setScore(score)
generateNewTargetNumber()
notifyScoreChanged()
}
func generateNewTargetNumber(){
if targetNumber != nil{
let numberList = gameCircles.filter{$0 is NumberCircle}.map{($0 as NumberCircle).number!}
targetNumber = randomNumbers.generateTarget(numberList)
}else{
targetNumber = randomNumbers.generateTarget()
}
headerController?.setTargetNumber(targetNumber!)
//GameTargetNumLabel.text = String(targetNumber!)
}
func setUpScenePhysics() {
scene.physicsWorld.gravity = CGVectorMake(0, 0)
scene.physicsBody = createScenePhysBody()
scene.setGameFrame(getGameBoardRect())
}
private func createScenePhysBody() -> SKPhysicsBody {
// we put contraints on the top, left, right, bottom so that our balls can bounce off them
let physicsBody = SKPhysicsBody(edgeLoopFromRect: getGameBoardRect())
physicsBody.dynamic = false
physicsBody.categoryBitMask = 0xFFFFFFFF
physicsBody.restitution = 0.1
physicsBody.friction = 0.0
return physicsBody
}
private func getGameBoardRect() -> CGRect {
let origin = scene.frame.origin
let width = scene.frame.width
let height = scene.frame.height * (1 - constraints.header_height)
return CGRectMake(origin.x, origin.y, width, height)
}
private func drawHeaderLine() {
let x = 0
let y = frame.height - frame.height * constraints.header_height
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0, y)
CGPathAddLineToPoint(path, nil, frame.width, y)
let node = SKShapeNode(path: path)
node.strokeColor = debugColor
scene.addChild(node)
}
func nodeRemoved(pos: Int) {
gameCircles[pos] = nil
}
func upgradeCircle(){
let shouldUpgrade = Int(arc4random_uniform(10) + 1)
if shouldUpgrade == 1{
let upgradeOption = UpgradeOptions(rawValue: Int(arc4random_uniform(2)))
let numberCircles = gameCircles.filter{$0 is NumberCircle}
let upgradedCircles = numberCircles.filter{($0 as NumberCircle).upgrade != .None}
let unUpgradedCircles = numberCircles.filter{($0 as NumberCircle).upgrade == .None}
if upgradeOption != .None && upgradedCircles.count < 2{
let index = Int(arc4random_uniform(UInt32(unUpgradedCircles.count)))
var nodeToUpgrade = unUpgradedCircles[index] as NumberCircle
if nodeToUpgrade !== scene.getActiveNode() {
nodeToUpgrade.setUpgrade(upgradeOption!)
nodeToUpgrade.setFillColor(upgradeOption!.upgradeColor())
}
}
}
}
func replaceMissingNodes() {
func topColIdx(idx: Int) -> Int {
if idx < 2 * longColNodes {
// in a long column
return idx % 2
} else {
// in the short column
return 2 * longColNodes
}
}
// move existing long column nodes down as far as possible
for (var i = 2 * longColNodes - 1; i > 1; i--) {
if gameCircles[i] != nil {
continue
}
for (var j = i - 2; j >= topColIdx(i); j -= 2) {
if let nextNode = gameCircles[j] {
// move this node into the i'th spot
nextNode.physicsBody?.fieldBitMask = 1 << UInt32(i)
nextNode.boardPos = i
gameCircles[i] = nextNode
gameCircles[j] = nil
break
}
}
}
// move short column nodes down as far as possible
for (var i = gameCircles.count - 1; i > longColNodes * 2; i--) {
if gameCircles[i] != nil {
continue
}
let nextNode = gameCircles[i - 1]
nextNode!.physicsBody?.fieldBitMask = 1 << UInt32(i)
nextNode!.boardPos = i
gameCircles[i] = nextNode
gameCircles[i - 1] = nil
}
var nodesAdded = (leftCol: 0.0, rightCol: 0.0)
// bring in new nodes to fill the gaps at the top
for (var idx = gameCircles.count - 1; idx >= 0; idx--) {
if gameCircles[idx] != nil {
continue
}
//println("replacing node \(idx)")
let node = (idx < 2 * longColNodes) ? NumberCircle(num: randomNumbers.generateNumber()) :
OperatorCircle(operatorSymbol: randomOperators.generateOperator())
var delayMultiplier: CGFloat = 1.0
if node is NumberCircle {
if idx % 2 == 0 {
nodesAdded.leftCol++
delayMultiplier = CGFloat(4 * nodesAdded.leftCol)
} else {
nodesAdded.rightCol++
delayMultiplier = CGFloat(4 * nodesAdded.rightCol)
}
}
// cause node to start slightly above the rest position
let restPosition = nodeRestPositions[topColIdx(idx)]
node.position = CGPoint(x: restPosition.x, y: restPosition.y + GameCircleProperties.nodeRadius)
node.setScale(0.0)
node.setBoardPosition(idx)
gameCircles[idx] = node
let delayAction = SKAction.waitForDuration(NSTimeInterval(0.1 * delayMultiplier))
let scaleAction = SKAction.scaleTo(1.0, duration: NSTimeInterval(0.2))
scaleAction.timingMode = SKActionTimingMode.EaseIn
let physBody = self.createGameCirclePhysBody(1 << UInt32(idx))
let bitmaskAction = SKAction.runBlock {
node.physicsBody = physBody
}
let seqAction = SKAction.sequence([delayAction, scaleAction, bitmaskAction])
node.runAction(seqAction)
scene.addChild(node)
}
}
private func addGameCircles() {
var physCategory: UInt32 = 0
var scaleDelay: CGFloat = 0.2
var scaleDelayIncrement: CGFloat = 0.1
var scaleDuration: CGFloat = 0.2
for i in 0...(2 * longColNodes + shortColNodes - 1) {
let node = (i >= 2 * longColNodes) ? OperatorCircle(operatorSymbol: randomOperators.generateOperator()) : NumberCircle(num: randomNumbers.generateNumber())
//let node = NumberCircle(num: i)
//node.fillColor = UIColor.redColor()
node.physicsBody = createGameCirclePhysBody(1 << physCategory)
node.position = nodeRestPositions[i]
node.setScale(0.0)
physCategory++
if i == 2 * longColNodes {
scaleDelay = 0.2
}
let delayAction = SKAction.waitForDuration(NSTimeInterval(scaleDelay))
let scaleAction = SKAction.scaleTo(1.0, duration: NSTimeInterval(scaleDuration))
scaleAction.timingMode = SKActionTimingMode.EaseIn
let groupAction = SKAction.sequence([delayAction, scaleAction])
node.runAction(groupAction)
if i % 2 == 1 {
scaleDelay += scaleDelayIncrement
}
node.setBoardPosition(i)
gameCircles.append(node)
scene.addChild(node)
//circleList.append(node)
}
}
private func createGameCirclePhysBody(category: UInt32) -> SKPhysicsBody {
let physBody = SKPhysicsBody(circleOfRadius: GameCircleProperties.nodeRadius)
// friction when sliding against this physics body
physBody.friction = 3.8
// bounciness of this physics body when colliding
physBody.restitution = 0.8
// mass (and hence inertia) of this physics body
physBody.mass = 1
// this will allow the balls to rotate when bouncing off each other
physBody.allowsRotation = false
physBody.dynamic = true
physBody.fieldBitMask = category
physBody.linearDamping = 2.0
// check for contact with other game circle phys bodies
physBody.contactTestBitMask = 1
return physBody
}
private func drawLongColLines() {
let starty = frame.height - (constraints.header_height + constraints.long_col_vert_padding) * frame.height
let endy = constraints.long_col_vert_padding * frame.height
let leftX = constraints.col_horiz_padding * frame.width
let rightX = frame.width - constraints.col_horiz_padding * frame.width
// draw left col
let leftPath = CGPathCreateMutable()
CGPathMoveToPoint(leftPath, nil, leftX, starty)
CGPathAddLineToPoint(leftPath, nil, leftX, endy)
let leftNode = SKShapeNode(path: leftPath)
leftNode.strokeColor = debugColor
// draw right col
let rightPath = CGPathCreateMutable()
CGPathMoveToPoint(rightPath, nil, rightX, starty)
CGPathAddLineToPoint(rightPath, nil, rightX, endy)
let rightNode = SKShapeNode(path: rightPath)
rightNode.strokeColor = debugColor
scene.addChild(leftNode)
scene.addChild(rightNode)
}
private func drawShortColLine() {
let starty = frame.height - (constraints.header_height + constraints.short_col_vert_padding) * frame.height
let endy = constraints.short_col_vert_padding * frame.height
let x = frame.width / 2.0
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, x, starty)
CGPathAddLineToPoint(path, nil, x, endy)
let node = SKShapeNode(path: path)
node.strokeColor = debugColor
scene.addChild(node)
}
private func createFieldNode(category: UInt32) -> SKFieldNode {
let node = SKFieldNode.radialGravityField()
node.falloff = 0.01
node.strength = 5.5
node.minimumRadius = 10.0
node.categoryBitMask = category
let dragNode = SKFieldNode.dragField()
dragNode.region = SKRegion(radius: 30.0)
dragNode.strength = 20.0
dragNode.categoryBitMask = category
dragNode.exclusive = true
//dragNode.minimumRadius = 5.0
node.addChild(dragNode)
return node
}
private func setupLongColFieldNodes() {
let startY = frame.height - (constraints.header_height + constraints.long_col_vert_padding) * frame.height
let endY = constraints.long_col_vert_padding * frame.height
let leftX = constraints.col_horiz_padding * frame.width
let rightX = frame.width - constraints.col_horiz_padding * frame.width
let yDist = (startY - endY) / CGFloat(longColNodes - 1)
var curOffset: CGFloat = 0.0
var physCategory: UInt32 = 0
for i in 1...longColNodes {
let leftFieldNode = createFieldNode(1 << physCategory)
physCategory++
leftFieldNode.position = CGPointMake(leftX, startY - curOffset)
let rightFieldNode = createFieldNode(1 << physCategory)
physCategory++
rightFieldNode.position = CGPointMake(rightX, startY - curOffset)
if debug {
let leftNode = SKShapeNode(circleOfRadius: 3.0)
//leftNode.position = CGPointMake(leftX, startY - curOffset)
leftNode.fillColor = debugColor
let rightNode = SKShapeNode(circleOfRadius: 3.0)
//rightNode.position = CGPointMake(rightX, startY - curOffset)
rightNode.fillColor = debugColor
leftFieldNode.addChild(leftNode)
rightFieldNode.addChild(rightNode)
}
curOffset += yDist
scene.addChild(leftFieldNode)
scene.addChild(rightFieldNode)
nodeRestPositions.append(leftFieldNode.position)
nodeRestPositions.append(rightFieldNode.position)
}
}
private func setupShortColFieldNodes() {
let startY = frame.height - (constraints.header_height + constraints.short_col_vert_padding) * frame.height
let endY = constraints.short_col_vert_padding * frame.height
let x = frame.width / 2.0
let yDist = (startY - endY) / CGFloat(shortColNodes - 1)
var curOffset: CGFloat = 0.0
var physCategory = 2 * UInt32(longColNodes)
for i in 1...shortColNodes {
let fieldNode = createFieldNode(1 << physCategory)
physCategory++
fieldNode.position = CGPointMake(x, startY - curOffset)
if debug {
let node = SKShapeNode(circleOfRadius: 3.0)
//node.position = CGPointMake(x, startY - curOffset)
node.fillColor = debugColor
fieldNode.addChild(node)
}
curOffset += yDist
scene.addChild(fieldNode)
nodeRestPositions.append(fieldNode.position)
}
}
private func drawDebugLines() {
drawHeaderLine()
drawLongColLines()
drawShortColLine()
}
}
| gpl-2.0 | 83736d1fd7e0e370cb9fe5c7cfd6813b | 34.440678 | 167 | 0.580918 | 4.831331 | false | false | false | false |
grpc/grpc-swift | Sources/protoc-gen-grpc-swift/Generator-Client+AsyncAwait.swift | 1 | 9030 | /*
* Copyright 2021, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import SwiftProtobuf
import SwiftProtobufPluginLibrary
// MARK: - Client protocol
extension Generator {
internal func printAsyncServiceClientProtocol() {
let comments = self.service.protoSourceComments()
if !comments.isEmpty {
// Source comments already have the leading '///'
self.println(comments, newline: false)
}
self.printAvailabilityForAsyncAwait()
self.println("\(self.access) protocol \(self.asyncClientProtocolName): GRPCClient {")
self.withIndentation {
self.println("static var serviceDescriptor: GRPCServiceDescriptor { get }")
self.println("var interceptors: \(self.clientInterceptorProtocolName)? { get }")
for method in service.methods {
self.println()
self.method = method
let rpcType = streamingType(self.method)
let callType = Types.call(for: rpcType)
let arguments: [String]
switch rpcType {
case .unary, .serverStreaming:
arguments = [
"_ request: \(self.methodInputName)",
"callOptions: \(Types.clientCallOptions)?",
]
case .clientStreaming, .bidirectionalStreaming:
arguments = [
"callOptions: \(Types.clientCallOptions)?",
]
}
self.printFunction(
name: self.methodMakeFunctionCallName,
arguments: arguments,
returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>",
bodyBuilder: nil
)
}
}
self.println("}") // protocol
}
}
// MARK: - Client protocol default implementation: Calls
extension Generator {
internal func printAsyncClientProtocolExtension() {
self.printAvailabilityForAsyncAwait()
self.withIndentation("extension \(self.asyncClientProtocolName)", braces: .curly) {
// Service descriptor.
self.withIndentation(
"\(self.access) static var serviceDescriptor: GRPCServiceDescriptor",
braces: .curly
) {
self.println("return \(self.serviceClientMetadata).serviceDescriptor")
}
self.println()
// Interceptor factory.
self.withIndentation(
"\(self.access) var interceptors: \(self.clientInterceptorProtocolName)?",
braces: .curly
) {
self.println("return nil")
}
// 'Unsafe' calls.
for method in self.service.methods {
self.println()
self.method = method
let rpcType = streamingType(self.method)
let callType = Types.call(for: rpcType)
let callTypeWithoutPrefix = Types.call(for: rpcType, withGRPCPrefix: false)
switch rpcType {
case .unary, .serverStreaming:
self.printFunction(
name: self.methodMakeFunctionCallName,
arguments: [
"_ request: \(self.methodInputName)",
"callOptions: \(Types.clientCallOptions)? = nil",
],
returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>",
access: self.access
) {
self.withIndentation("return self.make\(callTypeWithoutPrefix)", braces: .round) {
self.println("path: \(self.methodPathUsingClientMetadata),")
self.println("request: request,")
self.println("callOptions: callOptions ?? self.defaultCallOptions,")
self.println(
"interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
)
}
}
case .clientStreaming, .bidirectionalStreaming:
self.printFunction(
name: self.methodMakeFunctionCallName,
arguments: ["callOptions: \(Types.clientCallOptions)? = nil"],
returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>",
access: self.access
) {
self.withIndentation("return self.make\(callTypeWithoutPrefix)", braces: .round) {
self.println("path: \(self.methodPathUsingClientMetadata),")
self.println("callOptions: callOptions ?? self.defaultCallOptions,")
self.println(
"interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
)
}
}
}
}
}
}
}
// MARK: - Client protocol extension: "Simple, but safe" call wrappers.
extension Generator {
internal func printAsyncClientProtocolSafeWrappersExtension() {
self.printAvailabilityForAsyncAwait()
self.withIndentation("extension \(self.asyncClientProtocolName)", braces: .curly) {
for (i, method) in self.service.methods.enumerated() {
self.method = method
let rpcType = streamingType(self.method)
let callTypeWithoutPrefix = Types.call(for: rpcType, withGRPCPrefix: false)
let streamsResponses = [.serverStreaming, .bidirectionalStreaming].contains(rpcType)
let streamsRequests = [.clientStreaming, .bidirectionalStreaming].contains(rpcType)
// (protocol, requires sendable)
let sequenceProtocols: [(String, Bool)?] = streamsRequests
? [("Sequence", false), ("AsyncSequence", true)]
: [nil]
for (j, sequenceProtocol) in sequenceProtocols.enumerated() {
// Print a new line if this is not the first function in the extension.
if i > 0 || j > 0 {
self.println()
}
let functionName = streamsRequests
? "\(self.methodFunctionName)<RequestStream>"
: self.methodFunctionName
let requestParamName = streamsRequests ? "requests" : "request"
let requestParamType = streamsRequests ? "RequestStream" : self.methodInputName
let returnType = streamsResponses
? Types.responseStream(of: self.methodOutputName)
: self.methodOutputName
let maybeWhereClause = sequenceProtocol.map { protocolName, mustBeSendable -> String in
let constraints = [
"RequestStream: \(protocolName)" + (mustBeSendable ? " & Sendable" : ""),
"RequestStream.Element == \(self.methodInputName)",
]
return "where " + constraints.joined(separator: ", ")
}
self.printFunction(
name: functionName,
arguments: [
"_ \(requestParamName): \(requestParamType)",
"callOptions: \(Types.clientCallOptions)? = nil",
],
returnType: returnType,
access: self.access,
async: !streamsResponses,
throws: !streamsResponses,
genericWhereClause: maybeWhereClause
) {
self.withIndentation(
"return\(!streamsResponses ? " try await" : "") self.perform\(callTypeWithoutPrefix)",
braces: .round
) {
self.println("path: \(self.methodPathUsingClientMetadata),")
self.println("\(requestParamName): \(requestParamName),")
self.println("callOptions: callOptions ?? self.defaultCallOptions,")
self.println(
"interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []"
)
}
}
}
}
}
}
}
// MARK: - Client protocol implementation
extension Generator {
internal func printAsyncServiceClientImplementation() {
self.printAvailabilityForAsyncAwait()
self.withIndentation(
"\(self.access) struct \(self.asyncClientStructName): \(self.asyncClientProtocolName)",
braces: .curly
) {
self.println("\(self.access) var channel: GRPCChannel")
self.println("\(self.access) var defaultCallOptions: CallOptions")
self.println("\(self.access) var interceptors: \(self.clientInterceptorProtocolName)?")
self.println()
self.println("\(self.access) init(")
self.withIndentation {
self.println("channel: GRPCChannel,")
self.println("defaultCallOptions: CallOptions = CallOptions(),")
self.println("interceptors: \(self.clientInterceptorProtocolName)? = nil")
}
self.println(") {")
self.withIndentation {
self.println("self.channel = channel")
self.println("self.defaultCallOptions = defaultCallOptions")
self.println("self.interceptors = interceptors")
}
self.println("}")
}
}
}
| apache-2.0 | d960790c41730ec2a3345dcb7d07af96 | 36.160494 | 100 | 0.620155 | 4.767687 | false | false | false | false |
squall09s/VegOresto | VegoResto/Comment/CreateCommentStep4ResumeViewController.swift | 1 | 1790 | //
// CreateCommentStep4ResumeViewController.swift
// VegoResto
//
// Created by Nicolas on 24/10/2017.
// Copyright © 2017 Nicolas Laurent. All rights reserved.
//
import UIKit
protocol CreateCommentStep4ResumeViewControllerProtocol {
func starLoading()
func stopLoading()
}
class CreateCommentStep4ResumeViewController: UIViewController, CreateCommentStep4ResumeViewControllerProtocol {
@IBOutlet var varIB_activityIndicatorw: UIActivityIndicatorView?
override func viewDidLoad() {
super.viewDidLoad()
self.stopLoading()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func starLoading() {
self.varIB_activityIndicatorw?.alpha = 0
self.varIB_activityIndicatorw?.isHidden = false
self.varIB_activityIndicatorw?.startAnimating()
UIView.animate(withDuration: 0.5, animations: {
self.varIB_activityIndicatorw?.alpha = 1
}) { (_) in
}
}
func stopLoading() {
UIView.animate(withDuration: 0.5, animations: {
self.varIB_activityIndicatorw?.alpha = 0
}) { (_) in
self.varIB_activityIndicatorw?.stopAnimating()
self.varIB_activityIndicatorw?.isHidden = true
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | 829cfd27abe05f888424862d7b654700 | 23.175676 | 112 | 0.666294 | 4.783422 | false | false | false | false |
netguru/inbbbox-ios | Unit Tests/PageRequestSpec.swift | 1 | 2134 | //
// PageRequestSpec.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 03/02/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Quick
import Nimble
import Mockingjay
@testable import Inbbbox
class PageRequestSpec: QuickSpec {
override func spec() {
var sut: PageRequest!
beforeEach {
sut = PageRequest(query: QueryMock())
}
afterEach {
sut = nil
self.removeAllStubs()
}
context("when sending data with success") {
var didInvokeSuccess: Bool?
beforeEach {
self.stub(everything, json([]))
}
afterEach {
didInvokeSuccess = nil
}
it("should respond") {
sut.resume().then { _ -> Void in
didInvokeSuccess = true
}.catch { _ in fail() }
expect(didInvokeSuccess).toEventuallyNot(beNil())
expect(didInvokeSuccess!).toEventually(beTruthy())
}
}
context("when sending data with failure") {
var error: Error?
beforeEach {
let error = NSError(domain: "fixture.domain", code: 0, userInfo: nil)
self.stub(everything, failure(error))
}
afterEach {
error = nil
}
it("should respond with proper json") {
sut.resume().then { _ -> Void in
fail()
}.catch { _error in
error = _error
}
expect(error).toEventuallyNot(beNil())
expect((error as! NSError).domain).toEventually(equal("fixture.domain"))
}
}
}
}
private struct QueryMock: Query {
let path = "/fixture/path"
var parameters = Parameters(encoding: .json)
let method = Method.POST
}
| gpl-3.0 | d0c2261970a267bb7b88a8262244d2fa | 24.392857 | 88 | 0.455696 | 5.413706 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/Views/InfoView.swift | 1 | 2201 | //
// InfoView.swift
// breadwallet
//
// Created by InfoView.swift on 2019-03-25.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
import UIKit
class InfoView: UIView {
private let imageSize: CGFloat = 24
private let infoLabel = UILabel()
private let infoImageView = UIImageView()
var text: String = "" {
didSet {
infoLabel.text = text
}
}
var imageName: String = "ExclamationMarkCircle" {
didSet {
infoImageView.image = UIImage(named: imageName)
}
}
override init(frame: CGRect) {
super.init(frame: .zero)
setUp()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setUp() {
backgroundColor = Theme.secondaryBackground
infoLabel.numberOfLines = 0
infoLabel.textColor = Theme.secondaryText
infoLabel.font = Theme.caption
infoLabel.adjustsFontSizeToFitWidth = true
infoLabel.minimumScaleFactor = 0.5
infoImageView.contentMode = .center
addSubview(infoLabel)
addSubview(infoImageView)
self.heightAnchor.constraint(equalToConstant: 56).isActive = true
infoImageView.constrain([
infoImageView.heightAnchor.constraint(equalToConstant: imageSize),
infoImageView.widthAnchor.constraint(equalToConstant: imageSize),
infoImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor),
infoImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: C.padding[2])
])
let textPadding: CGFloat = 12
infoLabel.constrain([
infoLabel.leftAnchor.constraint(equalTo: infoImageView.rightAnchor, constant: C.padding[2]),
infoLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: textPadding),
infoLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -textPadding),
infoLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -(textPadding * 2))
])
}
}
| mit | 6feef6076753ee35291d05faae0d98b5 | 29.555556 | 104 | 0.630909 | 5.140187 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/Platform/PairedWalletData.swift | 1 | 3258 | //
// PairedWalletData.swift
// breadwallet
//
// Created by Ehsan Rezaie on 2018-07-24.
// Copyright © 2018-2019 Breadwinner AG. All rights reserved.
//
import Foundation
/// Metadata for an EME paired wallet
class PairedWalletData: BRKVStoreObject, BRCoding {
var classVersion: Int = 1
var identifier: String = ""
var service: String = ""
var remotePubKey: String = "" // Base64-encoded string
var created = Date.zeroValue()
/// Find existing paired wallet object based on the remote public key
init?(remotePubKey: String, store: BRReplicatedKVStore) {
var ver: UInt64
var date: Date
var del: Bool
var bytes: [UInt8]
let storeKey = PairedWalletData.storeKey(fromRemotePubKey: remotePubKey)
do {
(ver, date, del, bytes) = try store.get(storeKey)
} catch let error {
print("Unable to initialize PairedWalletData: \(error.localizedDescription)")
return nil
}
let bytesDat = Data(bytes: &bytes, count: bytes.count)
super.init(key: storeKey, version: ver, lastModified: date, deleted: del, data: bytesDat)
}
/// Create new
init(remotePubKey: String, remoteIdentifier: String, service: String) {
super.init(key: PairedWalletData.storeKey(fromRemotePubKey: remotePubKey),
version: 0,
lastModified: Date(),
deleted: false,
data: Data())
self.identifier = remoteIdentifier
self.service = service
self.remotePubKey = remotePubKey
self.created = Date()
}
private static func storeKey(fromRemotePubKey remotePubKeyBase64: String) -> String {
guard let remotePubKey = Data(base64Encoded: remotePubKeyBase64) else {
assertionFailure("expect remotePubKey to be a base64-encoded string")
return ""
}
return "pwd-\(remotePubKey.sha256.hexString)"
}
// MARK: - BRKVStoreObject
override func getData() -> Data? {
return BRKeyedArchiver.archivedDataWithRootObject(self)
}
override func dataWasSet(_ value: Data) {
guard let s: PairedWalletData = BRKeyedUnarchiver.unarchiveObjectWithData(value) else { return }
identifier = s.identifier
service = s.service
remotePubKey = s.remotePubKey
created = s.created
}
// MARK: - BRCoding
required public init?(coder decoder: BRCoder) {
classVersion = decoder.decode("classVersion")
guard classVersion != Int.zeroValue() else {
return nil
}
identifier = decoder.decode("identifier")
service = decoder.decode("service")
remotePubKey = decoder.decode("remotePubKey")
created = decoder.decode("created")
super.init(key: "", version: 0, lastModified: Date(), deleted: true, data: Data())
}
func encode(_ coder: BRCoder) {
coder.encode(classVersion, key: "classVersion")
coder.encode(identifier, key: "identifier")
coder.encode(service, key: "service")
coder.encode(remotePubKey, key: "remotePubKey")
coder.encode(created, key: "created")
}
}
| mit | de18a1aa8a68f7105cb7f7256b08dfec | 33.648936 | 104 | 0.621431 | 4.389488 | false | false | false | false |
dalu93/SwiftHelpSet | Sources/Foundation/DictionaryExtensions.swift | 1 | 1535 | //
// DictionaryExtensions.swift
// SwiftHelpSet
//
// Created by Luca D'Alberti on 8/9/16.
// Copyright © 2016 dalu93. All rights reserved.
//
import Foundation
public extension Dictionary {
/**
Creates a new dictionary instance by adding a set of dictionaries
- parameter dictionaries: Set of dictionaries of the same type
- returns: Sum of all the dictionaries
*/
public static func byAdding<K,V>(dictionaries: [[K:V]]) -> [K:V] {
var dictionarySum: [K:V] = [:]
dictionaries.forEach {
dictionarySum += $0
}
return dictionarySum
}
}
/**
Adds the element of the right dictionary to the left dictionary
- Note: If a right dictionary's key exists on the left dictionary, the value will be
overwritten
- parameter left: A dictionary
- parameter right: An another dictionary
*/
public func +=<K,V>(left: inout [K:V], right: [K:V]) {
for (key, value) in right {
left[key] = value
}
}
/**
Creates a new `Dictionary` instance that is the result of the
`lhs += rhs` operation.
- Note: the `rhs` values have the priority and they will override the `lhs` values
for the same key.
- parameter lhs: A `Dictionary`
- parameter rhs: The other `Dictionary`
- returns: A new `Dictionary` instance that is the sum of the two dictionaries
*/
public func +<K,V>(lhs: [K:V], rhs: [K:V]) -> [K:V] {
var sumDictionary = lhs
sumDictionary += rhs
return sumDictionary
}
| mit | 9480a9fdfd4b15a8371aa18b80731ccc | 24.147541 | 86 | 0.629726 | 3.913265 | false | false | false | false |
xl51009429/SogaAccount | SogaAccount/CommonViews/BLAlertView/AddRecordAlertView.swift | 1 | 4991 | //
// AddRecordAlertView.swift
// SogaAccount
//
// Created by bigliang on 2017/10/23.
// Copyright © 2017年 5i5j. All rights reserved.
//
import UIKit
class AddRecordAlertView: UIView,UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate {
public var sureClosure:(()->Void)?
private var collectionView: UICollectionView!
private var priceTextField: UITextField!
private var desTextField: UITextField!
private var sureBtn: UIButton!
private let numOfLine = 8
private let titles = ["美食1","美食2","美食3","美食4","美食","美食","美食","美食","美食"]
private let images = ["foot","foot","foot","foot","foot","foot","foot","foot","foot"]
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10
layout.scrollDirection = UICollectionViewScrollDirection.vertical
self.collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.backgroundColor = UIColor.white
self.collectionView.contentInset = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
self.collectionView.register(AddRecordCell.classForCoder(), forCellWithReuseIdentifier: "AddRecordCellId")
self.addSubview(self.collectionView)
self.priceTextField = UITextField.init()
self.priceTextField.placeholder = "价格"
self.priceTextField.font = UIFont.H12
self.addSubview(self.priceTextField)
self.desTextField = UITextField.init()
self.desTextField.placeholder = "描述"
self.desTextField.font = UIFont.H12
self.addSubview(self.desTextField)
self.sureBtn = UIButton.init()
self.sureBtn.setTitle("确定", for: UIControlState.normal)
self.sureBtn.backgroundColor = UIColor.orange
self.sureBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
self.sureBtn.addTarget(self, action: #selector(sureBtnClick), for: UIControlEvents.touchUpInside)
self.addSubview(self.sureBtn)
self.collectionView.snp.makeConstraints { (make) in
make.left.right.top.equalTo(0)
make.height.equalTo(((UIScreen.width - CGFloat(10*(self.numOfLine+1)))/CGFloat(self.numOfLine) + 10)*2 + 50)
}
self.priceTextField.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.right.equalTo(-10)
make.height.equalTo(30)
make.top.equalTo(self.collectionView.snp.bottom).offset(10)
}
self.desTextField.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.right.equalTo(-10)
make.height.equalTo(30)
make.top.equalTo(self.priceTextField.snp.bottom).offset(10)
}
self.sureBtn.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.size.equalTo(CGSize(width: 80, height: 30))
make.top.equalTo(self.desTextField.snp.bottom).offset(10)
}
}
@objc func sureBtnClick() {
if let _ = self.sureClosure{
self.sureClosure!()
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 9;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: AddRecordCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddRecordCellId", for: indexPath) as! AddRecordCell
cell .updateCell(title: titles[indexPath.row], imageName: images[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (UIScreen.width - CGFloat(10*(self.numOfLine+1)))/CGFloat(self.numOfLine), height: (UIScreen.width - CGFloat(10*(self.numOfLine+1)))/CGFloat(self.numOfLine) + 10)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class AddRecordCell: UICollectionViewCell {
fileprivate var iconView: UIImageView!
fileprivate var titleLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.iconView = UIImageView()
self.iconView.image = UIImage.init(named: "foot")
self.contentView.addSubview(self.iconView)
self.iconView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(0)
make.bottom.equalTo(-15)
}
self.titleLabel = UILabel()
self.titleLabel.textAlignment = NSTextAlignment.center
self.titleLabel.font = UIFont.H12
self.contentView.addSubview(self.titleLabel)
self.titleLabel.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(0)
make.height.equalTo(20)
}
}
func updateCell(title:String,imageName:String){
self.iconView.image = UIImage(named: imageName)
self.titleLabel.text = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 278e21e0d445f097df77e59e82ec7ed9 | 33.545455 | 185 | 0.75 | 3.733938 | false | false | false | false |
milseman/swift | test/SILGen/ownership.swift | 12 | 834 | // RUN: %target-swift-frontend -parse-stdlib -module-name Swift -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
protocol Error {}
enum MyError : Error {
case case1
}
// CHECK: bb{{[0-9]+}}([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]]
// CHECK-NEXT: [[ERROR_SLOT:%.*]] = alloc_stack $Error
// CHECK-NEXT: [[COPIED_BORROWED_ERROR:%.*]] = copy_value [[BORROWED_ERROR]]
// CHECK-NEXT: store [[COPIED_BORROWED_ERROR]] to [init] [[ERROR_SLOT]]
// CHECK-NEXT: [[ERROR_SLOT_CAST_RESULT:%.*]] = alloc_stack $MyError
// CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[ERROR_SLOT]] : $*Error to MyError in [[ERROR_SLOT_CAST_RESULT]] : $*MyError
func test1(f: () throws -> ()) throws {
do {
let _ = try f()
} catch MyError.case1 {
}
}
| apache-2.0 | c42aa57666ce55e15cf918f426115f98 | 38.714286 | 140 | 0.625899 | 3.159091 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureProducts/Sources/FeatureProductsDomain/ProductIneligibility.swift | 1 | 1907 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import ToolKit
public struct ProductIneligibilityReason: NewTypeString {
public static let eu5Sanction: Self = "EU_5_SANCTION" // SANCTIONS
public static let tier1Required: Self = "TIER_1_REQUIRED" // INSUFFICIENT_TIER
public static let tier2Required: Self = "TIER_2_REQUIRED" // INSUFFICIENT_TIER
public static let tier1TradeLimit: Self = "TIER_1_TRADE_LIMIT" // INSUFFICIENT_TIER
public static let featureNotAvailable: Self = "NOT_ELIGIBLE" // OTHER
public var value: String
public init(_ value: String) {
self.value = value
}
}
public struct ProductIneligibilityType: NewTypeString {
public static let other: Self = "OTHER"
public static let sanction: Self = "SANCTIONS"
public static let insufficientTier: Self = "INSUFFICIENT_TIER"
public var value: String
public init(_ value: String) {
self.value = value
}
}
public struct ProductIneligibility: Codable, Hashable {
/// type of ineligibility: sanctions, insufficient tier, other
public let type: ProductIneligibilityType
/// the ineligibility reason, for now only EU_5_SANCTION is supported
public let reason: ProductIneligibilityReason
/// message to be shown to the user
public let message: String
/// the url to show for learn more if any, this should come from the BE in the future
public var learnMoreUrl: URL? {
switch reason {
case .eu5Sanction:
return URL(string: "https://ec.europa.eu/commission/presscorner/detail/en/ip_22_2332")
default:
return nil
}
}
public init(
type: ProductIneligibilityType,
message: String,
reason: ProductIneligibilityReason
) {
self.type = type
self.message = message
self.reason = reason
}
}
| lgpl-3.0 | 88f6c2aa152b38468aba2f9c26bca56e | 28.78125 | 98 | 0.679433 | 4.07265 | false | false | false | false |
RCacheaux/Bitbucket-iOS | Bitbucket-iOS/Bitbucket/AppDelegate.swift | 1 | 3970 | //
// AppDelegate.swift
// Bitbucket
//
// Created by Rene Cacheaux on 12/17/16.
// Copyright © 2016 Atlassian. All rights reserved.
//
import UIKit
import OAuthKit
import RxSwift
import ReSwift
import ReSwiftRx
import UseCaseKit
import BitbucketKit
import Swinject
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let queue = OperationQueue()
var observable: Observable<AccountState>?
let store = Store<AppState>(reducer: AppReducer(), state: nil)
let container: Container = {
let c = Container()
c.register(AnyReducer.self) { _ in AppReducer() }
c.register(Store<AppState>.self) { r in Store<AppState>(reducer: r.resolve(AnyReducer.self)!, state: nil) }
.inObjectScope(.container)
c.register(Store<AccountState>.self) { _ in Store<AccountState>(reducer: AccountReducer(), state: nil) }
c.register(Observable<AccountState>.self) { r in
let store = r.resolve(Store<AccountState>.self)!
return store.makeObservable(nil)
}
return c
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
observable = AccountStateObservable.make()
let _ = observable?.subscribe(onNext: { state in
if state.accounts.isEmpty {
return
}
print(state.accounts[0])
let accountObservable = AccountStateObservable.make { state in
return state.accounts[0]
}
let teamsUseCase = RefreshTeamsUseCase(observable: accountObservable, store: self.store)
teamsUseCase.schedule(on: self.queue)
})
let loginUseCase = LoginUseCase(presentingViewController: window!.rootViewController!, accountStore: OAuthKit.store)
loginUseCase.schedule(on: queue)
let teamVC = (window!.rootViewController as! UINavigationController).viewControllers[0] as! TeamListViewController
teamVC.observable = store.makeObservable { state in
return state.teams
}
teamVC.makeRefreshUseCase = {
let accountObservable = AccountStateObservable.make { state in
return state.accounts[0]
}
return RefreshTeamsUseCase(observable: accountObservable, store: self.store)
}
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:.
}
}
| apache-2.0 | 7a0fc67ee86ca1d4363fc1cf9a324c98 | 34.123894 | 281 | 0.741245 | 4.9 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | nRF Toolbox/Profiles/Proximity/Peripheral+Proximity.swift | 1 | 3000 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
import CoreBluetooth
extension CBUUID {
static let immediateAlertService = CBUUID(hex: 0x1802)
static let linkLossService = CBUUID(hex: 0x1803)
static let proximityAlertLevelCharacteristic = CBUUID(hex: 0x2A06)
static let txPowerLevelService = CBUUID(hex: 0x1804)
static let txPowerLevelCharacteristic = CBUUID(hex: 0x2A07)
}
extension PeripheralDescription {
static let proximity = PeripheralDescription(uuid: .linkLossService, services: [
.battery, .immediateAlert, .linkLoss, .txPower
],
mandatoryServices: [.immediateAlertService],
mandatoryCharacteristics: [.proximityAlertLevelCharacteristic])
}
private extension PeripheralDescription.Service {
static let immediateAlert = PeripheralDescription.Service(uuid: .immediateAlertService, characteristics: [.proximityAlertLevel])
static let linkLoss = PeripheralDescription.Service(uuid: .linkLossService, characteristics: [.proximityAlertLevel])
static let txPower = PeripheralDescription.Service(uuid: .txPowerLevelService, characteristics: [.txPowerLevel])
}
private extension PeripheralDescription.Service.Characteristic {
static let proximityAlertLevel = PeripheralDescription.Service.Characteristic(uuid: .proximityAlertLevelCharacteristic, properties: nil)
static let txPowerLevel = PeripheralDescription.Service.Characteristic(uuid: .txPowerLevelCharacteristic, properties: .read)
}
| bsd-3-clause | f08ce7cf8eb64ac5f14f27ff04d01855 | 48.180328 | 140 | 0.787333 | 4.77707 | false | false | false | false |
avilin/BeatTheDay | BeatTheDay/Modules/Goals/Router/GoalsRouter.swift | 1 | 773 | //
// GoalsWireframe.swift
// BeatTheDay
//
// Created by Andrés Vicente Linares on 18/6/17.
// Copyright © 2017 Andrés Vicente Linares. All rights reserved.
//
import UIKit
class GoalsRouter {
weak var viewController: UIViewController?
func assembleModule() -> UIViewController {
let view = GoalsViewController()
let presenter = GoalsPresenter()
let interactor = GoalsInteractor()
let goalDataStore = GoalMockDataStore()
view.presenter = presenter
presenter.view = view
presenter.router = self
presenter.interactor = interactor
interactor.presenter = presenter
interactor.dataStore = goalDataStore
return view
}
}
extension GoalsRouter: GoalsWireFrame {
}
| mit | 60d8d3f2a9d06f50f34a30892cddda51 | 21 | 65 | 0.671429 | 4.8125 | false | false | false | false |
HarukaMa/SteamAuth-Swift | SteamAuth/APIEndpoints.swift | 1 | 585 | //
// APIEndpoints.swift
// SteamAuth
//
// Created by Haruka Ma on H28/05/16.
//
import Foundation
public struct APIEndpoints {
static let steamAPI = "https://api.steampowered.com"
static let community = "https://steamcommunity.com"
static let mobileAuth = steamAPI + "/IMobileAuthService/%s/v0001"
static let mobileAuthGetWGToken = mobileAuth.replacingOccurrences(of: "%s", with: "GetWGToken")
static let twoFactor = steamAPI + "/ITwoFactorService/%s/v0001"
static let twoFactorTimeQuery = twoFactor.replacingOccurrences(of: "%s", with: "QueryTime")
}
| mit | 0bbbf1537998b9fd1cbd059a7f2d3bfc | 29.789474 | 99 | 0.717949 | 3.502994 | false | false | false | false |
aiwalle/LiveProject | LiveProject/Home/ViewModel/LJHomeViewModel.swift | 1 | 1235 | //
// LJHomeViewModel.swift
// LiveProject
//
// Created by liang on 2017/8/3.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
class LJHomeViewModel {
lazy var anchorModels = [AnchorModel]()
}
extension LJHomeViewModel {
func loadHomeData(type : HomeType, index : Int, finishedCallBack : @escaping() -> ()) {
LJNetWorkManager.requestData(.get, URLString: "http://qf.56.com/home/v4/moreAnchor.ios", parameters: ["type" : type.type, "index" : index, "size" : 48], finishedCallBack: {(result) -> Void in
guard let resultDict = result as? [String : Any] else { return }
guard let messageDict = resultDict["message"] as? [String : Any] else { return }
// 上面的转换都是字典,这个转换出来是数组,注意看有两个方括号
guard let dataArray = messageDict["anchors"] as? [[String : Any]] else { return }
for (index, dict) in dataArray.enumerated() {
let anchor = AnchorModel(dict: dict)
anchor.isEvenIndex = index % 2 == 0
self.anchorModels.append(anchor)
}
finishedCallBack()
})
}
}
| mit | 0fe5e3b004b293931935515fc9179131 | 33.529412 | 199 | 0.581772 | 4.090592 | false | false | false | false |
jcheng77/missfit-ios | missfit/missfit/HomeViewController.swift | 1 | 3629 | //
// ViewController.swift
// missfit
//
// Created by Hank Liang on 4/13/15.
// Copyright (c) 2015 Hank Liang. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
@IBOutlet weak var myClassesButton: UIButton!
@IBOutlet weak var settings: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
settings.setImage(UIImage(named: "setting")?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
settings.tintColor = UIColor.whiteColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func allClassesButtonClicked(sender: AnyObject) {
UmengHelper.event(AnalyticsClickClasses)
// let allClassesController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("AllClassesViewController") as! AllClassesViewController
// presentViewController(UINavigationController(rootViewController: allClassesController), animated: true, completion: nil)
let featuredClassesController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("FeaturedClassesViewController") as! FeaturedClassesViewController
presentViewController(UINavigationController(rootViewController: featuredClassesController), animated: true, completion: nil)
}
@IBAction func myClassesButtonClicked(sender: AnyObject) {
UmengHelper.event(AnalyticsClickMyClasses)
if MissFitUser.user.isLogin {
let myClassesController: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MyClassesViewController") as! MyClassesViewController
presentViewController(UINavigationController(rootViewController: myClassesController), animated: true, completion: nil)
} else {
UmengHelper.event(AnalyticsClickMyClassesButNotLogin)
let loginController: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController") as! UIViewController
presentViewController(UINavigationController(rootViewController: loginController), animated: true, completion: nil)
}
}
@IBAction func allTeachersButtonClicked(sender: AnyObject) {
UmengHelper.event(AnalyticsClickTeachers)
let allTeachersController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("AllTeachersViewController") as! AllTeachersViewController
presentViewController(UINavigationController(rootViewController: allTeachersController), animated: true, completion: nil)
}
@IBAction func settingsButtonClicked(sender: AnyObject) {
UmengHelper.event(AnalyticsClickSettings)
if MissFitUser.user.isLogin {
let settingsController: SettingsViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SettingsViewController") as! SettingsViewController
presentViewController(UINavigationController(rootViewController: settingsController), animated: true, completion: nil)
} else {
UmengHelper.event(AnalyticsClickSettingsButNotLogin)
let loginController: LoginViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
presentViewController(UINavigationController(rootViewController: loginController), animated: true, completion: nil)
}
}
}
| mit | de29bd460d1febaecbf02f81775c8a43 | 54.830769 | 193 | 0.756682 | 5.8064 | false | false | false | false |
manfengjun/KYMart | Section/Product/List/View/KYSearchView.swift | 1 | 1005 | //
// KYSearchView.swift
// KYMart
//
// Created by JUN on 2017/7/17.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYSearchView: UIView {
@IBOutlet var contentView: UIView!
var ResultNoClosure: NoParamsClosure?
override init(frame: CGRect) {
super.init(frame: frame)
contentView = Bundle.main.loadNibNamed("KYSearchView", owner: self, options: nil)?.first as! UIView
contentView.frame = self.bounds
addSubview(contentView)
awakeFromNib()
}
override func awakeFromNib() {
super.awakeFromNib()
layer.masksToBounds = true
layer.cornerRadius = self.frame.height/2
}
@IBAction func tapAction(_ sender: UITapGestureRecognizer) {
ResultNoClosure?()
}
func callBackNo(_ finished: @escaping NoParamsClosure) {
ResultNoClosure = finished
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 404887862f9cd76ded69e9f82036de0b | 24.692308 | 107 | 0.649701 | 4.337662 | false | false | false | false |
NickKech/Spaceship | Spaceship-iOS/ProgressBarNode.swift | 1 | 2346 | //
// ProgressBarNode.swift
// Spaceship
//
/* Imports SpriteKit frameworks */
import SpriteKit
/* Create the class ProgressBarNode as a subclass of SKNode */
class ProgressBarNode: SKNode {
/* This array stores the pieces of the progress bar */
private var pieces: [SKShapeNode]!
/* This variable stores the size of the progress bar */
// var size: CGSize!
/* Object Initialization */
override init() {
super.init()
/* Adds the pieces */
addPieces()
/* Calculates the size of the progress bar */
// self.size = self.calculateAccumulatedFrame().size
}
private func addPieces() {
/* Initializes pieces array */
pieces = [SKShapeNode]()
/* The width and height of the piece */
let width: CGFloat = 20.0
let height: CGFloat = 24.0
/* The space between two pieces */
let space: CGFloat = 1.0
/* Creates ten pieces */
for index in 0 ..< 10 {
/* Calculates the position of the piece */
let xPos = (width + space) * CGFloat(index)
let yPos: CGFloat = 0
/* Initializes the piece (Draws a rectangle) */
let piece = SKShapeNode(rectOf: CGSize(width: width, height: height))
/* Fill Color: Red */
piece.fillColor = SKColor.red
/* Stroke Color: Dark Red */
piece.strokeColor = SKColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1.0)
/* Piece's position*/
piece.position = CGPoint(x: xPos, y: yPos)
/* Add piece on the node */
addChild(piece)
/* Insert piece in the array */
pieces.append(piece)
}
}
/* Removes all the pieces of the progress bar */
func empty() {
self.removeAllChildren()
/* Initializes shapes' array */
pieces = [SKShapeNode]()
}
/* Sets the progress bar at full */
func full() {
empty()
addPieces()
}
/* Removes one piece from the progress bar */
func decrease() -> Int{
/* Removes the last piece from the progress bar */
if let piece = pieces.last {
piece.removeFromParent()
/* Removes the last element from the array */
pieces.removeLast()
}
/* Return the rest pieces */
return pieces.count
}
/* Required initializer - Not used */
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 189b9db13a526bf8f97bb3a4dca68c15 | 24.225806 | 78 | 0.609548 | 4.234657 | false | false | false | false |
dhardiman/Fetch | Tests/FetchTests/EncodableRequestTests.swift | 1 | 1769 | //
// EncodableRequestTests.swift
// Fetch
//
// Created by drh on 14/02/2022.
// Copyright © 2022 David Hardiman. All rights reserved.
//
import Foundation
@testable import Fetch
import Nimble
import XCTest
class EncodableRequestTests: XCTestCase {
func testItConvertsItsJSONBodyToData() throws {
let testRequest = TestEncodableRequest(encodableBody: StubEncodable(id: MockId(rawValue: "123"),
field: "test",
intField: 42))
guard let data = testRequest.body else {
return fail("Expected body data to not be nil")
}
let decoder = JSONDecoder()
guard let receivedObject = try? decoder.decode(StubEncodable.self, from: data) else {
return fail("Couldn't decode JSON data")
}
expect(receivedObject.id).to(equal(MockId(rawValue: "123")))
expect(receivedObject.field).to(equal("test"))
expect(receivedObject.intField).to(equal(42))
}
}
struct TestEncodableRequest: EncodableRequest {
var encodableBody: StubEncodable
let url: URL = URL(string: "https://test.com")!
let method = HTTPMethod.get
let headers: [String: String]? = nil
}
// Something Swift-specific that would not be serializable with JSONSerializer
typealias MockId = RawStringIdentifier<StubEncodable>
struct StubEncodable: Codable {
let id: MockId
let field: String
let intField: Int
}
struct RawStringIdentifier<T>: RawRepresentable, Codable, Hashable, Equatable {
public typealias RawValue = String
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
}
| mit | 3e0f1b8aadc85a9fef78bfa727b1d748 | 31.145455 | 104 | 0.635181 | 4.652632 | false | true | false | false |
nathawes/swift | test/expr/closure/closures.swift | 1 | 29965 | // RUN: %target-typecheck-verify-swift
var func6 : (_ fn : (Int,Int) -> Int) -> ()
var func6a : ((Int, Int) -> Int) -> ()
var func6b : (Int, (Int, Int) -> Int) -> ()
func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {}
// Expressions can be auto-closurified, so that they can be evaluated separately
// from their definition.
var closure1 : () -> Int = {4} // Function producing 4 whenever it is called.
var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}}
var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing.
var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }}
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{53-53= _ in}}
var closure4 : (Int,Int) -> Int = { $0 + $1 }
var closure5 : (Double) -> Int = {
$0 + 1.0
// expected-error@-1 {{cannot convert value of type 'Double' to closure result type 'Int'}}
}
var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}}
var closure7 : Int = { 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{27-27=()}} // expected-note {{Remove '=' to make 'closure7' a computed property}}{{20-22=}}
var capturedVariable = 1
var closure8 = { [capturedVariable] in
capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}}
}
func funcdecl1(_ a: Int, _ y: Int) {}
func funcdecl3() -> Int {}
func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {}
func funcdecl5(_ a: Int, _ y: Int) {
// Pass in a closure containing the call to funcdecl3.
funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}}
func6({$0 + $1}) // Closure with two named anonymous arguments
func6({($0) + $1}) // Closure with sequence expr inferred type
func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}}
testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}}
// expected-error@-1 {{cannot convert value of type '(Int) -> Int' to expected argument type '()'}}
funcdecl5(1, 2) // recursion.
// Element access from a tuple.
var a : (Int, f : Int, Int)
var b = a.1+a.f
// Tuple expressions with named elements.
var i : (y : Int, x : Int) = (x : 42, y : 11) // expected-warning {{expression shuffles the elements of this tuple; this behavior is deprecated}}
funcdecl1(123, 444)
// Calls.
4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}}
// rdar://12017658 - Infer some argument types from func6.
func6({ a, b -> Int in a+b})
// Return type inference.
func6({ a,b in a+b })
// Infer incompatible type.
func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments.
func6({ _,_ in 4 })
func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}}
// TODO: This diagnostic can be improved: rdar://22128205
func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, Int) -> Int' to expected argument type '(Int, Int) -> Int'}}
var fn = {}
var fn2 = { 4 }
var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}}
}
func unlabeledClosureArgument() {
func add(_ x: Int, y: Int) -> Int { return x + y }
func6a({$0 + $1}) // single closure argument
func6a(add)
func6b(1, {$0 + $1}) // second arg is closure
func6b(1, add)
func6c({$0 + $1}) // second arg is default int
func6c(add)
}
// rdar://11935352 - closure with no body.
func closure_no_body(_ p: () -> ()) {
return closure_no_body({})
}
// rdar://12019415
func t() {
let u8 : UInt8 = 1
let x : Bool = true
if 0xA0..<0xBF ~= Int(u8) && x {
}
}
// <rdar://problem/11927184>
func f0(_ a: Any) -> Int { return 1 }
assert(f0(1) == 1)
var selfRef = { selfRef() } // expected-error {{variable used within its own initial value}}
var nestedSelfRef = {
var recursive = { nestedSelfRef() } // expected-error {{variable used within its own initial value}}
recursive()
}
var shadowed = { (shadowed: Int) -> Int in
let x = shadowed
return x
} // no-warning
var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning
func anonymousClosureArgsInClosureWithArgs() {
func f(_: String) {}
var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}}
var a4 = { (z: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
var a5 = { (_: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}}
// expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String'}}
}
}
func doStuff(_ fn : @escaping () -> Int) {}
func doVoidStuff(_ fn : @escaping () -> ()) {}
// <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely
class ExplicitSelfRequiredTest {
var x = 42
func method() -> Int {
// explicit closure requires an explicit "self." base or an explicit capture.
doVoidStuff({ self.x += 1 })
doVoidStuff({ [self] in x += 1 })
doVoidStuff({ [self = self] in x += 1 })
doVoidStuff({ [unowned self] in x += 1 })
doVoidStuff({ [unowned(unsafe) self] in x += 1 })
doVoidStuff({ [unowned self = self] in x += 1 })
doStuff({ [self] in x+1 })
doStuff({ [self = self] in x+1 })
doStuff({ self.x+1 })
doStuff({ [unowned self] in x+1 })
doStuff({ [unowned(unsafe) self] in x+1 })
doStuff({ [unowned self = self] in x+1 })
doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}}
doVoidStuff({ doStuff({ x+1 })}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{28-28= [self] in}} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{19-19=self.}}
doVoidStuff({ _ = "\(x)"}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}}
doVoidStuff({ [y = self] in x += 1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{33-33=self.}}
doStuff({ [y = self] in x+1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ [weak self] in x += 1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [weak self] in x+1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff({ [self = self.x] in x += 1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [self = self.x] in x+1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
// Methods follow the same rules as properties, uses of 'self' without capturing must be marked with "self."
doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}}
doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}}
doVoidStuff { () -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{35-35=self.}}
doVoidStuff { [y = self] in _ = method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{37-37=self.}}
doStuff({ [y = self] in method() }) // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ [weak self] in _ = method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [weak self] in method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff({ [self = self.x] in _ = method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [self = self.x] in method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff { _ = self.method() }
doVoidStuff { [self] in _ = method() }
doVoidStuff { [self = self] in _ = method() }
doVoidStuff({ [unowned self] in _ = method() })
doVoidStuff({ [unowned(unsafe) self] in _ = method() })
doVoidStuff({ [unowned self = self] in _ = method() })
doStuff { self.method() }
doStuff { [self] in method() }
doStuff({ [self = self] in method() })
doStuff({ [unowned self] in method() })
doStuff({ [unowned(unsafe) self] in method() })
doStuff({ [unowned self = self] in method() })
// When there's no space between the opening brace and the first expression, insert it
doStuff {method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in }} expected-note{{reference 'self.' explicitly}} {{14-14=self.}}
doVoidStuff {_ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}}
doVoidStuff {() -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{34-34=self.}}
// With an empty capture list, insertion should should be suggested without a comma
doStuff { [] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{21-21=self.}}
doStuff { [ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
doStuff { [ /* This space intentionally left blank. */ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{65-65=self.}}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}}
doStuff { [ // Nothing in this capture list!
]
in
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{9-9=self.}}
}
// An inserted capture list should be on the same line as the opening brace, immediately following it.
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff {
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+2 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
// Note: Trailing whitespace on the following line is intentional and should not be removed!
doStuff {
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff { // We have stuff to do.
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff {// We have stuff to do.
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// String interpolation should offer the diagnosis and fix-its at the expected locations
doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}}
doVoidStuff { _ = "\(x+1)" } // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}}
// If we already have a capture list, self should be added to the list
let y = 1
doStuff { [y] in method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}}
doStuff { [ // expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
y // expected-warning {{capture 'y' was never used}}
] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{14-14=self.}}
// <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list
// This should not produce an error, "x" isn't being captured by the closure.
doStuff({ [myX = x] in myX })
// This should produce an error, since x is used within the inner closure.
doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{23-23= [self] in }} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
// expected-warning @-1 {{capture 'myX' was never used}}
return 42
}
}
// If the implicit self is of value type, no diagnostic should be produced.
struct ImplicitSelfAllowedInStruct {
var x = 42
mutating func method() -> Int {
doStuff({ x+1 })
doVoidStuff({ x += 1 })
doStuff({ method() })
doVoidStuff({ _ = method() })
}
func method2() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method2() })
doVoidStuff({ _ = method2() })
}
}
enum ImplicitSelfAllowedInEnum {
case foo
var x: Int { 42 }
mutating func method() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method() })
doVoidStuff({ _ = method() })
}
func method2() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method2() })
doVoidStuff({ _ = method2() })
}
}
class SomeClass {
var field : SomeClass?
func foo() -> Int {}
}
func testCaptureBehavior(_ ptr : SomeClass) {
// Test normal captures.
weak var wv : SomeClass? = ptr
unowned let uv : SomeClass = ptr
unowned(unsafe) let uv1 : SomeClass = ptr
unowned(safe) let uv2 : SomeClass = ptr
doStuff { wv!.foo() }
doStuff { uv.foo() }
doStuff { uv1.foo() }
doStuff { uv2.foo() }
// Capture list tests
let v1 : SomeClass? = ptr
let v2 : SomeClass = ptr
doStuff { [weak v1] in v1!.foo() }
// expected-warning @+2 {{variable 'v1' was written to, but never read}}
doStuff { [weak v1, // expected-note {{previous}}
weak v1] in v1!.foo() } // expected-error {{definition conflicts with previous value}}
doStuff { [unowned v2] in v2.foo() }
doStuff { [unowned(unsafe) v2] in v2.foo() }
doStuff { [unowned(safe) v2] in v2.foo() }
doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() }
let i = 42
// expected-warning @+1 {{variable 'i' was never mutated}}
doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
}
extension SomeClass {
func bar() {
doStuff { [unowned self] in self.foo() }
doStuff { [unowned xyz = self.field!] in xyz.foo() }
doStuff { [weak xyz = self.field] in xyz!.foo() }
// rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure
// FIXME: We should probably offer a fix-it to the field capture error and suppress the 'implicit self' error. https://bugs.swift.org/browse/SR-11634
doStuff { [weak self.field] in field!.foo() } // expected-error {{fields may only be captured by assigning to a specific name}} expected-error {{reference to property 'field' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note {{reference 'self.' explicitly}} {{36-36=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
// expected-warning @+1 {{variable 'self' was written to, but never read}}
doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}}
}
func strong_in_capture_list() {
// <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message
_ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}}
}
}
// <rdar://problem/16955318> Observed variable in a closure triggers an assertion
var closureWithObservedProperty: () -> () = {
var a: Int = 42 { // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
willSet {
_ = "Will set a to \(newValue)"
}
didSet {
_ = "Did set a with old value of \(oldValue)"
}
}
}
;
{}() // expected-error{{top-level statement cannot begin with a closure expression}}
// rdar://19179412 - Crash on valid code.
func rdar19179412() -> (Int) -> Int {
return { x in
class A {
let d : Int = 0
}
return 0
}
}
// Test coercion of single-expression closure return types to void.
func takesVoidFunc(_ f: () -> ()) {}
var i: Int = 1
// expected-warning @+1 {{expression of type 'Int' is unused}}
takesVoidFunc({i})
// expected-warning @+1 {{expression of type 'Int' is unused}}
var f1: () -> () = {i}
var x = {return $0}(1)
func returnsInt() -> Int { return 0 }
takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}}
takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}}
// These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969
Void(0) // expected-error{{argument passed to call that takes no arguments}}
_ = {0}
// <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note
let samples = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> <#Result#> in }}
if (i > 10) { return true }
else { return false }
}()
// <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared
func f(_ fp : (Bool, Bool) -> Bool) {}
f { $0 && !$1 }
// <rdar://problem/18123596> unexpected error on self. capture inside class method
func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {}
struct TestStructWithStaticMethod {
static func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
class TestClassWithStaticMethod {
class func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
// Test that we can infer () as the result type of these closures.
func genericOne<T>(_ a: () -> T) {}
func genericTwo<T>(_ a: () -> T, _ b: () -> T) {}
genericOne {}
genericTwo({}, {})
// <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized
class r22344208 {
func f() {
let q = 42
let _: () -> Int = {
[unowned self, // expected-warning {{capture 'self' was never used}}
q] in // expected-warning {{capture 'q' was never used}}
1 }
}
}
var f = { (s: Undeclared) -> Int in 0 } // expected-error {{cannot find type 'Undeclared' in scope}}
// <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type.
func r21375863() {
var width = 0 // expected-warning {{variable 'width' was never mutated}}
var height = 0 // expected-warning {{variable 'height' was never mutated}}
var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{cannot find type 'asdf' in scope}} expected-warning {{variable 'bufs' was never used}}
[UInt8](repeating: 0, count: width*height)
}
}
// <rdar://problem/25993258>
// Don't crash if we infer a closure argument to have a tuple type containing inouts.
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258a() {
r25993258_helper { x in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
func r25993258b() {
r25993258_helper { _ in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// We have to map the captured var type into the right generic environment.
class GenericClass<T> {}
func lvalueCapture<T>(c: GenericClass<T>) {
var cc = c
weak var wc = c
func innerGeneric<U>(_: U) {
_ = cc
_ = wc
cc = wc!
}
}
// Don't expose @lvalue-ness in diagnostics.
let closure = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{16-16= () -> <#Result#> in }}
var helper = true
return helper
}
// SR-9839
func SR9839(_ x: @escaping @convention(block) () -> Void) {}
func id<T>(_ x: T) -> T {
return x
}
var qux: () -> Void = {}
SR9839(qux)
SR9839(id(qux)) // expected-error {{conflicting arguments to generic parameter 'T' ('() -> Void' vs. '@convention(block) () -> Void')}}
func forceUnwrap<T>(_ x: T?) -> T {
return x!
}
var qux1: (() -> Void)? = {}
SR9839(qux1!)
SR9839(forceUnwrap(qux1))
// rdar://problem/65155671 - crash referencing parameter of outer closure
func rdar65155671(x: Int) {
{ a in
_ = { [a] in a }
}(x)
}
func sr3186<T, U>(_ f: (@escaping (@escaping (T) -> U) -> ((T) -> U))) -> ((T) -> U) {
return { x in return f(sr3186(f))(x) }
}
class SR3186 {
init() {
// expected-warning@+1{{capture 'self' was never used}}
let v = sr3186 { f in { [unowned self, f] x in x != 1000 ? f(x + 1) : "success" } }(0)
print("\(v)")
}
}
| apache-2.0 | b686a93fb08077ff725ad0f56f5daf62 | 55.967681 | 426 | 0.660037 | 3.740949 | false | false | false | false |
PANDA-Guide/PandaGuideApp | PandaGuide/SwipeController.swift | 1 | 7652 | //
// SwipeController.swift
// Photonomie
//
// Created by Pierre Dulac on 18/05/2016.
// Copyright © 2016 Sixième Etage. All rights reserved.
//
import UIKit
import os.log
enum SwipeControllerIdentifier: Int {
case AccountController = 0
case CaptureController = 1
case HistoryController = 2
}
class SwipeController: UIViewController {
fileprivate var swippingController: UIViewController? // reference the next controller being animated
fileprivate var stackViewControllers = [UIViewController]()
fileprivate var stackPageViewControllers = [UIViewController]()
fileprivate let stackStartLocation: Int = 1
fileprivate var pageViewController = UIPageViewController()
var currentStackPageViewController: UIViewController?
fileprivate struct Constants {
static var ScreenWidth: CGFloat {
return UIScreen.main.bounds.width
}
static var ScreenHeight: CGFloat {
return UIScreen.main.bounds.height
}
static var StatusBarHeight: CGFloat {
return UIApplication.shared.statusBarFrame.height
}
static var ScreenHeightWithoutStatusBar: CGFloat {
return UIScreen.main.bounds.height - StatusBarHeight
}
}
override func viewDidLoad() {
super.viewDidLoad()
initializeStackViewControllers()
setupViewControllers() // NB: it accesses the controllers view property
// load the first controller
pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
pageViewController.dataSource = self
pageViewController.delegate = self
pageViewController.setViewControllers([stackPageViewControllers[stackStartLocation]], direction: .forward, animated: false, completion: nil)
// only setup this here, because it accesses the controllers view property
setupPageViewControllers()
}
fileprivate func initializeStackViewControllers() {
let accountController = AccountViewController()
let accountNavigationController = BrandNavigationController(rootViewController: accountController)
let cameraController = CaptureViewController()
let historyController = UserHistoryViewController()
let historyNavigationController = BrandNavigationController(rootViewController: historyController)
stackViewControllers = [accountNavigationController, cameraController, historyNavigationController]
}
fileprivate func setupViewControllers() {
stackViewControllers.enumerated().forEach { index, viewController in
let pageViewController = UIViewController()
pageViewController.addChildViewController(viewController)
pageViewController.view.addSubview(viewController.view)
viewController.didMove(toParentViewController: pageViewController)
stackPageViewControllers.append(pageViewController)
}
currentStackPageViewController = stackPageViewControllers[stackStartLocation]
}
fileprivate func setupPageViewControllers() {
addChildViewController(pageViewController)
view.addSubview(pageViewController.view)
pageViewController.view.frame = view.bounds
pageViewController.didMove(toParentViewController: self)
}
override var childViewControllerForStatusBarHidden : UIViewController? {
return swippingController
}
override var childViewControllerForStatusBarStyle : UIViewController? {
return swippingController
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
func moveToControllerIdentifier(_ controllerIdentifier: SwipeControllerIdentifier, animated: Bool) {
let controllerIndex: Int = controllerIdentifier.rawValue
let currentControllerIndex: Int = {
if let controller = currentStackPageViewController {
return stackPageViewControllers.index(of: controller) ?? 0
}
return 0
}()
let direction: UIPageViewControllerNavigationDirection = {
if controllerIndex < currentControllerIndex {
return .reverse
} else {
return .forward
}
}()
let newPageViewController = stackPageViewControllers[controllerIndex]
currentStackPageViewController = newPageViewController
pageViewController.setViewControllers(
[newPageViewController],
direction: direction,
animated: true,
completion: { finished in
self.updateStateAfterSwipe(controllerIndex)
})
}
fileprivate func updateStateAfterSwipe(_ newStackViewControllerIndex: Int) {
self.swippingController = self.stackViewControllers[newStackViewControllerIndex]
// ensure the status bar is updated correctly
self.setNeedsStatusBarAppearanceUpdate()
}
}
// MARK: Panda logic
extension SwipeController {
func present(helpRequest: HelpRequest, animated: Bool) {
let controllerIndex: Int = SwipeControllerIdentifier.HistoryController.rawValue
var controller = stackViewControllers[controllerIndex]
if let navController = controller as? UINavigationController {
navController.popToRootViewController(animated: false)
controller = navController.topViewController!
}
guard let historyViewController = controller as? UserHistoryViewController else {
os_log("Failed to cast top view controller of the history tab, should not happen", type: .error)
return
}
historyViewController.present(helpRequest: helpRequest, animated: animated)
}
}
extension SwipeController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if viewController == stackPageViewControllers.first {
return nil
}
return stackPageViewControllers[stackPageViewControllers.index(of: viewController)! - 1]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if viewController == stackPageViewControllers.last {
return nil
}
return stackPageViewControllers[stackPageViewControllers.index(of: viewController)! + 1]
}
}
// MARK: override the delegate behavior
extension SwipeController: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if !completed {
return
}
if let vc = pageViewController.viewControllers?.first, let newIndex = stackPageViewControllers.index(of: vc) {
currentStackPageViewController = stackPageViewControllers[newIndex]
self.updateStateAfterSwipe(newIndex)
}
}
}
// MARK: Enable/Disable swipe
extension SwipeController {
func enableSwipeGestures() {
pageViewController.dataSource = self
}
func disableSwipeGestures() {
// behavior documented by Apple, no datasource disable the gestures
pageViewController.dataSource = nil
}
}
| gpl-3.0 | 0f8a61df312e23bbac489d488a76b172 | 34.581395 | 190 | 0.713333 | 6.260229 | false | false | false | false |
mcnoquera/UPExtension | Example/Tests/Tests.swift | 1 | 1161 | // https://github.com/Quick/Quick
import Quick
import Nimble
import UPExtension
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 9d576a513c06261ae58f0b029ac1db77 | 22.1 | 60 | 0.358442 | 5.526316 | false | false | false | false |
respan/ChainableSwift | ChainableSwift/Classes/UITextFieldExtensions.swift | 1 | 6362 | //
// UITextFieldExtensions.swift
// Pods
//
// Created by Denis Sushko on 21.04.16.
//
//
public extension UITextField {
/// ChainableSwift
@discardableResult final func text(_ text: String?) -> Self {
self.text = text
return self
}
/// ChainableSwift
@discardableResult final func textColor(_ textColor: UIColor?) -> Self {
self.textColor = textColor
return self
}
/// ChainableSwift
@discardableResult final func font(_ font: UIFont?) -> Self {
self.font = font
return self
}
/// ChainableSwift
@discardableResult final func textAlignment(_ textAlignment: NSTextAlignment) -> Self {
self.textAlignment = textAlignment
return self
}
/// ChainableSwift
@discardableResult final func borderStyle(_ borderStyle: UITextField.BorderStyle) -> Self {
self.borderStyle = borderStyle
return self
}
/// ChainableSwift
@discardableResult final func defaultTextAttributes(_ defaultTextAttributes: [NSAttributedString.Key : Any]) -> Self {
self.defaultTextAttributes = defaultTextAttributes
return self
}
/// ChainableSwift
@discardableResult final func placeholder(_ placeholder: String?) -> Self {
self.placeholder = placeholder
return self
}
/// ChainableSwift
@discardableResult final func clearsOnBeginEditing(_ clearsOnBeginEditing: Bool) -> Self {
self.clearsOnBeginEditing = clearsOnBeginEditing
return self
}
/// ChainableSwift
@discardableResult final func adjustsFontSizeToFitWidth(_ adjustsFontSizeToFitWidth: Bool) -> Self {
self.adjustsFontSizeToFitWidth = adjustsFontSizeToFitWidth
return self
}
/// ChainableSwift
@discardableResult final func minimumFontSize(_ minimumFontSize: CGFloat) -> Self {
self.minimumFontSize = minimumFontSize
return self
}
/// ChainableSwift
@discardableResult final func background(_ background: UIImage?) -> Self {
self.background = background
return self
}
/// ChainableSwift
@discardableResult final func disabledBackground(_ disabledBackground: UIImage?) -> Self {
self.disabledBackground = disabledBackground
return self
}
/// ChainableSwift
@discardableResult final func allowsEditingTextAttributes(_ allowsEditingTextAttributes: Bool) -> Self {
self.allowsEditingTextAttributes = allowsEditingTextAttributes
return self
}
/// ChainableSwift
@discardableResult final func typingAttributes(_ typingAttributes: [NSAttributedString.Key : Any]?) -> Self {
self.typingAttributes = typingAttributes
return self
}
/// ChainableSwift
@discardableResult final func clearButtonMode(_ clearButtonMode: UITextField.ViewMode) -> Self {
self.clearButtonMode = clearButtonMode
return self
}
/// ChainableSwift
@discardableResult final func leftView(_ leftView: UIView?) -> Self {
self.leftView = leftView
return self
}
/// ChainableSwift
@discardableResult final func leftViewMode(_ leftViewMode: UITextField.ViewMode) -> Self {
self.leftViewMode = leftViewMode
return self
}
/// ChainableSwift
@discardableResult final func rightView(_ rightView: UIView?) -> Self {
self.rightView = rightView
return self
}
/// ChainableSwift
@discardableResult final func rightViewMode(_ rightViewMode: UITextField.ViewMode) -> Self {
self.rightViewMode = rightViewMode
return self
}
/// ChainableSwift
@discardableResult final func inputView(_ inputView: UIView?) -> Self {
self.inputView = inputView
return self
}
/// ChainableSwift
@discardableResult final func inputAccessoryView(_ inputAccessoryView: UIView?) -> Self {
self.inputAccessoryView = inputAccessoryView
return self
}
/// ChainableSwift
@discardableResult final func clearsOnInsertion(_ clearsOnInsertion: Bool) -> Self {
self.clearsOnInsertion = clearsOnInsertion
return self
}
/// ChainableSwift
@discardableResult final func attributedText(_ attributedText: NSAttributedString?) -> Self {
self.attributedText = attributedText
return self
}
/// ChainableSwift
@discardableResult final func attributedPlaceholder(_ attributedPlaceholder: NSAttributedString?) -> Self {
self.attributedPlaceholder = attributedPlaceholder
return self
}
/// ChainableSwift
@discardableResult final func autocapitalizationType(_ autocapitalizationType: UITextAutocapitalizationType) -> Self {
self.autocapitalizationType = autocapitalizationType
return self
}
/// ChainableSwift
@discardableResult final func autocorrectionType(_ autocorrectionType: UITextAutocorrectionType) -> Self {
self.autocorrectionType = autocorrectionType
return self
}
/// ChainableSwift
@discardableResult final func spellCheckingType(_ spellCheckingType: UITextSpellCheckingType) -> Self {
self.spellCheckingType = spellCheckingType
return self
}
/// ChainableSwift
@discardableResult final func keyboardType(_ keyboardType: UIKeyboardType) -> Self {
self.keyboardType = keyboardType
return self
}
/// ChainableSwift
@discardableResult final func keyboardAppearance(_ keyboardAppearance: UIKeyboardAppearance) -> Self {
self.keyboardAppearance = keyboardAppearance
return self
}
/// ChainableSwift
@discardableResult final func returnKeyType(_ returnKeyType: UIReturnKeyType) -> Self {
self.returnKeyType = returnKeyType
return self
}
/// ChainableSwift
@discardableResult final func enablesReturnKeyAutomatically(_ enablesReturnKeyAutomatically: Bool) -> Self {
self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically
return self
}
/// ChainableSwift
@discardableResult final func secureTextEntry(_ secureTextEntry: Bool) -> Self {
self.isSecureTextEntry = secureTextEntry
return self
}
}
| mit | 3c7809183e531291da96ced1e6289c78 | 26.304721 | 122 | 0.671801 | 6.059048 | false | false | false | false |
nickqiao/NKBill | NKBill/Third/CVCalendar/CVAuxiliaryView.swift | 4 | 4351 | //
// CVAuxiliaryView.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 22/03/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
public final class CVAuxiliaryView: UIView {
public var shape: CVShape!
public var strokeColor: UIColor! {
didSet {
setNeedsDisplay()
}
}
public var fillColor: UIColor! {
didSet {
setNeedsDisplay()
}
}
public let defaultFillColor = UIColor.colorFromCode(0xe74c3c)
private var radius: CGFloat {
get {
return (min(frame.height, frame.width) - 10) / 2
}
}
public unowned let dayView: DayView
public init(dayView: DayView, rect: CGRect, shape: CVShape) {
self.dayView = dayView
self.shape = shape
super.init(frame: rect)
strokeColor = UIColor.clearColor()
fillColor = UIColor.colorFromCode(0xe74c3c)
layer.cornerRadius = 5
backgroundColor = .clearColor()
}
public override func didMoveToSuperview() {
setNeedsDisplay()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func drawRect(rect: CGRect) {
var path: UIBezierPath!
if let shape = shape {
switch shape {
case .RightFlag: path = rightFlagPath()
case .LeftFlag: path = leftFlagPath()
case .Circle: path = circlePath()
case .Rect: path = rectPath()
case .Custom(let customPathBlock): path = customPathBlock(rect)
}
switch shape {
case .Custom: break
default: path.lineWidth = 1
}
}
strokeColor.setStroke()
fillColor.setFill()
if let path = path {
path.stroke()
path.fill()
}
}
deinit {
//println("[CVCalendar Recovery]: AuxiliaryView is deinited.")
}
}
extension CVAuxiliaryView {
public func updateFrame(frame: CGRect) {
self.frame = frame
setNeedsDisplay()
}
}
extension CVAuxiliaryView {
func circlePath() -> UIBezierPath {
let arcCenter = CGPoint(x: frame.width / 2, y: frame.height / 2)
let startAngle = CGFloat(0)
let endAngle = CGFloat(M_PI * 2.0)
let clockwise = true
let path = UIBezierPath(arcCenter: arcCenter, radius: radius,
startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
return path
}
func rightFlagPath() -> UIBezierPath {
// let appearance = dayView.calendarView.appearance
// let offset = appearance.spaceBetweenDayViews!
let flag = UIBezierPath()
flag.moveToPoint(CGPoint(x: bounds.width / 2, y: bounds.height / 2 - radius))
flag.addLineToPoint(CGPoint(x: bounds.width, y: bounds.height / 2 - radius))
flag.addLineToPoint(CGPoint(x: bounds.width, y: bounds.height / 2 + radius ))
flag.addLineToPoint(CGPoint(x: bounds.width / 2, y: bounds.height / 2 + radius))
let path = CGPathCreateMutable()
CGPathAddPath(path, nil, circlePath().CGPath)
CGPathAddPath(path, nil, flag.CGPath)
return UIBezierPath(CGPath: path)
}
func leftFlagPath() -> UIBezierPath {
let flag = UIBezierPath()
flag.moveToPoint(CGPoint(x: bounds.width / 2, y: bounds.height / 2 + radius))
flag.addLineToPoint(CGPoint(x: 0, y: bounds.height / 2 + radius))
flag.addLineToPoint(CGPoint(x: 0, y: bounds.height / 2 - radius))
flag.addLineToPoint(CGPoint(x: bounds.width / 2, y: bounds.height / 2 - radius))
let path = CGPathCreateMutable()
CGPathAddPath(path, nil, circlePath().CGPath)
CGPathAddPath(path, nil, flag.CGPath)
return UIBezierPath(CGPath: path)
}
func rectPath() -> UIBezierPath {
// let midX = bounds.width / 2
let midY = bounds.height / 2
let appearance = dayView.calendarView.appearance
let offset = appearance.spaceBetweenDayViews!
print("offset = \(offset)")
let path = UIBezierPath(rect: CGRect(x: 0 - offset, y: midY - radius,
width: bounds.width + offset / 2, height: radius * 2))
return path
}
}
| apache-2.0 | cab2a02be9a7476ecbdfc5b34789e32c | 27.81457 | 97 | 0.598253 | 4.471737 | false | false | false | false |
xcodeswift/xcproj | Sources/XcodeProj/Project/XCSharedData.swift | 1 | 1967 | import Foundation
import PathKit
public final class XCSharedData: Equatable {
// MARK: - Attributes
/// Shared data schemes.
public var schemes: [XCScheme]
/// Shared data breakpoints.
public var breakpoints: XCBreakpointList?
/// Workspace settings (represents the WorksapceSettings.xcsettings file).
public var workspaceSettings: WorkspaceSettings?
// MARK: - Init
/// Initializes the shared data with its properties.
///
/// - Parameters:
/// - schemes: Shared data schemes.
/// - breakpoints: Shared data breakpoints.
/// - workspaceSettings: Workspace settings (represents the WorksapceSettings.xcsettings file).
public init(schemes: [XCScheme],
breakpoints: XCBreakpointList? = nil,
workspaceSettings: WorkspaceSettings? = nil) {
self.schemes = schemes
self.breakpoints = breakpoints
self.workspaceSettings = workspaceSettings
}
/// Initializes the XCSharedData reading the content from the disk.
///
/// - Parameter path: path where the .xcshareddata is.
public init(path: Path) throws {
if !path.exists {
throw XCSharedDataError.notFound(path: path)
}
schemes = path.glob("xcschemes/*.xcscheme")
.compactMap { try? XCScheme(path: $0) }
breakpoints = try? XCBreakpointList(path: path + "xcdebugger/Breakpoints_v2.xcbkptlist")
let workspaceSettingsPath = path + "WorkspaceSettings.xcsettings"
if workspaceSettingsPath.exists {
workspaceSettings = try WorkspaceSettings.at(path: workspaceSettingsPath)
} else {
workspaceSettings = nil
}
}
// MARK: - Equatable
public static func == (lhs: XCSharedData, rhs: XCSharedData) -> Bool {
lhs.schemes == rhs.schemes &&
lhs.breakpoints == rhs.breakpoints &&
lhs.workspaceSettings == rhs.workspaceSettings
}
}
| mit | f21e483bb5420404c22f4ee24f2b042b | 32.913793 | 101 | 0.644637 | 4.595794 | false | false | false | false |
RameshRM/just-now | JustNow/JustNow/AppInfo.swift | 1 | 898 | //
// AppInfo.swift
// JustNow
//
// Created by Mahadevan, Ramesh on 7/26/15.
// Copyright (c) 2015 GoliaMania. All rights reserved.
//
import Foundation
public class AppInfo {
var appId : String!;
var appVersion : String!;
var lastUpdated = NSDate().timeIntervalSince1970;
var firstInstalledTime = NSDate().timeIntervalSince1970;
static let APPVERSION:String = "CFBundleVersion";
init(){
}
init(appId:String, bundleProperties: [NSObject : AnyObject]){
self.appId = appId;
self.appVersion = bundleProperties[AppInfo.APPVERSION] as! String
}
func toKVP()->NSDictionary{
var messageKVP:NSDictionary=["appId":self.appId, "appVersion": self.appVersion, "lastUpdated": self.lastUpdated, "firstInstalledTime": self.firstInstalledTime];
return messageKVP;
}
} | apache-2.0 | f99dee16e4ee9d48cbf9b6748a589d3b | 22.051282 | 168 | 0.639198 | 4.467662 | false | false | false | false |
zhiquan911/chance_btc_wallet | chance_btc_wallet/Pods/Log/Source/Formatter.swift | 4 | 10789 | //
// Formatter.swift
//
// Copyright (c) 2015-2016 Damien (http://delba.io)
//
// 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.
//
public enum Component {
case date(String)
case message
case level
case file(fullPath: Bool, fileExtension: Bool)
case line
case column
case function
case location
case block(() -> Any?)
}
public class Formatters {}
public class Formatter: Formatters {
/// The formatter format.
private var format: String
/// The formatter components.
private var components: [Component]
/// The date formatter.
fileprivate let dateFormatter = DateFormatter()
/// The formatter logger.
internal weak var logger: Logger!
/// The formatter textual representation.
internal var description: String {
return String(format: format, arguments: components.map { (component: Component) -> CVarArg in
return String(describing: component).uppercased()
})
}
/**
Creates and returns a new formatter with the specified format and components.
- parameter format: The formatter format.
- parameter components: The formatter components.
- returns: A newly created formatter.
*/
public convenience init(_ format: String, _ components: Component...) {
self.init(format, components)
}
/**
Creates and returns a new formatter with the specified format and components.
- parameter format: The formatter format.
- parameter components: The formatter components.
- returns: A newly created formatter.
*/
public init(_ format: String, _ components: [Component]) {
self.format = format
self.components = components
}
/**
Formats a string with the formatter format and components.
- parameter level: The severity level.
- parameter items: The items to format.
- parameter separator: The separator between the items.
- parameter terminator: The terminator of the formatted string.
- parameter file: The log file path.
- parameter line: The log line number.
- parameter column: The log column number.
- parameter function: The log function.
- parameter date: The log date.
- returns: A formatted string.
*/
internal func format(level: Level, items: [Any], separator: String, terminator: String, file: String, line: Int, column: Int, function: String, date: Date) -> String {
let arguments = components.map { (component: Component) -> CVarArg in
switch component {
case .date(let dateFormat):
return format(date: date, dateFormat: dateFormat)
case .file(let fullPath, let fileExtension):
return format(file: file, fullPath: fullPath, fileExtension: fileExtension)
case .function:
return String(function)
case .line:
return String(line)
case .column:
return String(column)
case .level:
return format(level: level)
case .message:
return items.map({ String(describing: $0) }).joined(separator: separator)
case .location:
return format(file: file, line: line)
case .block(let block):
return block().flatMap({ String(describing: $0) }) ?? ""
}
}
return String(format: format, arguments: arguments) + terminator
}
/**
Formats a string with the formatter format and components.
- parameter description: The measure description.
- parameter average: The average time.
- parameter relativeStandardDeviation: The relative standard description.
- parameter file: The log file path.
- parameter line: The log line number.
- parameter column: The log column number.
- parameter function: The log function.
- parameter date: The log date.
- returns: A formatted string.
*/
func format(description: String?, average: Double, relativeStandardDeviation: Double, file: String, line: Int, column: Int, function: String, date: Date) -> String {
let arguments = components.map { (component: Component) -> CVarArg in
switch component {
case .date(let dateFormat):
return format(date: date, dateFormat: dateFormat)
case .file(let fullPath, let fileExtension):
return format(file: file, fullPath: fullPath, fileExtension: fileExtension)
case .function:
return String(function)
case .line:
return String(line)
case .column:
return String(column)
case .level:
return format(description: description)
case .message:
return format(average: average, relativeStandardDeviation: relativeStandardDeviation)
case .location:
return format(file: file, line: line)
case .block(let block):
return block().flatMap({ String(describing: $0) }) ?? ""
}
}
return String(format: format, arguments: arguments)
}
}
private extension Formatter {
/**
Formats a date with the specified date format.
- parameter date: The date.
- parameter dateFormat: The date format.
- returns: A formatted date.
*/
func format(date: Date, dateFormat: String) -> String {
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: date)
}
/**
Formats a file path with the specified parameters.
- parameter file: The file path.
- parameter fullPath: Whether the full path should be included.
- parameter fileExtension: Whether the file extension should be included.
- returns: A formatted file path.
*/
func format(file: String, fullPath: Bool, fileExtension: Bool) -> String {
var file = file
if !fullPath { file = file.lastPathComponent }
if !fileExtension { file = file.stringByDeletingPathExtension }
return file
}
/**
Formats a Location component with a specified file path and line number.
- parameter file: The file path.
- parameter line: The line number.
- returns: A formatted Location component.
*/
func format(file: String, line: Int) -> String {
return [
format(file: file, fullPath: false, fileExtension: true),
String(line)
].joined(separator: ":")
}
/**
Formats a Level component.
- parameter level: The Level component.
- returns: A formatted Level component.
*/
func format(level: Level) -> String {
let text = level.description
if let color = logger.theme?.colors[level] {
return text.withColor(color)
}
return text
}
/**
Formats a measure description.
- parameter description: The measure description.
- returns: A formatted measure description.
*/
func format(description: String?) -> String {
var text = "MEASURE"
if let color = logger.theme?.colors[.debug] {
text = text.withColor(color)
}
if let description = description {
text = "\(text) \(description)"
}
return text
}
/**
Formats an average time and a relative standard deviation.
- parameter average: The average time.
- parameter relativeStandardDeviation: The relative standard deviation.
- returns: A formatted average time and relative standard deviation.
*/
func format(average: Double, relativeStandardDeviation: Double) -> String {
let average = format(average: average)
let relativeStandardDeviation = format(relativeStandardDeviation: relativeStandardDeviation)
return "Time: \(average) sec (\(relativeStandardDeviation) STDEV)"
}
/**
Formats an average time.
- parameter average: An average time.
- returns: A formatted average time.
*/
func format(average: Double) -> String {
return String(format: "%.3f", average)
}
/**
Formats a list of durations.
- parameter durations: A list of durations.
- returns: A formatted list of durations.
*/
func format(durations: [Double]) -> String {
var format = Array(repeating: "%.6f", count: durations.count).joined(separator: ", ")
format = "[\(format)]"
return String(format: format, arguments: durations.map{ $0 as CVarArg })
}
/**
Formats a standard deviation.
- parameter standardDeviation: A standard deviation.
- returns: A formatted standard deviation.
*/
func format(standardDeviation: Double) -> String {
return String(format: "%.6f", standardDeviation)
}
/**
Formats a relative standard deviation.
- parameter relativeStandardDeviation: A relative standard deviation.
- returns: A formatted relative standard deviation.
*/
func format(relativeStandardDeviation: Double) -> String {
return String(format: "%.3f%%", relativeStandardDeviation)
}
}
| mit | 28f0c45a83b7cca7fc9951d5abedaf96 | 33.250794 | 171 | 0.606636 | 5.10601 | false | false | false | false |
TH-Brandenburg/University-Evaluation-iOS | EdL/TextQuestionViewController.swift | 1 | 11260 | //
// TextQuestionViewController.swift
// EdL
//
// Created by Daniel Weis on 19.06.16.
//
//
import UIKit
import ImageViewer
class TextQuestionViewController: UIViewController, UITextViewDelegate, UIPickerViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImageProvider {
var questionDTO: TextQuestionDTO!
var answerDTO: TextAnswerDTO!
var index: Int = -1
var localIndex: Int = -1
var imagePicker: UIImagePickerController!
var subscribedToKeyboardNotifications = false {
willSet(newValue) {
if newValue && !subscribedToKeyboardNotifications {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TextQuestionViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TextQuestionViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
} else if !newValue && subscribedToKeyboardNotifications {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
}
}
let bottomNavigationHeight = 50
var textFieldOffsetWithoutNavigationBar = 0
var textFieldOffset = false;
@IBOutlet weak var answerTextView: UITextView!
@IBOutlet weak var imageButton: UIButton!
@IBOutlet weak var imageStackView: UIStackView!
func takePhoto(sender: UIBarButtonItem) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func showPhoto(sender: UIButton) {
let buttonAssets = CloseButtonAssets(normal: UIImage(named:"ic_close_white")!, highlighted: UIImage(named: "ic_close_white")!)
let configuration = ImageViewerConfiguration(imageSize: CGSize(width: 10, height: 10), closeButtonAssets: buttonAssets)
let imageViewer = ImageViewer(imageProvider: self, configuration: configuration, displacedView: sender)
self.presentImageViewer(imageViewer)
}
@IBAction func deletePhoto(sender: UIButton) {
let fileMgr = NSFileManager()
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let dataPath = documentsPath.stringByAppendingPathComponent("images")
let imagePath = "\(dataPath)/\(answerDTO.questionID).jpg"
let thumbnailsPath = documentsPath.stringByAppendingPathComponent("thumbnails")
let thumbnailPath = "\(thumbnailsPath)/\(answerDTO.questionID).jpg"
_ = try? fileMgr.removeItemAtPath(imagePath)
_ = try? fileMgr.removeItemAtPath(thumbnailPath)
self.imageButton.setImage(nil, forState: .Normal)
loadPhoto()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
subscribedToKeyboardNotifications = true //refer to setter
//Question Text
if let questionTextView = self.view.viewWithTag(10) as? UITextView{
questionTextView.text = questionDTO.questionText
questionTextView.selectable = false // set to true in storyboard and changed back here to fix font size
}
self.loadPhoto()
if let answerTextView = self.view.viewWithTag(20) as? UITextView{
answerTextView.layer.cornerRadius = 5
answerTextView.layer.borderColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1).CGColor
answerTextView.layer.borderWidth = 1
answerTextView.delegate = self
if answerDTO.answerText != ""{
answerTextView.text = answerDTO.answerText
} else {
answerTextView.text = "Antwort eingeben..."
answerTextView.textColor = UIColor.lightGrayColor()
}
}
}
override func viewDidAppear(animated: Bool) {
let camera = UIBarButtonItem(barButtonSystemItem: .Camera,
target: self,
action: #selector(self.takePhoto(_:))
)
parentViewController!.parentViewController!.navigationItem.rightBarButtonItem = camera
}
override func viewWillDisappear(animated: Bool) {
// Remove NavBarButton for Camera, if exists
if ((parentViewController?.parentViewController?.navigationItem) != nil){
parentViewController!.parentViewController!.navigationItem.rightBarButtonItem = nil
}
subscribedToKeyboardNotifications = false //refer to setter
}
// MARK: - Text View Delegate
func textViewDidBeginEditing(textView: UITextView) {
if textView.text == "Antwort eingeben..." {
textView.text = ""
textView.textColor = UIColor.blackColor()
}
}
func textViewDidEndEditing(textView: UITextView) {
answerDTO.answerText = textView.text
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
textView.resignFirstResponder()
return false
}
return true
}
// MARK: - Image Picker View Delegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
let image1000 = Helper.resizeImage(image, newWidth: 1000)
let data = UIImageJPEGRepresentation(image1000, 0.8)
let image150 = Helper.resizeImage(image, newWidth: 150)
let thumbData = UIImageJPEGRepresentation(image150, 0.8)
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let dataPath = documentsPath.stringByAppendingPathComponent("images")
let thumbnailPath = documentsPath.stringByAppendingPathComponent("thumbnails")
do {
try NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
do {
try NSFileManager.defaultManager().createDirectoryAtPath(thumbnailPath, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
try data?.writeToFile("\(dataPath)/\(answerDTO.questionID).jpg", options: .DataWritingAtomic)
try thumbData?.writeToFile("\(thumbnailPath)/\(answerDTO.questionID).jpg", options: .DataWritingAtomic)
} catch let error as NSError {
print(error.localizedDescription);
}
print("Saved image!")
self.loadPhoto()
}
func loadPhoto(){
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let thumbnailPath = documentsPath.stringByAppendingPathComponent("thumbnails")
let imagePath = "\(thumbnailPath)/\(answerDTO.questionID).jpg"
let image = UIImage(contentsOfFile: imagePath)
if image != nil {
self.imageButton.setImage(image, forState: .Normal)
self.imageButton.imageView?.contentMode = .ScaleAspectFit
self.imageStackView.hidden = false
} else {
self.imageStackView.hidden = true
}
}
// MARK: - ImageProvider
func provideImage(completion: UIImage? -> Void){
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let imagesPath = documentsPath.stringByAppendingPathComponent("images")
let imagePath = "\(imagesPath)/\(answerDTO.questionID).jpg"
let image = UIImage(contentsOfFile: imagePath)
completion(image)
}
func provideImage(atIndex index: Int, completion: UIImage? -> Void) {
//not implemented, but required by ImageProvider protocol
completion(nil)
}
// MARK: - Keyboard related behavior
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
if textFieldOffset{
self.view.frame.origin.y -= keyboardSize.height - CGFloat(self.textFieldOffsetWithoutNavigationBar)
} else {
self.view.frame.origin.y -= keyboardSize.height - CGFloat(self.bottomNavigationHeight) - CGFloat(self.textFieldOffsetWithoutNavigationBar)
}
self.textFieldOffsetWithoutNavigationBar = Int(keyboardSize.height)
self.textFieldOffset = true
}
for view in self.parentViewController!.view.subviews {
if let subView = view as? UIScrollView {
subView.scrollEnabled = false
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
if textFieldOffset{
if keyboardSize.height == CGFloat(self.textFieldOffsetWithoutNavigationBar){
self.view.frame.origin.y += keyboardSize.height - CGFloat(self.bottomNavigationHeight)
self.textFieldOffsetWithoutNavigationBar = 0
textFieldOffset = false
} else {
self.view.frame.origin.y += CGFloat(self.textFieldOffsetWithoutNavigationBar) - keyboardSize.height
self.textFieldOffsetWithoutNavigationBar = Int(keyboardSize.height)
}
}
}
for view in self.parentViewController!.view.subviews {
if let subView = view as? UIScrollView {
subView.scrollEnabled = true
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 833a5a63be8693481d0ce38e30d3a480 | 39.649819 | 191 | 0.648934 | 5.747831 | false | false | false | false |
airspeedswift/swift | test/IRGen/prespecialized-metadata/struct-outmodule-frozen-1argument-1distinct_use-struct-outmodule-frozen-samemodule.swift | 3 | 1331 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-frozen-1argument.swift %S/Inputs/struct-public-frozen-0argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK-NOT: @"$s7Generic11OneArgumentVyAA7IntegerVGMN" =
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
import Generic
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s7Generic11OneArgumentVyAA7IntegerVGMD")
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture {{%[0-9]+}}, %swift.type* [[METADATA]])
// CHECK: }
func doit() {
consume( OneArgument(Integer(13)) )
}
doit()
| apache-2.0 | ae65d6f7b2bfe68e36cc42fa9442206e | 43.366667 | 345 | 0.706987 | 3.278325 | false | false | false | false |
jiamao130/DouYuSwift | DouYuBroad/DouYuBroad/Home/Controller/FunnyViewController.swift | 1 | 921 | //
// FunnyViewController.swift
// DouYuBroad
//
// Created by 贾卯 on 2017/8/14.
// Copyright © 2017年 贾卯. All rights reserved.
//
import UIKit
private let kTopMargin : CGFloat = 8
class FunnyViewController: BaseAnchorController {
fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel()
}
extension FunnyViewController{
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: 0, bottom: 0, right: 0)
}
}
extension FunnyViewController{
override func loadData() {
baseVM = funnyVM
funnyVM.loadFunnyData {
self.collectionView.reloadData()
self.loadDataFinished()
}
}
}
| mit | b04e8dcbcab132c7ae687e37681693e0 | 21.75 | 97 | 0.643956 | 4.892473 | false | false | false | false |
victorlesk/vilcore | Pod/Classes/MultiPicker.swift | 1 | 9317 | //
// MultiPicker.swift
// Pods
//
// Created by Victor Lesk on 26/10/2017.
//
import UIKit
public class MultiPicker: UIView, UIScrollViewDelegate{
public var delegate:MultiPickerDelegate?;
@objc public var originalView:UIView?
@objc var boolHasDoneButton = false;
@objc var doneButton:UIButton?;
@objc public var font:UIFont = UIFont.systemFont(ofSize: UIFont.smallSystemFontSize);
@objc public var boldFont:UIFont = UIFont.boldSystemFont(ofSize: UIFont.smallSystemFontSize);
@objc public var darkBackgroundColor = UIColor.black;
@objc public var midBackgroundColor = UIColor.lightGray;
@objc public var lightBackgroundColor = UIColor.white;
@objc public var darkTextColor = UIColor.black;
@objc public var lightTextColor = UIColor.white;
@objc var column1ElementHeight:CGFloat = 50;
@objc var itemLabels = [String:InsetLabel]();
@objc var scrollViews = [UIScrollView]();
@objc public var currentPickedItem:String?
@objc public var mainView:UIView;
@objc public var boolInitialScrollQueued = false;
required public init?(coder aDecoder: NSCoder) {
mainView = UIView(frame:CGRect(x: 0, y: 0, width: 0, height: 0));
super.init(coder: aDecoder);
}
override public init(frame: CGRect) {
mainView = UIView(frame:frame);
mainView.clipsToBounds = true;
super.init(frame:frame);
addSubview(mainView);
mainView.fillParent();
backgroundColor = UIColor.white.withAlphaComponent(0.7);
alpha=0.0;
}
@objc private func itemTapHandler(g:UITapGestureRecognizer){
guard let v = g.view else {return;}
for (_,label) in itemLabels{
if(label == v){
self.setNeedsLayout();
if(nil == doneButton){
delegate?.multiPicker(multiPicker: self, didReturnItem: 0, inColumn: 0);
}
return;
}
}
}
override public func layoutSubviews() {
super.layoutSubviews();
mainView.layer.borderColor = darkBackgroundColor.cgColor;
mainView.layer.borderWidth = 2.0;
guard let delegate = delegate else { return; }
let numberOfColumns = delegate.numberOfColumnsForMultiPicker(multiPicker: self);
if(scrollViews.count != numberOfColumns){
let columnWidth = CGFloat(mainView.frame.width/CGFloat(numberOfColumns));
for columnIndex in 0..<numberOfColumns{
let newScrollView = UIScrollView(frame:mainView.frame);
mainView.addSubview(newScrollView);
newScrollView.setWidth(columnWidth);
newScrollView.backgroundColor = lightBackgroundColor;
newScrollView.alignParentLeftBy(.moving, margin:columnWidth * CGFloat(columnIndex));
newScrollView.alignParentTopBy(.moving);
newScrollView.delegate = self;
scrollViews.append(newScrollView);
}
}
for (_,itemLabel) in itemLabels{
itemLabel.removeFromSuperview();
}
itemLabels.removeAll();
var lastView:UIView?
let baseHeight:CGFloat = 30;
for column in 0..<numberOfColumns{
let currentScrollView = scrollViews[column];
let itemCount = delegate.numberOfItemsInColumn(column, forMultiPicker: self);
lastView = nil;
for item in 0..<itemCount{
let newItemLabel = InsetLabel(frame:currentScrollView.frame);
currentScrollView.addSubview(newItemLabel);
newItemLabel.font = boldFont;
newItemLabel.text = delegate.multiPicker(multiPicker: self, textForItem: item, inColumn: column);
newItemLabel.textAlignment = .center;
newItemLabel.sizeToFit();
newItemLabel.stretchHorizontallyToFillParent();
newItemLabel.setHeight(delegate.multiPicker(multiPicker: self, heightFactorForItem: item, inColumn: column) * baseHeight);
if let lastView = lastView{
newItemLabel.moveToBelow(lastView);
}else{
newItemLabel.alignParentTopBy(.moving, margin:delegate.multiPicker(multiPicker: self, offsetForItem: 0, inColumn: column) * newItemLabel.frame.height);
}
let string = "\(column).\(item)";
itemLabels[string] = newItemLabel;
if( currentPickedItem == string){
newItemLabel.backgroundColor = darkBackgroundColor;
newItemLabel.textColor = lightTextColor;
}else{
newItemLabel.backgroundColor = lightBackgroundColor;
newItemLabel.textColor = darkTextColor;
}
newItemLabel.isUserInteractionEnabled = true;
newItemLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(itemLabelTapHandler(g:))));
lastView = newItemLabel;
}
currentScrollView.contentSize = CGSize(width: currentScrollView.frame.width, height: lastView!.frame.maxY);
}
var offset = CGPoint(x:0,y:( scrollViews[0].contentSize.height - scrollViews[0].frame.height ) / 2.0 );
if boolInitialScrollQueued{
if let pi = currentPickedItem, let label = itemLabels[pi]{
offset = CGPoint(x:0,y:label.frame.midY - ( scrollViews[0].frame.height / 2.0 ));
}
for scrollView in self.scrollViews{
scrollView.contentOffset = offset;
}
}
boolInitialScrollQueued = false;
mainView.hugChildren();
}
@objc public func show(){
guard let delegate=delegate else {return;}
self.removeFromSuperview();
let inView = delegate.multiPickerContainerView;
inView.addSubview(self);
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(cancelHandler(g:))));
mainView.isUserInteractionEnabled = true;
mainView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(cancelHandler(g:))));
if let originalView = originalView {
frame = originalView.frame ;
self.stretchUp(-(originalView.frame.size.height));
mainView.fillParent();
}
boolInitialScrollQueued = true;
UIView.animate(withDuration: 0.4, animations: {
self.fillParent();
self.mainView.alignParentTopBy(.moving, margin: self.originalView?.frame.maxY ?? 0.0);
self.mainView.stretchHorizontallyToFillParentWithMargin(inView.frame.width * 0.08);
self.mainView.setHeightOfParent(0.85);
self.alpha = 1.0;
}, completion: { (boolComplete) in
UIView.animate(withDuration: 0.15, animations: {
self.mainView.centreInParent();
});
});
}
@objc public func setStyle(font _font:UIFont,boldFont _boldFont:UIFont, darkBackgroundColor _darkBackgroundColor:UIColor, midBackgroundColor _midBackgroundColor:UIColor, lightBackgroundColor _lightBackgroundColor:UIColor, darkTextColor _darkTextColor:UIColor, lightTextColor _lightTextColor:UIColor,hasDoneButton _boolHasDoneButton:Bool){
font = _font;
boldFont = _boldFont;
darkBackgroundColor = _darkBackgroundColor;
midBackgroundColor = _midBackgroundColor;
lightBackgroundColor = _lightBackgroundColor;
darkTextColor = _darkTextColor;
lightTextColor = _lightTextColor;
boolHasDoneButton = _boolHasDoneButton;
}
@objc func cancelHandler(g:UIGestureRecognizer){
if(g.view == self){
delegate?.multiPickerCancelled(multiPicker: self);
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
for otherScrollView in scrollViews{
if(scrollView != otherScrollView){
otherScrollView.scrollTo(scrollView.contentOffset);
}
}
}
@objc func itemLabelTapHandler(g _g:UITapGestureRecognizer){
guard let v = _g.view else {return;}
for (itemString,itemLabel) in itemLabels{
if(v == itemLabel){
currentPickedItem = itemString;
let components:[String] = currentPickedItem?.split(".") ?? ["-1","-1"];
delegate?.multiPicker(multiPicker: self, didReturnItem: Int(components[1]) ?? -1, inColumn: Int(components[0]) ?? -1)
return;
}
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| mit | ce5a2bf237828fdcd9dc18a10cd37a2d | 36.268 | 342 | 0.599549 | 5.254935 | false | false | false | false |
inamiy/ReactiveCocoaCatalog | ReactiveCocoaCatalog/Samples/MenuCustomViewController.swift | 1 | 1607 | //
// MenuCustomViewController.swift
// ReactiveCocoaCatalog
//
// Created by Yasuhiro Inami on 2016-04-09.
// Copyright © 2016 Yasuhiro Inami. All rights reserved.
//
import UIKit
import Result
import ReactiveSwift
import FontAwesome
final class MenuCustomViewController: UIViewController, StoryboardSceneProvider
{
static let storyboardScene = StoryboardScene<MenuCustomViewController>(name: "MenuBadge")
@IBOutlet weak var mainLabel: UILabel?
@IBOutlet weak var subLabel: UILabel?
@IBOutlet weak var updateButton: UIButton?
weak var menu: CustomMenu?
override func viewDidLoad()
{
super.viewDidLoad()
guard let menu = self.menu, let mainLabel = self.mainLabel, let subLabel = self.subLabel, let updateButton = self.updateButton else
{
fatalError("Required properties are not set.")
}
mainLabel.font = UIFont.fontAwesome(ofSize: mainLabel.font.pointSize)
mainLabel.reactive.text
<~ menu.title.producer
.map { [unowned menu] title -> String in
let fontAwesome = menu.menuId.fontAwesome
var title2 = String.fontAwesomeIcon(name: fontAwesome)
title2.append(" \(title)")
return title2
}
subLabel.reactive.text
<~ menu.badge.producer
.map { "Badge: \($0)" }
BadgeManager.badges[menu.menuId]
<~ updateButton.reactive.controlEvents(.touchUpInside)
.map { _ in Badge(rawValue: Badge.randomBadgeString()) }
}
}
| mit | 2ef3dd6323f1b56e8e8c63423d782fe8 | 29.884615 | 139 | 0.635118 | 4.92638 | false | false | false | false |
mrchenhao/VPNOn | VPNOnKit/VPNManager+Domains.swift | 1 | 2714 | //
// VPNManager+Domains.swift
// VPNOn
//
// Created by Lex Tang on 1/29/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
let kOnDemandKey = "onDemand"
let kOnDemandDomainsKey = "onDemandDomains"
extension VPNManager
{
public var onDemand: Bool {
get {
if let onDemandObject = _defaults.objectForKey(kOnDemandKey) as NSNumber? {
if onDemandObject.isKindOfClass(NSNumber.self) {
return onDemandObject.boolValue
}
}
return false
}
set {
_defaults.setObject(NSNumber(bool: newValue), forKey: kOnDemandKey)
_defaults.synchronize()
}
}
public var onDemandDomains: String? {
get {
if let domainsObject = _defaults.stringForKey(kOnDemandDomainsKey) {
return domainsObject
}
return .None
}
set {
if newValue == nil {
_defaults.removeObjectForKey(kOnDemandDomainsKey)
} else {
_defaults.setObject(newValue, forKey: kOnDemandDomainsKey)
}
_defaults.synchronize()
}
}
public var onDemandDomainsArray: [String] {
get {
return self.domainsInString(onDemandDomains ?? "")
}
}
public func domainsInString(string: String) -> [String] {
let s = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if s.isEmpty {
return [String]()
}
var domains = s.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) as [String]
var wildCardDomains = [String]()
if domains.count > 1 {
if domains[domains.count - 1].isEmpty {
domains.removeAtIndex(domains.count - 1)
}
for domain in domains {
wildCardDomains.append(domain)
if domain.rangeOfString("*.") == nil {
wildCardDomains.append("*.\(domain)")
}
}
}
return uniq(wildCardDomains)
}
// See: http://stackoverflow.com/questions/25738817/does-there-exist-within-swifts-api-an-easy-way-to-remove-duplicate-elements-fro
private func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] {
var buffer = Array<T>()
var addedDict = [T: Bool]()
for elem in source {
if addedDict[elem] == nil {
addedDict[elem] = true
buffer.append(elem)
}
}
return buffer
}
}
| mit | d2313195ffda695141b2c0cf49094b3c | 29.840909 | 135 | 0.554164 | 4.786596 | false | false | false | false |
caobo56/Juyou | JuYou/JuYou/Home/VIew/IsHotCell.swift | 1 | 4463 | //
// IsHotCell.swift
// JuYou
//
// Created by caobo56 on 16/5/19.
// Copyright © 2016年 caobo56. All rights reserved.
//
import UIKit
class IsHotCell: UITableViewCell {
//MARK: - property 属性
var imageV: UIImageView? = UIImageView.init()
var monthPriceLable:UILabel? = UILabel.init()
var titleLable: UILabel? = UILabel.init()
var totalPrice:UILabel? = UILabel.init()
var travel_dateLable:UILabel? = UILabel.init()
var team_typeLable:UILabel? = UILabel.init()
//MARK: - View Lifecycle (View 的生命周期)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Custom Accessors (自定义访问器)
func initUI(){
self.setSize(CGSizeMake(IsHotsCellW,IsHotsCellH))
self.selectionStyle = UITableViewCellSelectionStyle.None
self.addSubview(self.imageV!)
self.imageV?.setSize(CGSizeMake(IsHotsCellW,IsHotsCellH-62))
self.imageV?.setOrigin(CGPointMake(0, 0))
self.addSubview(self.monthPriceLable!)
self.monthPriceLable?.setSize(CGSizeMake(70,20))
self.monthPriceLable?.setRight(10)
self.monthPriceLable?.setTop(10)
self.monthPriceLable?.backgroundColor = UIColorWithHex(0xFF7F05,alpha: 1.0)
self.monthPriceLable?.textColor = UIColor.whiteColor()
self.monthPriceLable?.font = UIFont.systemFontOfSize(12)
self.monthPriceLable?.textAlignment = NSTextAlignment.Center
self.monthPriceLable?.setRoundedCorner(1)
self.addSubview(self.travel_dateLable!)
self.travel_dateLable?.setSize(CGSizeMake(200, 20))
self.travel_dateLable?.setRight(10)
self.travel_dateLable?.setBottom(10)
self.travel_dateLable?.textColor = UIColorWithHex(0xA5A5A5, alpha: 1.0)
self.travel_dateLable?.font = UIFont.systemFontOfSize(12)
self.travel_dateLable?.textAlignment = NSTextAlignment.Right
let totalName:UILabel = UILabel.init()
self.addSubview(totalName)
totalName.setSize(CGSizeMake(40, 20))
totalName.setLeft(10)
totalName.setBottom(10)
totalName.textColor = UIColorWithHex(0xA5A5A5, alpha: 1.0)
totalName.font = UIFont.systemFontOfSize(12)
totalName.textAlignment = NSTextAlignment.Left
totalName.text = "总价:"
self.addSubview(self.totalPrice!)
self.totalPrice?.setSize(CGSizeMake(70, 20))
self.totalPrice?.setLeft(totalName.right)
self.totalPrice?.setBottom(10)
self.totalPrice?.textColor = UIColorWithHex(0xFF7F05, alpha: 1.0)
self.totalPrice?.font = UIFont.systemFontOfSize(12)
self.totalPrice?.textAlignment = NSTextAlignment.Left
self.addSubview(self.team_typeLable!)
self.team_typeLable?.setSize(CGSizeMake(70, 25))
self.team_typeLable?.setLeft(totalName.left)
self.team_typeLable?.setTop((self.imageV?.bottom)!+6)
self.team_typeLable?.textColor = UIColorWithHex(0x007dc6, alpha: 1.0)
self.team_typeLable?.font = UIFont.systemFontOfSize(12)
self.team_typeLable?.setborderWidthAndColor(1, borderColor: lightBlueColor())
self.team_typeLable?.textAlignment = NSTextAlignment.Center
self.team_typeLable?.setRoundedCorner(3)
self.team_typeLable?.text = "自由行"
self.addSubview(self.titleLable!)
let titleLableW = (Screen_weight-(self.team_typeLable?.right)!-5)
self.titleLable?.setSize(CGSizeMake(titleLableW,30))
self.titleLable?.setLeft((self.team_typeLable?.right)!+5)
self.titleLable!.setCenterY((self.team_typeLable?.centerY)!)
self.titleLable?.textColor = UIColor.darkTextColor()
self.titleLable?.textAlignment = NSTextAlignment.Left
self.titleLable?.font = UIFont.systemFontOfSize(14)
}
func loadData(fits:Filterfreedom){
self.imageV!.sd_setImageWithURL(NSURL(string: fits.pic!))
self.monthPriceLable?.text = ("月付"+String(fits.monthPrice)+"元")
self.travel_dateLable?.text = fits.travel_date
self.totalPrice?.text = ("¥"+String(fits.price))
self.titleLable?.text = fits.title
}
}
| apache-2.0 | 70f89c69560338a93b715aee8106baca | 39.063636 | 85 | 0.670524 | 3.988235 | false | false | false | false |
mownier/photostream | Photostream/Services/Models/Photo.swift | 1 | 957 | //
// Photo.swift
// Photostream
//
// Created by Mounir Ybanez on 17/08/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import Foundation
import Firebase
struct Photo {
var url: String
var width: Int
var height: Int
init() {
url = ""
width = 0
height = 0
}
}
extension Photo: SnapshotParser {
init(with snapshot: DataSnapshot, exception: String...) {
self.init()
if snapshot.hasChild("url") && !exception.contains("url") {
url = snapshot.childSnapshot(forPath: "url").value as! String
}
if snapshot.hasChild("width") && !exception.contains("width") {
width = snapshot.childSnapshot(forPath: "width").value as! Int
}
if snapshot.hasChild("height") && !exception.contains("height") {
height = snapshot.childSnapshot(forPath: "height").value as! Int
}
}
}
| mit | b1886a8f712e2ba404fb2fab06be8eeb | 21.761905 | 76 | 0.572176 | 4.192982 | false | false | false | false |
Geor9eLau/WorkHelper | Carthage/Checkouts/SwiftCharts/SwiftCharts/Layers/ChartPointsAreaLayer.swift | 1 | 1521 | //
// ChartPointsAreaLayer.swift
// swiftCharts
//
// Created by ischuetz on 15/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartPointsAreaLayer<T: ChartPoint>: ChartPointsLayer<T> {
fileprivate let areaColor: UIColor
fileprivate let animDuration: Float
fileprivate let animDelay: Float
fileprivate let addContainerPoints: Bool
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], areaColor: UIColor, animDuration: Float, animDelay: Float, addContainerPoints: Bool) {
self.areaColor = areaColor
self.animDuration = animDuration
self.animDelay = animDelay
self.addContainerPoints = addContainerPoints
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints)
}
override func display(chart: Chart) {
var points = self.chartPointScreenLocs
let origin = self.innerFrame.origin
let xLength = self.innerFrame.width
let bottomY = origin.y + self.innerFrame.height
if self.addContainerPoints {
points.append(CGPoint(x: origin.x + xLength, y: bottomY))
points.append(CGPoint(x: origin.x, y: bottomY))
}
let areaView = ChartAreasView(points: points, frame: chart.bounds, color: self.areaColor, animDuration: self.animDuration, animDelay: self.animDelay)
chart.addSubview(areaView)
}
}
| mit | 64829059550863f9e117b26ea2805be6 | 34.372093 | 186 | 0.674556 | 4.5 | false | false | false | false |
miller-ms/ViewAnimator | ViewAnimator/SpringAnimationCell.swift | 1 | 4576 | //
// AnimationCell.swift
// ViewAnimator
//
// Created by William Miller DBA Miller Mobilesoft on 5/22/17.
//
// This application is intended to be a developer tool for evaluating the
// options for creating an animation or transition using the UIView static
// methods UIView.animate and UIView.transition.
// Copyright © 2017 William Miller DBA Miller Mobilesoft
//
// 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/>.
//
// If you would like to reach the developer you may email me at
// [email protected] or visit my website at
// http://millermobilesoft.com
//
import UIKit
class SpringAnimationCell: UITableViewCell {
@IBOutlet weak var stopView: UIView!
@IBOutlet weak var startView: UIView!
@IBOutlet weak var moveObjectView: UIImageView!
@IBOutlet weak var animateBtn: UIButton!
@IBOutlet weak var colorView: UIView!
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
}
func reset() {
stopView.isHidden = false
startView.isHidden = false
moveObjectView.isHidden = true
colorView.isHidden = true
colorView.layer.removeAllAnimations()
imageView?.layer.removeAllAnimations()
}
func executeAnimation(withDuration duration:Double, andDelay delay:Double, usingSpringwithDamping damping:CGFloat, withInitialSpringVelocity velocity:CGFloat, animationOptions options:UIViewAnimationOptions, animationProperties properties:PropertiesModel) -> Void {
// Make the animation view visible and hide the start and stop views.
colorView.isHidden = false
startView.isHidden = true
stopView.isHidden = true
// disable the animate button
animateBtn.isEnabled = false
/* position the start of the animation view and its final resting place based on the direction of the animation.
*/
colorView.transform = CGAffineTransform.identity
colorView.frame = startView.frame
var finalFrame = stopView.frame
finalFrame.size = properties.applyMulitiplier(toSize: self.colorView.frame.size)
switch properties.animationVector {
case .leftToRight:
finalFrame.origin.x = stopView.frame.origin.x + stopView.frame.width - finalFrame.width
case .rightToLeft:
colorView.frame = stopView.frame
finalFrame.origin = startView.frame.origin
case .still:
var centerPt = stopView.center
centerPt.x = (self.frame.width + colorView.frame.width) / 2
colorView.center = centerPt
finalFrame.origin = colorView.frame.origin
}
// initialize the starting color of the animation view.
colorView.backgroundColor = properties.startBackgroundColor
colorView.alpha = CGFloat(properties.startBackgroundAlpha)
UIView.animate(withDuration: duration,
delay: delay,
usingSpringWithDamping: damping,
initialSpringVelocity: velocity,
options: options,
animations: { () in
self.colorView.frame = finalFrame
self.colorView.backgroundColor = properties.endBackgroundColor
self.colorView.alpha = CGFloat(properties.endBackgroundAlpha)
self.colorView.transform = properties.affineTransform
},
completion: { (isDone:Bool) in
self.animateBtn.isEnabled = true
}
)
}
}
| gpl-3.0 | 9d7ad388df05bc3409a0e72b791c8a5b | 36.809917 | 269 | 0.641093 | 5.169492 | false | false | false | false |
phimage/MomXML | Sources/FromXML/MomRelationship+XMLObject.swift | 1 | 1750 | // Created by Eric Marchand on 07/06/2017.
// Copyright © 2017 Eric Marchand. All rights reserved.
//
import Foundation
extension MomRelationship: XMLObject {
public init?(xml: XML) {
guard let element = xml.element, element.name == "relationship" else {
return nil
}
guard let name = element.attribute(by: "name")?.text,
let destinationEntity = element.attribute(by: "destinationEntity")?.text else {
return nil
}
self.init(name: name, destinationEntity: destinationEntity)
self.syncable = xml.element?.attribute(by: "syncable")?.text.fromXMLToBool ?? false
self.isOptional = xml.element?.attribute(by: "optional")?.text.fromXMLToBool ?? false
self.isToMany = xml.element?.attribute(by: "toMany")?.text.fromXMLToBool ?? false
self.isOrdered = xml.element?.attribute(by: "ordered")?.text.fromXMLToBool ?? false
self.isTransient = xml.element?.attribute(by: "transient")?.text.fromXMLToBool ?? false
if let text = xml.element?.attribute(by: "deletionRule")?.text, let rule = DeletionRule(rawValue: text) {
self.deletionRule = rule
}
self.maxCount = xml.element?.attribute(by: "maxCount")?.text.fromXMLToInt
self.minCount = xml.element?.attribute(by: "minCount")?.text.fromXMLToInt
self.inverseName = xml.element?.attribute(by: "inverseName")?.text
self.inverseEntity = xml.element?.attribute(by: "inverseEntity")?.text
for xml in xml.children {
if let object = MomUserInfo(xml: xml) {
userInfo = object
} else {
MomXML.orphanCallback?(xml, MomUserInfo.self)
}
}
}
}
| mit | 7ed4b19612227e5541279a13ffaea360 | 37.866667 | 113 | 0.627787 | 4.234867 | false | false | false | false |
gregomni/swift | test/decl/protocol/recursive_requirement.swift | 1 | 2231 | // RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on
// -----
protocol Foo {
associatedtype Bar : Foo
}
struct Oroborous : Foo {
typealias Bar = Oroborous
}
// -----
protocol P {
associatedtype A : P
}
struct X<T: P> {
}
func f<T : P>(_ z: T) {
_ = X<T.A>()
}
// -----
protocol PP2 {
associatedtype A : P2 = Self
}
protocol P2 : PP2 {
associatedtype A = Self
}
struct X2<T: P2> {
}
struct Y2 : P2 {
typealias A = Y2
}
func f<T : P2>(_ z: T) {
_ = X2<T.A>()
}
// -----
protocol P3 {
associatedtype A: P4 = Self
}
protocol P4 : P3 {}
protocol DeclaredP : P3, // expected-warning{{redundant conformance constraint 'Self' : 'P3'}}
P4 {}
struct Y3 : DeclaredP {
}
struct X3<T:P4> {}
func f2<T:P4>(_ a: T) {
_ = X3<T.A>()
}
f2(Y3())
// -----
protocol Alpha {
associatedtype Beta: Gamma
}
protocol Gamma {
associatedtype Delta: Alpha
}
struct Epsilon<T: Alpha,
U: Gamma> // expected-warning{{redundant conformance constraint 'U' : 'Gamma'}}
where T.Beta == U,
U.Delta == T {}
// -----
protocol AsExistentialA {
var delegate : AsExistentialB? { get }
}
protocol AsExistentialB {
func aMethod(_ object : AsExistentialA)
}
protocol AsExistentialAssocTypeA {
var delegate : AsExistentialAssocTypeB? { get } // expected-warning {{use of protocol 'AsExistentialAssocTypeB' as a type must be written 'any AsExistentialAssocTypeB'}}
}
protocol AsExistentialAssocTypeB {
func aMethod(_ object : AsExistentialAssocTypeA)
associatedtype Bar
}
protocol AsExistentialAssocTypeAgainA {
var delegate : AsExistentialAssocTypeAgainB? { get }
associatedtype Bar
}
protocol AsExistentialAssocTypeAgainB {
func aMethod(_ object : AsExistentialAssocTypeAgainA) // expected-warning {{use of protocol 'AsExistentialAssocTypeAgainA' as a type must be written 'any AsExistentialAssocTypeAgainA'}}
}
// SR-547
protocol A {
associatedtype B1: B
associatedtype C1: C
mutating func addObserver(_ observer: B1, forProperty: C1)
}
protocol C {
}
protocol B {
associatedtype BA: A
associatedtype BC: C
func observeChangeOfProperty(_ property: BC, observable: BA)
}
| apache-2.0 | b3bc0b8d60115cc413605bc16489cbf3 | 16.706349 | 187 | 0.670103 | 3.427035 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Location/LocationSendViewController.swift | 1 | 3637 | //
// Wire
// Copyright (C) 2016 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 UIKit
import WireCommonComponents
protocol LocationSendViewControllerDelegate: AnyObject {
func locationSendViewControllerSendButtonTapped(_ viewController: LocationSendViewController)
}
final class LocationSendViewController: UIViewController {
let sendButton = Button(style: .accentColorTextButtonStyle, cornerRadius: 12, fontSpec: .normalSemiboldFont)
let addressLabel: UILabel = {
let label = DynamicFontLabel(fontSpec: FontSpec.normalFont, color: SemanticColors.Label.textDefault)
label.numberOfLines = 0
return label
}()
private let containerView = UIView()
weak var delegate: LocationSendViewControllerDelegate?
var address: String? {
didSet {
addressLabel.text = address
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureViews()
createConstraints()
view.backgroundColor = SemanticColors.View.backgroundDefault
}
fileprivate func configureViews() {
sendButton.setTitle("location.send_button.title".localized, for: [])
sendButton.addTarget(self, action: #selector(sendButtonTapped), for: .touchUpInside)
sendButton.accessibilityIdentifier = "sendLocation"
addressLabel.accessibilityIdentifier = "selectedAddress"
view.addSubview(containerView)
[addressLabel, sendButton].forEach(containerView.addSubview)
}
private func createConstraints() {
[containerView, addressLabel, sendButton].prepareForLayout()
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: view.topAnchor),
containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
containerView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 12),
containerView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -12),
addressLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
addressLabel.trailingAnchor.constraint(lessThanOrEqualTo: sendButton.leadingAnchor, constant: -12),
addressLabel.topAnchor.constraint(equalTo: containerView.topAnchor),
addressLabel.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -UIScreen.safeArea.bottom),
sendButton.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
sendButton.centerYAnchor.constraint(equalTo: addressLabel.centerYAnchor),
sendButton.heightAnchor.constraint(equalToConstant: 28)
])
sendButton.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
addressLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 750), for: .horizontal)
}
@objc
private func sendButtonTapped(_ sender: LegacyButton) {
delegate?.locationSendViewControllerSendButtonTapped(self)
}
}
| gpl-3.0 | ba2f2c25b784cfe286cff3995e8f18a7 | 40.804598 | 123 | 0.732197 | 5.388148 | false | false | false | false |
gregomni/swift | test/SILOptimizer/move_function_kills_copyable_loadable_vars.swift | 4 | 20294 | // RUN: %target-swift-frontend -enable-experimental-move-only -verify %s -parse-stdlib -emit-sil -o /dev/null
// REQUIRES: optimized_stdlib
import Swift
//////////////////
// Declarations //
//////////////////
public class Klass {
var k: Klass? = nil
func getOtherKlass() -> Klass? { nil }
}
public class SubKlass1 : Klass {}
public class SubKlass2 : Klass {}
struct KlassWrapper {
var k: Klass
}
func consumingUse(_ k: __owned Klass) {}
var booleanValue: Bool { false }
var booleanValue2: Bool { false }
func nonConsumingUse(_ k: Klass) {}
func exchangeUse(_ k: Klass) -> Klass { k }
///////////
// Tests //
///////////
public func performMoveOnVarSingleBlock(_ p: Klass) {
var x = p
let _ = _move(x)
x = p
nonConsumingUse(x)
}
public func performMoveOnVarSingleBlockError(_ p: Klass) {
var x = p // expected-error {{'x' used after being moved}}
let _ = _move(x) // expected-note {{move here}}
nonConsumingUse(x) // expected-note {{use here}}
x = p
nonConsumingUse(x)
}
public func performMoveOnVarMultiBlock(_ p: Klass) {
var x = p
let _ = _move(x)
while booleanValue {
print("true")
}
while booleanValue {
print("true")
}
x = p
nonConsumingUse(x)
}
public func performMoveOnVarMultiBlockError1(_ p: Klass) {
var x = p // expected-error {{'x' used after being moved}}
let _ = _move(x) // expected-note {{move here}}
nonConsumingUse(x) // expected-note {{use here}}
while booleanValue {
print("true")
}
// We only emit an error on the first one.
nonConsumingUse(x)
while booleanValue {
print("true")
}
// We only emit an error on the first one.
nonConsumingUse(x)
x = p
nonConsumingUse(x)
}
public func performMoveOnVarMultiBlockError2(_ p: Klass) {
var x = p // expected-error {{'x' used after being moved}}
let _ = _move(x) // expected-note {{move here}}
while booleanValue {
print("true")
}
nonConsumingUse(x) // expected-note {{use here}}
while booleanValue {
print("true")
}
// We only error on the first one.
nonConsumingUse(x)
x = p
nonConsumingUse(x)
}
public func performMoveConditionalReinitalization(_ p: Klass) {
var x = p
if booleanValue {
nonConsumingUse(x)
let _ = _move(x)
x = p
nonConsumingUse(x)
} else {
nonConsumingUse(x)
}
nonConsumingUse(x)
}
public func performMoveConditionalReinitalization2(_ p: Klass) {
var x = p // expected-error {{'x' used after being moved}}
if booleanValue {
nonConsumingUse(x)
let _ = _move(x) // expected-note {{move here}}
nonConsumingUse(x) // expected-note {{use here}}
x = p
nonConsumingUse(x)
} else {
nonConsumingUse(x)
}
nonConsumingUse(x)
}
public func performMoveConditionalReinitalization3(_ p: Klass, _ p2: Klass, _ p3: Klass) {
var x = p // expected-error {{'x' used after being moved}}
// expected-error @-1 {{'x' used after being moved}}
if booleanValue {
nonConsumingUse(x)
let _ = _move(x) // expected-note {{move here}}
nonConsumingUse(x) // expected-note {{use here}}
nonConsumingUse(x) // We only emit for the first one.
x = p2
nonConsumingUse(x)
let _ = _move(x) // expected-note {{move here}}
nonConsumingUse(x) // expected-note {{use here}}
} else {
nonConsumingUse(x)
}
nonConsumingUse(x)
}
// Even though the examples below are for lets, since the let is not initially
// defined it comes out like a var.
public func performMoveOnLaterDefinedInit(_ p: Klass) {
let x: Klass // expected-error {{'x' used after being moved}}
do {
x = p
}
let _ = _move(x) // expected-note {{move here}}
nonConsumingUse(x) // expected-note {{use here}}
}
public func performMoveOnLaterDefinedInit2(_ p: Klass) {
let x: Klass
do {
x = p
}
nonConsumingUse(x)
let _ = _move(x)
}
public func performMoveOnInOut(_ p: inout Klass) { // expected-error {{'p' used after being moved}}
let buf = _move(p) // expected-note {{move here}}
let _ = buf
} // expected-note {{use here}}
public func performMoveOnInOut2(_ p: inout Klass, _ p2: Klass) {
let buf = _move(p)
p = p2
let _ = buf
}
// Mutating self is an inout argument.
struct S {
var buffer: Klass?
mutating func appendNoError() {
let b = _move(self).buffer!
let maybeNewB = exchangeUse(b)
self = .init(buffer: maybeNewB)
}
mutating func appendError() { // expected-error {{'self' used after being moved}}
let b = _move(self).buffer // expected-note {{move here}}
let _ = b
} // expected-note {{use here}}
mutating func appendThrowingNoError1(_ f: () throws -> ()) throws {
let b = _move(self).buffer!
let maybeNewB = exchangeUse(b)
// We have to initialize self before we call try since otherwise we will
// not initialize self along the throws path.
self = .init(buffer: maybeNewB)
try f()
}
mutating func appendThrowingNoError2(_ f: () throws -> ()) {
do {
let b = _move(self).buffer!
try f()
let maybeNewB = exchangeUse(b)
self = .init(buffer: maybeNewB)
} catch {
self = .init(buffer: nil)
}
}
// In this case, since we initialize self before the try point, we will have
// re-initialized self before hitting either the code after the try that is
// inline or the catch block.
mutating func appendThrowingNoError3(_ f: () throws -> ()) {
do {
let b = _move(self).buffer!
let maybeNewB = exchangeUse(b)
self = .init(buffer: maybeNewB)
try f()
} catch {
}
}
mutating func appendThrowingError0(_ f: () throws -> ()) throws { // expected-error {{'self' used after being moved}}
let b = _move(self).buffer! // expected-note {{move here}}
let maybeNewB = exchangeUse(b)
try f() // expected-note {{use here}}
self = .init(buffer: maybeNewB)
}
mutating func appendThrowingError1(_ f: () throws -> ()) throws { // expected-error {{'self' used after being moved}}
let b = _move(self).buffer! // expected-note {{move here}}
let maybeNewB = exchangeUse(b)
let _ = maybeNewB
try f() // expected-note {{use here}}
}
mutating func appendThrowingError2(_ f: () throws -> ()) { // expected-error {{'self' used after being moved}}
do {
let b = _move(self).buffer // expected-note {{move here}}
let _ = b
try f()
} catch {
self = .init(buffer: nil)
}
} // expected-note {{use here}}
mutating func appendThrowingError3(_ f: () throws -> ()) { // expected-error {{'self' used after being moved}}
do {
let b = _move(self).buffer! // expected-note {{move here}}
try f()
let maybeNewB = exchangeUse(b)
self = .init(buffer: maybeNewB)
} catch {
}
} // expected-note {{use here}}
mutating func appendThrowingError4(_ f: () throws -> ()) { // expected-error {{'self' used after being moved}}
do {
let b = _move(self).buffer // expected-note {{move here}}
let _ = b
try f()
} catch {
}
} // expected-note {{use here}}
}
/////////////////
// Defer Tests //
/////////////////
extension KlassWrapper {
mutating func deferTestSuccess1() {
let _ = _move(self)
defer {
self = KlassWrapper(k: Klass())
}
print("123")
}
// Make sure we can init/reinit self multiple times without error.
mutating func deferTestSuccess2() {
let _ = _move(self)
self = KlassWrapper(k: Klass())
let _ = _move(self)
defer {
self = KlassWrapper(k: Klass())
}
print("123")
}
mutating func deferTestSuccess3() {
let _ = _move(self)
defer {
self = KlassWrapper(k: Klass())
}
defer {
self = KlassWrapper(k: Klass())
}
print("123")
}
// We do not support moving within a defer right now.
mutating func deferTestFail1() {
let _ = _move(self)
defer {
self = KlassWrapper(k: Klass())
let _ = _move(self) // expected-error {{_move applied to value that the compiler does not support checking}}
}
print("123")
}
// We do not support moving within a defer right now.
mutating func deferTestFail2() { // expected-error {{'self' used after being moved}}
let _ = _move(self) // expected-note {{move here}}
defer {
nonConsumingUse(k) // expected-note {{use here}}
self = KlassWrapper(k: Klass())
}
print("123")
}
mutating func deferTestFail3() { // expected-error {{'self' used after being moved}}
let _ = _move(self) // expected-note {{move here}}
nonConsumingUse(k) // expected-note {{use here}}
defer {
nonConsumingUse(k)
self = KlassWrapper(k: Klass())
}
print("123")
}
mutating func deferTestFail4() { // expected-error {{'self' used after being moved}}
let _ = _move(self) // expected-note {{move here}}
defer {
consumingUse(k) // expected-note {{use here}}
self = KlassWrapper(k: Klass())
}
print("123")
}
// TODO: We should definitely be erroring on consuming use I think.
mutating func deferTestFail5() { // expected-error {{'self' used after being moved}}
let _ = _move(self) // expected-note {{move here}}
for _ in 0..<1024 {
defer {
consumingUse(k)
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
print("123")
} // expected-note {{use here}}
// TODO: We should be erroring on nonConsumingUse rather than the end of
// scope use.
//
mutating func deferTestFail6() { // expected-error {{'self' used after being moved}}
let _ = _move(self) // expected-note {{move here}}
for _ in 0..<1024 {
defer {
nonConsumingUse(k)
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
print("123")
} // expected-note {{use here}}
mutating func deferTestFail7() { // expected-error {{'self' used after being moved}}
for _ in 0..<1024 {
let _ = _move(self) // expected-note {{move here}}
defer {
nonConsumingUse(k) // expected-note {{use here}}
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
print("123")
}
mutating func deferTestFail8() { // expected-error {{'self' used after being moved}}
let _ = _move(self) // expected-note {{move here}}
defer {
if booleanValue {
nonConsumingUse(k) // expected-note {{use here}}
}
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
mutating func deferTestFail9() { // expected-error {{'self' used after being moved}}
let _ = _move(self) // expected-note {{move here}}
defer {
if booleanValue {
nonConsumingUse(k) // expected-note {{use here}}
} else {
nonConsumingUse(k)
}
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
mutating func deferTestFail10() { // expected-error {{'self' used after being moved}}
let _ = _move(self) // expected-note {{move here}}
defer {
for _ in 0..<1024 {
nonConsumingUse(k) // expected-note {{use here}}
}
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
mutating func deferTestFail11() { // expected-error {{'self' used after being moved}}
let _ = _move(self) // expected-note {{move here}}
if booleanValue {
print("creating blocks")
} else {
print("creating blocks2")
}
defer {
for _ in 0..<1024 {
nonConsumingUse(k) // expected-note {{use here}}
}
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
mutating func deferTestFail12() { // expected-error {{'self' used after being moved}}
if booleanValue {
print("creating blocks")
} else {
let _ = _move(self) // expected-note {{move here}}
print("creating blocks2")
}
defer {
for _ in 0..<1024 {
nonConsumingUse(k) // expected-note {{use here}}
}
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
mutating func deferTestSuccess13() {
if booleanValue {
print("creating blocks")
} else {
let _ = _move(self)
print("creating blocks2")
}
defer {
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
mutating func deferTestSuccess14() {
if booleanValue {
print("creating blocks")
self.doSomething()
} else {
let _ = _move(self)
print("creating blocks2")
}
defer {
self = KlassWrapper(k: Klass())
}
print("foo bar")
}
}
////////////////
// Cast Tests //
////////////////
public func castTest0(_ x: __owned SubKlass1) -> Klass {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
return x2 as Klass // expected-note {{use here}}
}
public func castTest1(_ x: __owned Klass) -> SubKlass1 {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
return x2 as! SubKlass1 // expected-note {{use here}}
}
public func castTest2(_ x: __owned Klass) -> SubKlass1? {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
return x2 as? SubKlass1 // expected-note {{use here}}
}
public func castTestSwitch1(_ x : __owned Klass) {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
switch x2 { // expected-note {{use here}}
case let k as SubKlass1:
print(k)
default:
print("Nope")
}
}
public func castTestSwitch2(_ x : __owned Klass) {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
switch x2 { // expected-note {{use here}}
case let k as SubKlass1:
print(k)
case let k as SubKlass2:
print(k)
default:
print("Nope")
}
}
public func castTestSwitchInLoop(_ x : __owned Klass) {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
for _ in 0..<1024 {
switch x2 { // expected-note {{use here}}
case let k as SubKlass1:
print(k)
default:
print("Nope")
}
}
}
public func castTestIfLet(_ x : __owned Klass) {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
if case let k as SubKlass1 = x2 { // expected-note {{use here}}
print(k)
} else {
print("no")
}
}
public func castTestIfLetInLoop(_ x : __owned Klass) {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
for _ in 0..<1024 {
if case let k as SubKlass1 = x2 { // expected-note {{use here}}
print(k)
} else {
print("no")
}
}
}
public enum EnumWithKlass {
case none
case klass(Klass)
}
public func castTestIfLet2(_ x : __owned EnumWithKlass) {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
if case let .klass(k as SubKlass1) = x2 { // expected-note {{use here}}
print(k)
} else {
print("no")
}
}
///////////////
// GEP Tests //
///////////////
public func castAccess(_ x : __owned Klass) {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
let _ = x2.k // expected-note {{use here}}
}
public func castAccess2(_ x : __owned Klass) {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
let _ = x2.k!.getOtherKlass() // expected-note {{use here}}
}
/////////////////////////
// Partial Apply Tests //
/////////////////////////
// Emit a better error here. At least we properly error.
public func partialApplyTest(_ x: __owned Klass) {
var x2 = x // expected-error {{'x2' used after being moved}}
x2 = x
let _ = _move(x2) // expected-note {{move here}}
let f = { // expected-note {{use here}}
print(x2)
}
f()
}
////////////////////////
// Misc Tests on Self //
////////////////////////
extension KlassWrapper {
func doSomething() { print("foo") }
// This test makes sure that we are able to properly put in the destroy_addr
// in the "creating blocks" branch. There used to be a bug where the impl
// would need at least one destroy_addr to properly infer the value to put
// into blocks not reachable from the _move but that are on the dominance
// frontier from the _move. This was unnecessary and the test makes sure we
// do not fail on this again.
mutating func noDestroyAddrBeforeOptInsertAfter() {
if booleanValue {
print("creating blocks")
} else {
let _ = _move(self)
print("creating blocks2")
}
self = .init(k: Klass())
print("foo bar")
}
// A derived version of noDestroyAddrBeforeOptInsertAfter that makes sure
// when we insert the destroy_addr, we destroy self at the end of the block.
mutating func noDestroyAddrBeforeOptInsertAfter2() {
if booleanValue {
print("creating blocks")
self.doSomething()
} else {
let _ = _move(self)
print("creating blocks2")
}
self = .init(k: Klass())
print("foo bar")
}
}
//////////////////////////////////
// Multiple Captures from Defer //
//////////////////////////////////
func multipleCapture1(_ k: Klass) -> () {
var k2 = k
var k3 = k
let _ = _move(k2)
let _ = _move(k3)
var k4 = k
k4 = k
defer {
k2 = Klass()
print(k4)
k3 = Klass()
}
print("foo bar")
}
func multipleCapture2(_ k: Klass) -> () {
var k2 = k // expected-error {{'k2' used after being moved}}
k2 = k
var k3 = k
let _ = _move(k2) // expected-note {{move here}}
let _ = _move(k3)
var k4 = k
k4 = k
defer {
print(k2) // expected-note {{use here}}
print(k4)
k3 = Klass()
}
print("foo bar")
}
//////////////////////
// Reinit in pieces //
//////////////////////
// These tests exercise the diagnostic to see how we error if we re-initialize a
// var in pieces. Eventually we should teach either this diagnostic pass how to
// handle this or teach DI how to combine the initializations into one large
// reinit.
struct KlassPair {
var lhs: Klass
var rhs: Klass
}
func reinitInPieces1(_ k: KlassPair) {
var k2 = k
k2 = k
let _ = _move(k2) // expected-error {{_move applied to value that the compiler does not support checking}}
k2.lhs = Klass()
k2.rhs = Klass()
}
| apache-2.0 | b99a63568b35fb6469304aaaa8acfa8a | 26.686221 | 121 | 0.539913 | 3.789022 | false | false | false | false |
Monnoroch/Cuckoo | Generator/Dependencies/SourceKitten/Source/SourceKittenFramework/JSONOutput.swift | 1 | 4177 | //
// JSONOutput.swift
// SourceKitten
//
// Created by Thomas Goyne on 9/17/15.
// Copyright © 2015 SourceKitten. All rights reserved.
//
import Foundation
/**
JSON Object to JSON String.
- parameter object: Object to convert to JSON.
- returns: JSON string representation of the input object.
*/
public func toJSON(_ object: Any) -> String {
do {
let prettyJSONData = try JSONSerialization.data(withJSONObject: object, options: .prettyPrinted)
if let jsonString = String(data: prettyJSONData, encoding: .utf8) {
return jsonString
}
} catch {}
return ""
}
/**
Convert [String: SourceKitRepresentable] to `NSDictionary`.
- parameter dictionary: [String: SourceKitRepresentable] to convert.
- returns: JSON-serializable value.
*/
public func toNSDictionary(_ dictionary: [String: SourceKitRepresentable]) -> NSDictionary {
var anyDictionary = [String: Any]()
for (key, object) in dictionary {
switch object {
case let object as [SourceKitRepresentable]:
anyDictionary[key] = object.map { toNSDictionary($0 as! [String: SourceKitRepresentable]) }
case let object as [[String: SourceKitRepresentable]]:
anyDictionary[key] = object.map { toNSDictionary($0) }
case let object as [String: SourceKitRepresentable]:
anyDictionary[key] = toNSDictionary(object)
case let object as String:
anyDictionary[key] = object
case let object as Int64:
anyDictionary[key] = NSNumber(value: object)
case let object as Bool:
anyDictionary[key] = NSNumber(value: object)
case let object as Any:
anyDictionary[key] = object
default:
fatalError("Should never happen because we've checked all SourceKitRepresentable types")
}
}
return anyDictionary as NSDictionary
}
public func declarationsToJSON(_ decl: [String: [SourceDeclaration]]) -> String {
return toJSON(decl.map({ [$0: toOutputDictionary($1)] }).sorted { $0.keys.first! < $1.keys.first! })
}
private func toOutputDictionary(_ decl: SourceDeclaration) -> [String: Any] {
var dict = [String: Any]()
func set(_ key: SwiftDocKey, _ value: Any?) {
if let value = value {
dict[key.rawValue] = value
}
}
func setA(_ key: SwiftDocKey, _ value: [Any]?) {
if let value = value, value.count > 0 {
dict[key.rawValue] = value
}
}
set(.kind, decl.type.rawValue)
set(.filePath, decl.location.file)
set(.docFile, decl.location.file)
set(.docLine, Int(decl.location.line))
set(.docColumn, Int(decl.location.column))
set(.name, decl.name)
set(.usr, decl.usr)
set(.parsedDeclaration, decl.declaration)
set(.documentationComment, decl.commentBody)
set(.parsedScopeStart, Int(decl.extent.start.line))
set(.parsedScopeEnd, Int(decl.extent.end.line))
set(.swiftDeclaration, decl.swiftDeclaration)
set(.alwaysDeprecated, decl.availability?.alwaysDeprecated)
set(.alwaysUnavailable, decl.availability?.alwaysUnavailable)
set(.deprecationMessage, decl.availability?.deprecationMessage)
set(.unavailableMessage, decl.availability?.unavailableMessage)
setA(.docResultDiscussion, decl.documentation?.returnDiscussion.map(toOutputDictionary))
setA(.docParameters, decl.documentation?.parameters.map(toOutputDictionary))
setA(.substructure, decl.children.map(toOutputDictionary))
if decl.commentBody != nil {
set(.fullXMLDocs, "")
}
return dict
}
private func toOutputDictionary(_ decl: [SourceDeclaration]) -> [String: Any] {
return ["key.substructure": decl.map(toOutputDictionary), "key.diagnostic_stage": ""]
}
private func toOutputDictionary(_ param: Parameter) -> [String: Any] {
return ["name": param.name, "discussion": param.discussion.map(toOutputDictionary)]
}
private func toOutputDictionary(_ text: Text) -> [String: Any] {
switch text {
case .Para(let str, let kind):
return ["kind": kind ?? "", "Para": str]
case .Verbatim(let str):
return ["kind": "", "Verbatim": str]
}
}
| mit | 89c4da21df432512fbd6b7d928063a75 | 33.8 | 104 | 0.664751 | 4.163509 | false | false | false | false |
quaderno/quaderno-ios | Tests/OHHTTPStubs+QuadernoTests.swift | 2 | 3261 | //
// OHHTTPStubs+QuadernoTests.swift
//
// Copyright (c) 2017 Recrea (http://recreahq.com/)
//
// 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
import OHHTTPStubs
@testable import Quaderno
// MARK: - Building Common Responses
private typealias HTTPHeader = [String: String]
private let defaultHTTPHeaders: HTTPHeader = [
"X-RateLimit-Reset" : "15",
"X-RateLimit-Remaining": "100",
]
private let defaultPaginationHTTPHeaders: HTTPHeader = {
var headers = defaultHTTPHeaders
headers["X-Pages-CurrentPage"] = "2"
headers["X-Pages-TotalPages"] = "5"
return headers
}()
private typealias JSON = [String: Any]
/// Creates a stubbed successful response containing an empty JSON object.
///
/// - Parameter paginated: Whether to include pagination headers.
/// - Returns: A stubbed successful response containing an empty JSON object.
func successJSONResponse(paginated: Bool = false) -> OHHTTPStubsResponse {
let headers: HTTPHeader = (paginated ? defaultPaginationHTTPHeaders : defaultHTTPHeaders)
return OHHTTPStubsResponse(jsonObject: JSON(), statusCode: 200, headers: headers)
}
/// A stubbed HTTP 401 response containing an empty JSON object.
let unauthorizedJSONResponse: OHHTTPStubsResponse = {
return OHHTTPStubsResponse(jsonObject: JSON(), statusCode: 401, headers: defaultHTTPHeaders)
}()
// MARK: - Stubbing Requests
private func isMethod(_ method: Quaderno.HTTPMethod) -> OHHTTPStubsTestBlock {
return { $0.httpMethod == method.rawValue }
}
private func matchesURL(_ url: URL) -> OHHTTPStubsTestBlock {
return { $0.url == url }
}
/// Stubs a request using a base URL and returning a given response.
///
/// - Parameters:
/// - request: The request to stub.
/// - client: The client sending the request.
/// - sucess: Whether the request is successful or not (defaults to `true`).
/// - response: The response to stub (defaults to `successJSONResponse()`).
func stub(_ request: Quaderno.Request, using httpClient: Client, succeeding sucess: Bool = true, with response: OHHTTPStubsResponse = successJSONResponse()) {
stub(condition: isMethod(request.method) && matchesURL(request.uri(using: httpClient.baseURL))) { _ in return response }
}
| mit | 1848cdcfdb65c9bc17a6e1d7acb4e07a | 38.768293 | 158 | 0.74057 | 4.418699 | false | false | false | false |
PuneCocoa/SpriteKit-Part-1 | MonkeyJump/GameScene.swift | 1 | 6036 | //
// GameScene.swift
// MonkeyJump
//
// Created by Kauserali on 09/10/14.
// Copyright (c) 2014 PuneCocoa. All rights reserved.
//
import SpriteKit
@objc protocol GameSceneDelegate {
func gameOver(#score: Double)
}
class GameScene: SKScene {
let BackgroundScrollSpeed: Double = 170
let MonkeySpeed: Double = 20
let jumpSound = SKAction.playSoundFileNamed("jump.wav", waitForCompletion: false)
let hurtSound = SKAction.playSoundFileNamed("hurt.mp3", waitForCompletion: false)
var monkey: Monkey!
var background1: SKSpriteNode!
var background2: SKSpriteNode!
var livesLabel: SKLabelNode!
var distanceLabel: SKLabelNode!
var previousTime: CFTimeInterval = 0
var nextSpawn: CFTimeInterval = 0
var difficultyMeasure: Double = 1
var distance: Double = 0
var jumping: Bool = false
var invincible: Bool = false
weak var gameSceneDelegate: GameSceneDelegate?
override func didMoveToView(view: SKView) {
background1 = childNodeWithName("background1") as SKSpriteNode
background2 = childNodeWithName("background2") as SKSpriteNode
livesLabel = childNodeWithName("lives_label") as SKLabelNode
distanceLabel = childNodeWithName("distance_label") as SKLabelNode
monkey = Monkey.monkey()
monkey.position = CGPoint(x: 70, y: 86)
addChild(monkey)
monkey.state = .Walking
distanceLabel.text = "Distance:0"
livesLabel.text = "Lives:\(monkey.noOfLives)"
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if !jumping {
jumping = true
runAction(jumpSound)
monkey.state = .Jumping
let jumpUpAction = SKAction.moveByX(0, y: 120, duration: 0.6)
let reverse = jumpUpAction.reversedAction()
let action = SKAction.sequence([jumpUpAction, reverse])
monkey.runAction(action, completion: {
self.jumping = false
self.monkey.state = .Walking
})
}
}
override func update(currentTime: CFTimeInterval) {
if monkey.state == MonkeyState.Dead {
println("You're dead")
return
}
if previousTime == 0 {
previousTime = currentTime
}
let deltaTime = currentTime - previousTime
previousTime = currentTime
let xOffset = BackgroundScrollSpeed * -1 * deltaTime
if background1.position.x < (background1.size.width * -1) {
background1.position = CGPoint(x: background2.position.x + background2.size.width, y: background1.size.height/2)
}
if background2.position.x < (background2.size.width * -1) {
background2.position = CGPoint(x: background1.position.x + background1.size.width, y: background2.size.height/2)
}
background1.position = CGPoint(x: background1.position.x + CGFloat(xOffset), y: background1.position.y)
background2.position = CGPoint(x: background2.position.x + CGFloat(xOffset), y: background2.position.y)
distance += MonkeySpeed * deltaTime
distanceLabel.text = "Distance:\(Int(distance))"
if currentTime > nextSpawn {
let enemyType = arc4random() % 3
var enemySprite: SKSpriteNode?
switch(enemyType) {
case 0:
enemySprite = Snake.snake()
case 1:
enemySprite = Croc.croc()
case 2:
enemySprite = HedgeHog.hedgehog()
default:
println("Thats weird..how did this happen?")
}
if let enemy = enemySprite {
enemy.position = CGPoint(x: size.width + enemy.size.width/2, y: 70)
addChild(enemy)
enemy.runAction(SKAction.moveBy(CGVectorMake(-size.width - enemy.size.width/2, 0), duration: 3), completion: {
enemy.removeFromParent()
})
}
let randomInterval = 4/difficultyMeasure
nextSpawn = currentTime + randomInterval
if difficultyMeasure < 2.22 {
difficultyMeasure = difficultyMeasure + 0.122
}
}
if !invincible {
for sprite in children as [SKNode] {
if sprite is Monkey {
continue
} else if (sprite is Snake) || (sprite is Croc) || (sprite is HedgeHog) {
let enemyRect = CGRectInset(sprite.frame, 10, 10)
if CGRectIntersectsRect(monkey.frame, enemyRect) {
invincible = true
monkey.noOfLives -= 1
livesLabel.text = "Lives:\(monkey.noOfLives)"
if monkey.noOfLives <= 0 {
monkey.state = .Dead
userInteractionEnabled = false
self.monkeyDead()
return
}
runAction(hurtSound)
let fadeOut = SKAction.fadeOutWithDuration(0.187)
let fadeIn = fadeOut.reversedAction()
let blinkAnimation = SKAction.sequence([fadeOut, fadeIn])
let repeatBlink = SKAction.repeatAction(blinkAnimation, count: 4)
monkey.runAction(repeatBlink, completion: {
self.invincible = false
self.monkey.state = .Walking
})
break
}
}
}
}
}
func monkeyDead() {
gameSceneDelegate?.gameOver(score: distance)
}
}
| apache-2.0 | e24e0f49f2f8d03bd06c3cb62cd3d737 | 35.804878 | 126 | 0.540921 | 5.119593 | false | false | false | false |
BareFeetWare/BFWControls | BFWControls/Modules/NibReplaceable/View/NibTableViewCell.swift | 1 | 8477 | //
// NibTableViewCell.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 24/4/18.
// Copyright © 2018 BareFeetWare. All rights reserved.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
import UIKit
@IBDesignable open class NibTableViewCell: BFWNibTableViewCell, NibReplaceable {
// MARK: - NibReplaceable
open var nibName: String?
open var placeholderViews: [UIView] {
return [textLabel, detailTextLabel, tertiaryTextLabel, actionView].compactMap { $0 }
}
// MARK: - IBOutlets
#if !TARGET_INTERFACE_BUILDER
@IBOutlet open override var textLabel: UILabel? {
get {
return overridingTextLabel ?? super.textLabel
}
set {
overridingTextLabel = newValue
}
}
@IBOutlet open override var detailTextLabel: UILabel? {
get {
return overridingDetailTextLabel ?? super.detailTextLabel
}
set {
overridingDetailTextLabel = newValue
}
}
@IBOutlet open override var imageView: UIImageView? {
get {
return overridingImageView ?? super.imageView
}
set {
overridingImageView = newValue
}
}
open override func awakeAfter(using coder: NSCoder) -> Any? {
guard let nibView = replacedByNibView()
else { return self }
nibView.copySubviewProperties(from: self)
nibView.removePlaceholders()
return nibView
}
#endif // !TARGET_INTERFACE_BUILDER
@IBOutlet open var tertiaryTextLabel: UILabel?
@IBInspectable open var tertiaryText: String? {
get {
return tertiaryTextLabel?.text
}
set {
tertiaryTextLabel?.text = newValue
}
}
// TODO: Perhaps integrate actionView with accessoryView
@IBOutlet open var actionView: UIView?
// MARK: - Private variables
private var overridingTextLabel: UILabel?
private var overridingDetailTextLabel: UILabel?
private var overridingImageView: UIImageView?
// MARK: - Variables
@IBInspectable open var isActionViewHidden: Bool {
get {
return actionView?.isHidden ?? true
}
set {
actionView?.isHidden = newValue
}
}
/// Minimum intrinsicContentSize.height to use if the table view uses auto dimension.
@IBInspectable open var minimumHeight: CGFloat = 0.0
open var style: UITableViewCell.CellStyle = .default
// MARK: - Init
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.style = style
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
let styleInt = coder.decodeInteger(forKey: "UITableViewCellStyle")
if let style = UITableViewCell.CellStyle(rawValue: styleInt) {
self.style = style
}
}
// MARK: - UIView
open override func systemLayoutSizeFitting(
_ targetSize: CGSize,
withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority,
verticalFittingPriority: UILayoutPriority
) -> CGSize
{
var size = super.systemLayoutSizeFitting(
targetSize,
withHorizontalFittingPriority: horizontalFittingPriority,
verticalFittingPriority: verticalFittingPriority
)
if size.height < minimumHeight {
size.height = minimumHeight
}
return size
}
// MARK: - IBDesignable
#if TARGET_INTERFACE_BUILDER
let isInterfaceBuilder = true
#else
let isInterfaceBuilder = false
#endif
#if TARGET_INTERFACE_BUILDER
private var isFinishedPrepare = false
@IBOutlet open override var textLabel: UILabel? {
get {
return isFinishedPrepare
? overridingTextLabel
: super.textLabel ?? UILabel()
}
set {
if overridingTextLabel == nil {
overridingTextLabel = newValue
}
}
}
@IBOutlet open override var detailTextLabel: UILabel? {
get {
return isFinishedPrepare
? overridingDetailTextLabel
: superDetailTextLabel ?? UILabel()
}
set {
if overridingDetailTextLabel == nil {
overridingDetailTextLabel = newValue
}
}
}
@IBOutlet open override var imageView: UIImageView? {
get {
return isFinishedPrepare
? overridingImageView
: super.imageView
}
set {
if overridingImageView == nil {
overridingImageView = newValue
}
}
}
/// super.detailTextLabel returns nil even though super.textLabel returns the label, so resorting to subviews:
private var superDetailTextLabel: UILabel? {
let label: UILabel?
if let detailTextLabel = super.detailTextLabel {
label = detailTextLabel
} else {
let superLabels = super.contentView.subviews.filter { $0 is UILabel } as! [UILabel]
label = superLabels.count == 2
? superLabels[1]
: nil
}
return label
}
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
if let destination = overridingTextLabel,
let source = super.textLabel
{
if !["Text", "Title"].contains(source.text) {
destination.copyNonDefaultProperties(from: source)
}
source.attributedText = nil
}
if let destination = overridingDetailTextLabel {
if let source = superDetailTextLabel
{
if !["Detail", "Subtitle"].contains(source.text) {
destination.copyNonDefaultProperties(from: source)
}
source.attributedText = nil
} else {
destination.text = nil
}
}
if let destination = overridingImageView,
let source = super.imageView
{
destination.copyNonDefaultProperties(from: source)
source.image = nil
}
isFinishedPrepare = true
}
open override func layoutSubviews() {
super.layoutSubviews()
offsetSubviewFramesIfNeeded()
}
/// Implement workaround for bug in IB frames of textLabel, detailTextLabel, imageView.
private var isOffsetSubviewFramesNeeded = true
private var isOffsetSubviewFramesFinished = false
// Hack to figure out in which layoutSubviews() call after prepareForInterfaceBuilder, to adjust the frames so the selection in IB lines up.
private var offsetCount = 0
private let changeFrameOffsetCount = 2
/// Workaround for bug in IB that does not show the correct frame for textLabel etc.
private func offsetSubviewFramesIfNeeded() {
guard isInterfaceBuilder && isOffsetSubviewFramesNeeded && isFinishedPrepare
else { return }
IBLog.write("offsetSubviewFramesIfNeeded() {", indent: 1)
offsetCount += 1
IBLog.write("offsetCount = \(offsetCount)")
if offsetCount == changeFrameOffsetCount {
[textLabel, detailTextLabel, imageView].compactMap { $0 }.forEach { subview in
let converted = subview.convert(CGPoint.zero, to: self)
if converted.x > 0
&& converted.y > 0
{
IBLog.write("subview: \(subview.shortDescription) {", indent: 1)
IBLog.write("old origin: \(subview.frame.origin)")
subview.frame.origin = converted
IBLog.write("new origin: \(subview.frame.origin)")
IBLog.write("}", indent: -1)
}
}
isOffsetSubviewFramesFinished = true
}
IBLog.write("}", indent: -1)
}
#endif // TARGET_INTERFACE_BUILDER
}
@objc public extension NibTableViewCell {
@objc func replacedByNibViewForInit() -> Self? {
return replacedByNibView()
}
}
| mit | ea1b9ec45389b1497ac10318be90a375 | 29.599278 | 144 | 0.588249 | 5.550753 | false | false | false | false |
Ashok28/Kingfisher | Demo/Demo/Kingfisher-Demo/ViewControllers/DetailImageViewController.swift | 2 | 2450 | //
// DetailImageViewController.swift
// Kingfisher
//
// Created by onevcat on 2018/11/25.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// 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
class DetailImageViewController: UIViewController {
var imageURL: URL!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var infoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
imageView.kf.setImage(with: imageURL, options: [.memoryCacheExpiration(.expired)]) { result in
guard let image = try? result.get().image else {
return
}
let scrollViewFrame = self.scrollView.frame
let scaleWidth = scrollViewFrame.size.width / image.size.width
let scaleHeight = scrollViewFrame.size.height / image.size.height
let minScale = min(scaleWidth, scaleHeight)
self.scrollView.minimumZoomScale = minScale
DispatchQueue.main.async {
self.scrollView.zoomScale = minScale
}
self.infoLabel.text = "\(image.size)"
}
}
}
extension DetailImageViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
| mit | 21acd743db11f23038298f1a7e18a3a7 | 38.516129 | 102 | 0.68898 | 4.766537 | false | false | false | false |
gottesmm/swift | benchmark/single-source/TwoSum.swift | 10 | 3936 | //===--- TwoSum.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 is solves 2SUM problem:
// Given an array and a number C, find elements A and B such that A+B = C
import TestsUtils
let array = [
959, 81, 670, 727, 416, 171, 401, 398, 707, 596, 200, 9, 414, 98, 43,
352, 752, 158, 593, 418, 240, 912, 542, 445, 429, 456, 993, 618, 52, 649,
759, 190, 126, 306, 966, 37, 787, 981, 606, 372, 597, 901, 158, 284, 809,
820, 173, 538, 644, 428, 932, 967, 962, 959, 233, 467, 220, 8, 729, 889,
277, 494, 554, 670, 91, 657, 606, 248, 644, 8, 366, 815, 567, 993, 696,
763, 800, 531, 301, 863, 680, 703, 279, 388, 871, 124, 302, 617, 410, 366,
813, 599, 543, 508, 336, 312, 212, 86, 524, 64, 641, 533, 207, 893, 146,
534, 104, 888, 534, 464, 423, 583, 365, 420, 642, 514, 336, 974, 846, 437,
604, 121, 180, 794, 278, 467, 818, 603, 537, 167, 169, 704, 9, 843, 555,
154, 598, 566, 676, 682, 828, 128, 875, 445, 918, 505, 393, 571, 3, 406,
719, 165, 505, 750, 396, 726, 404, 391, 532, 403, 728, 240, 89, 917, 665,
561, 282, 302, 438, 714, 6, 290, 939, 200, 788, 128, 773, 900, 934, 772,
130, 884, 60, 870, 812, 750, 349, 35, 155, 905, 595, 806, 771, 443, 304,
283, 404, 905, 861, 820, 338, 380, 709, 927, 42, 478, 789, 656, 106, 218,
412, 453, 262, 864, 701, 686, 770, 34, 624, 597, 843, 913, 966, 230, 942,
112, 991, 299, 669, 399, 630, 943, 934, 448, 62, 745, 917, 397, 440, 286,
875, 22, 989, 235, 732, 906, 923, 643, 853, 68, 48, 524, 86, 89, 688,
224, 546, 73, 963, 755, 413, 524, 680, 472, 19, 996, 81, 100, 338, 626,
911, 358, 887, 242, 159, 731, 494, 985, 83, 597, 98, 270, 909, 828, 988,
684, 622, 499, 932, 299, 449, 888, 533, 801, 844, 940, 642, 501, 513, 735,
674, 211, 394, 635, 372, 213, 618, 280, 792, 487, 605, 755, 584, 163, 358,
249, 784, 153, 166, 685, 264, 457, 677, 824, 391, 830, 310, 629, 591, 62,
265, 373, 195, 803, 756, 601, 592, 843, 184, 220, 155, 396, 828, 303, 553,
778, 477, 735, 430, 93, 464, 306, 579, 828, 759, 809, 916, 759, 336, 926,
776, 111, 746, 217, 585, 441, 928, 236, 959, 417, 268, 200, 231, 181, 228,
627, 675, 814, 534, 90, 665, 1, 604, 479, 598, 109, 370, 719, 786, 700,
591, 536, 7, 147, 648, 864, 162, 404, 536, 768, 175, 517, 394, 14, 945,
865, 490, 630, 963, 49, 904, 277, 16, 349, 301, 840, 817, 590, 738, 357,
199, 581, 601, 33, 659, 951, 640, 126, 302, 632, 265, 894, 892, 587, 274,
487, 499, 789, 954, 652, 825, 512, 170, 882, 269, 471, 571, 185, 364, 217,
427, 38, 715, 950, 808, 270, 746, 830, 501, 264, 581, 211, 466, 970, 395,
610, 930, 885, 696, 568, 920, 487, 764, 896, 903, 241, 894, 773, 896, 341,
126, 22, 420, 959, 691, 207, 745, 126, 873, 341, 166, 127, 108, 426, 497,
681, 796, 430, 367, 363
]
@inline(never)
public func run_TwoSum(_ N: Int) {
var i1: Int?
var i2: Int?
var Dict: Dictionary<Int, Int> = [:]
for _ in 1...2*N {
for Sum in 500..<600 {
Dict = [:]
i1 = nil
i2 = nil
for n in 0..<array.count {
if let m = Dict[Sum-array[n]] {
i1 = m
i2 = n
break
}
Dict[array[n]] = n
}
CheckResults(i1 != nil && i2 != nil,
"Incorrect results in TwoSum: i1 or i2 wasn't found.")
CheckResults(Sum == array[i1!] + array[i2!],
"Incorrect results in TwoSum: Sum: \(Sum), " +
"array[i1]: \(array[i1!]), array[i2]: \(array[i2!]).")
}
}
}
| apache-2.0 | bb6b665323c1b0b6af369f857083614c | 48.822785 | 80 | 0.545224 | 2.500635 | false | false | false | false |
StephenMIMI/U17Comics | U17Comics/U17Comics/classes/HomePage/main/Controllers/MoreComicController.swift | 1 | 9938 | //
// MoreComicController.swift
// U17Comics
//
// Created by qianfeng on 16/11/3.
// Copyright © 2016年 zhb. All rights reserved.
//
import UIKit
import MJRefresh
class MoreComicController: U17TabViewController, CustomNavigationProtocol {
//请求的url
var urlString: String?
var jumpClosure: HomeJumpClosure?
var viewType: ViewType = ViewType.Subscribe
//标题文字
var titleStr: String?
//页数
private var currentPage: Int = 1
//数据重载就刷新页面
private var detailData: Array<HomeVIPComics>? {
didSet {
tableView?.reloadData()
}
}
//更多页面筛选框
private var index: Int? {
didSet {
if index != oldValue {
if cataLabel != nil && urlString != nil {
cataLabel?.text = titleArray[index!]
var strArray = urlString?.componentsSeparatedByString("&")
//更新url
if strArray != nil {
strArray![2] = "argCon=\(index!+1)"
var newUrl = strArray![0]
for i in 1..<(strArray?.count)! {
newUrl += "&\(strArray![i])"
}
//修改显示页面为1并滚动回顶部
currentPage = 1
urlString = newUrl
tableView?.setContentOffset(CGPointMake(0, 0), animated: false)
if titleArray[index!] == "点击" {
viewType = .RankClick
}else if titleArray[index!] == "更新" {
viewType = .Subscribe
}else if titleArray[index!] == "收藏" {
viewType = .Collection
}
downloadDetailData(urlString!)
}
}
}
}
}
//定义筛选视图是否隐藏
private var viewHidden: Bool = true
private var tableView: UITableView?
private var cataLabel: UILabel?
private var sortView: UIView?//下拉框视图
private var coverView: UIView?//点击下拉后填充屏幕视图
let titleArray = ["点击","更新","收藏"]
override func viewDidLoad() {
super.viewDidLoad()
if let tmpTitle = titleStr {
addTitle(tmpTitle)
}
//自定义返回按钮
let backBtn = UIButton(frame: CGRectMake(0,0,30,30))
backBtn.setImage(UIImage(named: "nav_back_black"), forState: .Normal)
backBtn.addTarget(self, action: #selector(backBtnClick), forControlEvents: .TouchUpInside)
addBarButton(backBtn, position: BarButtonPosition.left)
//自定义下拉框按钮
let rightBtn = UIButton(frame: CGRectMake(0,0,45,40))
rightBtn.addTarget(self, action: #selector(rightBtnClick), forControlEvents: .TouchUpInside)
addBarButton(rightBtn, position: BarButtonPosition.right)
cataLabel = UILabel(frame: CGRectMake(0,0,25,40))
cataLabel?.font = UIFont.systemFontOfSize(12)
cataLabel?.textColor = UIColor.lightGrayColor()
cataLabel?.text = "更新"
rightBtn.addSubview(cataLabel!)
let downArrow = UIImageView(frame: CGRectMake(25,5,20,30))
downArrow.image = UIImage(named: "arrowdown")
rightBtn.addSubview(downArrow)
//创建tableView
createTableView()
if urlString != nil {
downloadDetailData(urlString!)
}
//添加下拉刷新
addRefresh({
[weak self] in
self!.currentPage = 1
self!.downloadDetailData(self!.urlString!)
}) {
[weak self] in
self!.currentPage += 1
self!.downloadDetailData(self!.urlString!)
}
}
func rightBtnClick() {
if coverView == nil {
coverView = UIView(frame: CGRectMake(0,20,screenWidth,screenHeight))
//bug这里的手势无法响应
coverView?.backgroundColor = UIColor.clearColor()
view.addSubview(coverView!)
let tap = UITapGestureRecognizer(target: self, action: #selector(coverTap))
//tap.cancelsTouchesInView = false
//tap.delegate = self
coverView?.addGestureRecognizer(tap)
}
if coverView != nil && sortView == nil {
sortView = UIView(frame: CGRectMake(screenWidth-15-50,44,50,90))
sortView?.backgroundColor = UIColor.whiteColor()
sortView?.layer.borderWidth = 1
sortView?.layer.borderColor = UIColor.lightGrayColor().CGColor
sortView?.layer.shadowOffset = CGSizeMake(1, 1)
for i in 0..<3 {
let btn = UIButton(type: UIButtonType.Custom)
btn.frame = CGRectMake(0,CGFloat(i)*30,45,30)
btn.addTarget(self, action: #selector(sortClick(_:)), forControlEvents: .TouchUpInside)
btn.tag = 100+i
sortView?.addSubview(btn)
let label = UILabel(frame: btn.bounds)
label.text = titleArray[i]
label.textColor = UIColor.lightGrayColor()
label.textAlignment = .Center
label.font = UIFont.systemFontOfSize(12)
btn.addSubview(label)
}
coverView!.addSubview(sortView!)
}
viewHidden = !viewHidden
coverView?.hidden = viewHidden
}
//背部蒙版点击隐藏
func coverTap() {
viewHidden = !viewHidden
coverView?.hidden = viewHidden
}
func sortClick(btn: UIButton) {
index = btn.tag-100
viewHidden = !viewHidden
coverView?.hidden = viewHidden
}
func backBtnClick() {
navigationController?.popViewControllerAnimated(true)
}
func createTableView() {
automaticallyAdjustsScrollViewInsets = false
tableView = UITableView(frame: CGRectZero, style: .Plain)
tableView?.delegate = self
tableView?.dataSource = self
tableView?.backgroundColor = customBgColor
view.addSubview(tableView!)
tableView?.snp_makeConstraints(closure: { (make) in
make.left.right.bottom.equalTo(view)
make.top.equalTo(view).offset(64)
})
}
//下载详情的数据
func downloadDetailData(urlString: String) {
let downloader = U17Download()
downloader.delegate = self
downloader.downloadType = HomeDownloadType.MoreComic
downloader.getWithUrl(urlString+"\(currentPage)")
}
func handleClickEvent(urlString: String, ticketUrl: String?) {
HomePageService.handleEvent(urlString, comicTicket: ticketUrl, onViewController: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: downloader的代理
extension MoreComicController: U17DownloadDelegate {
//下载失败
func downloader(downloader: U17Download, didFailWithError error: NSError) {
print(error)
}
//下载成功
func downloader(downloader: U17Download, didFinishWithData data: NSData?) {
if let tmpData = data {
if downloader.downloadType == HomeDownloadType.MoreComic {
if tableView!.mj_header != nil {
self.tableView!.mj_header.endRefreshing()
self.tableView!.mj_footer.endRefreshing()
}
if let tmpModel = HomeVIPModel.parseData(tmpData).data?.returnData?.comics {
if currentPage == 1 {
detailData = tmpModel
}else {
let tmpArray = NSMutableArray(array: detailData!)
tmpArray.addObjectsFromArray(tmpModel)
detailData = NSArray(array: tmpArray) as? Array<HomeVIPComics>
}
}
jumpClosure = {
[weak self](jumpUrl,ticketUrl,title) in
self!.handleClickEvent(jumpUrl, ticketUrl: ticketUrl)
}
}
}
}
}
//MARK: tableView的代理
extension MoreComicController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 150
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let tmpModel = detailData {
return tmpModel.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let listModel = detailData {
let cell = HomeVIPCell.createVIPCellFor(tableView, atIndexPath: indexPath, listModel: listModel[indexPath.row], type: viewType)
cell.jumpClosure = jumpClosure
cell.backgroundColor = customBgColor
return cell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
}
//刷新页面的代理
extension MoreComicController: CustomAddRefreshProtocol {
func addRefresh(header: (()->())?, footer:(()->())?) {
if header != nil && tableView != nil {
tableView!.mj_header = MJRefreshNormalHeader(refreshingBlock: {
header!()
})
}
if footer != nil && tableView != nil {
tableView!.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
footer!()
})
}
}
} | mit | 026c4ed0ddd878e1fd0ed913eadd17d7 | 34.571956 | 139 | 0.56676 | 5.073158 | false | false | false | false |
nerd0geek1/TableViewManager | TableViewManagerTests/classes/implementation/SelectableSectionDataSpec.swift | 1 | 2277 | //
// SelectableSectionDataSpec.swift
// TableViewManager
//
// Created by Kohei Tabata on 2016/07/19.
// Copyright © 2016 Kohei Tabata. All rights reserved.
//
import Quick
import Nimble
class SelectableSectionDataSpec: QuickSpec {
override func spec() {
describe("SelectableSectionData") {
describe("didUpdateSelectedState: (() -> Void)?", {
let selectableRowDataList: [MockSelectableRowData] = [Int](0..<9).map({ MockSelectableRowData.init(index: $0) })
let sectionData: SelectableSectionData = SelectableSectionData(rowDataList: selectableRowDataList)
var calledCount: Int = 0
sectionData.didUpdateSelectedState = {
calledCount += 1
expect(sectionData.selectedRowDataList().count).to(equal(calledCount))
}
(sectionData.rowData(at: 0) as! MockSelectableRowData).toggleSelectedState()
(sectionData.rowData(at: 2) as! MockSelectableRowData).toggleSelectedState()
})
describe("selectedRowDataList()", {
let selectableRowDataList: [MockSelectableRowData] = [Int](0..<9).map({ MockSelectableRowData.init(index: $0) })
let sectionData: SelectableSectionData = SelectableSectionData(rowDataList: selectableRowDataList)
(sectionData.rowData(at: 0) as! MockSelectableRowData).toggleSelectedState()
(sectionData.rowData(at: 3) as! MockSelectableRowData).toggleSelectedState()
(sectionData.rowData(at: 5) as! MockSelectableRowData).toggleSelectedState()
let selectedRowDataList: [MockSelectableRowData] = sectionData.selectedRowDataList() as! [MockSelectableRowData]
expect(selectedRowDataList.count).to(equal(3))
expect(selectedRowDataList[0].index).to(equal(0))
expect(selectedRowDataList[1].index).to(equal(3))
expect(selectedRowDataList[2].index).to(equal(5))
})
}
}
private class MockSelectableRowData: SelectableRowData {
let index: Int
init(index: Int) {
self.index = index
}
}
}
| mit | b41c26d75d5598cd50f61664ea7a5059 | 40.381818 | 128 | 0.616872 | 5.114607 | false | false | false | false |
ontouchstart/swift3-playground | Swift Standard Library.playground/Pages/Indexing and Slicing Strings.xcplaygroundpage/Sources/GroupChat.swift | 1 | 2312 | import UIKit
public var pastAllowedLengthFunction: ((String) -> Range<String.Index>?)?
private let messageCellIdentifier = "MessageCell"
private class GroupChatController: UITableViewController {
override init(style: UITableViewStyle) {
super.init(style: style)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: messageCellIdentifier)
view.frame = CGRect(x: 0, y: 0, width: 320, height: 300)
tableView.separatorStyle = .singleLine
tableView.separatorColor = .blue
tableView.estimatedRowHeight = 60
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: messageCellIdentifier, for: indexPath)
let attributedString = NSMutableAttributedString(string: String(messages[indexPath.row]))
if let redRangeFunction = pastAllowedLengthFunction,
let redRange = redRangeFunction(messages[indexPath.row].contents)
{
let redAttribute: [String: AnyObject] = [
NSBackgroundColorAttributeName: #colorLiteral(red: 0.9859465361, green: 0, blue: 0.04060116783, alpha: 0.4969499144)
]
let contents = messages[indexPath.row].contents
let location = contents.distance(from:contents.startIndex, to: redRange.lowerBound)
let length = contents.distance(from: redRange.lowerBound, to: redRange.upperBound)
attributedString.setAttributes(redAttribute, range: NSRange(location: location, length: length))
}
cell.textLabel!.numberOfLines = 0
cell.textLabel!.attributedText = attributedString
return cell
}
}
private let chatController = GroupChatController(style: .plain)
private var chatView: UIView {
return chatController.view
}
public func showChatView(_ rangeFunc: (contents: String) -> Range<String.Index>?) -> UIView {
pastAllowedLengthFunction = rangeFunc
return chatView
}
| mit | 942cacaa82787a7a3c10fc3a95754da2 | 39.561404 | 132 | 0.693772 | 4.982759 | false | false | false | false |
AaronMT/firefox-ios | XCUITests/ScreenGraphTest.swift | 6 | 10321 | /* 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 MappaMundi
import XCTest
class ScreenGraphTest: XCTestCase {
var navigator: MMNavigator<TestUserState>!
var app: XCUIApplication!
override func setUp() {
app = XCUIApplication()
navigator = createTestGraph(for: self, with: app).navigator()
app.terminate()
app.launchArguments = [LaunchArguments.Test, LaunchArguments.ClearProfile, LaunchArguments.SkipIntro, LaunchArguments.SkipWhatsNew, LaunchArguments.SkipETPCoverSheet]
app.activate()
}
}
extension XCTestCase {
func wait(forElement element: XCUIElement, timeout: TimeInterval) {
let predicate = NSPredicate(format: "exists == 1")
expectation(for: predicate, evaluatedWith: element)
waitForExpectations(timeout: timeout)
}
}
extension ScreenGraphTest {
// Temoporary disable since it is failing intermittently on BB
func testUserStateChanges() {
XCTAssertNil(navigator.userState.url, "Current url is empty")
navigator.userState.url = "https://mozilla.org"
navigator.performAction(TestActions.LoadURLByTyping)
// The UserState is mutated in BrowserTab.
navigator.goto(BrowserTab)
navigator.nowAt(BrowserTab)
XCTAssertTrue(navigator.userState.url?.starts(with: "www.mozilla.org") ?? false, "Current url recorded by from the url bar is \(navigator.userState.url ?? "nil")")
}
func testBackStack() {
// We'll go through the browser tab, through the menu.
navigator.goto(SettingsScreen)
// Going back, there is no explicit way back to the browser tab,
// and the menu will have dismissed. We should be detecting the existence of
// elements as we go through each screen state, so if there are errors, they'll be
// reported in the graph below.
navigator.goto(BrowserTab)
}
func testSimpleToggleAction() {
// Switch night mode on, by toggling.
navigator.performAction(TestActions.ToggleNightMode)
XCTAssertTrue(navigator.userState.nightMode)
navigator.back()
XCTAssertEqual(navigator.screenState, BrowserTab)
// Nothing should happen here, because night mode is already on.
navigator.toggleOn(navigator.userState.nightMode, withAction: TestActions.ToggleNightMode)
XCTAssertTrue(navigator.userState.nightMode)
XCTAssertEqual(navigator.screenState, BrowserTab)
// Switch night mode off.
navigator.toggleOff(navigator.userState.nightMode, withAction: TestActions.ToggleNightMode)
XCTAssertFalse(navigator.userState.nightMode)
navigator.back()
XCTAssertEqual(navigator.screenState, BrowserTab)
}
func testChainedActionPerf1() {
let navigator = self.navigator!
measure {
navigator.userState.url = defaultURL
navigator.performAction(TestActions.LoadURLByPasting)
XCTAssertEqual(navigator.screenState, WebPageLoading)
}
}
func testChainedActionPerf2() {
let navigator = self.navigator!
measure {
navigator.userState.url = defaultURL
navigator.performAction(TestActions.LoadURLByTyping)
XCTAssertEqual(navigator.screenState, WebPageLoading)
}
navigator.userState.url = defaultURL
navigator.performAction(TestActions.LoadURL)
XCTAssertEqual(navigator.screenState, WebPageLoading)
}
func testConditionalEdgesSimple() {
XCTAssertTrue(navigator.can(goto: PasscodeSettingsOff))
XCTAssertFalse(navigator.can(goto: PasscodeSettingsOn))
navigator.goto(PasscodeSettingsOff)
XCTAssertEqual(navigator.screenState, PasscodeSettingsOff)
}
func testConditionalEdgesRerouting() {
// The navigator should dynamically reroute to the target screen
// if the userState changes.
// This test adds to the graph a passcode setting screen. In that screen,
// there is a noop action that fatalErrors if it is taken.
//
let map = createTestGraph(for: self, with: app)
func typePasscode(_ passCode: String) {
passCode.forEach { char in
app.keys["\(char)"].tap()
}
}
map.addScreenState(SetPasscodeScreen) { screenState in
// This is a silly way to organize things here,
// and is an artifical way to show that the navigator is re-routing midway through
// a goto.
screenState.onEnter() { userState in
typePasscode(userState.newPasscode)
typePasscode(userState.newPasscode)
userState.passcode = userState.newPasscode
}
screenState.noop(forAction: "FatalError", transitionTo: PasscodeSettingsOn, if: "passcode == nil") { _ in fatalError() }
screenState.noop(forAction: "Very", "Long", "Path", "Of", "Actions", transitionTo: PasscodeSettingsOn, if: "passcode != nil") { _ in }
}
navigator = map.navigator()
XCTAssertTrue(navigator.can(goto: PasscodeSettingsOn))
XCTAssertTrue(navigator.can(goto: PasscodeSettingsOff))
XCTAssertTrue(navigator.can(goto: "FatalError"))
navigator.goto(PasscodeSettingsOn)
XCTAssertTrue(navigator.can(goto: PasscodeSettingsOn))
XCTAssertFalse(navigator.can(goto: PasscodeSettingsOff))
XCTAssertFalse(navigator.can(goto: "FatalError"))
XCTAssertEqual(navigator.screenState, PasscodeSettingsOn)
}
}
private let defaultURL = "https://example.com"
@objcMembers
class TestUserState: MMUserState {
required init() {
super.init()
initialScreenState = FirstRun
}
var url: String? = nil
var nightMode = false
var passcode: String? = nil
var newPasscode: String = "111111"
}
let PasscodeSettingsOn = "PasscodeSettingsOn"
let PasscodeSettingsOff = "PasscodeSettingsOff"
let WebPageLoading = "WebPageLoading"
fileprivate class TestActions {
static let ToggleNightMode = "menu-NightMode"
static let LoadURL = "LoadURL"
static let LoadURLByTyping = "LoadURLByTyping"
static let LoadURLByPasting = "LoadURLByPasting"
}
public var isTablet: Bool {
// There is more value in a variable having the same name,
// so it can be used in both predicates and in code
// than avoiding the duplication of one line of code.
return UIDevice.current.userInterfaceIdiom == .pad
}
fileprivate func createTestGraph(for test: XCTestCase, with app: XCUIApplication) -> MMScreenGraph<TestUserState> {
let map = MMScreenGraph(for: test, with: TestUserState.self)
map.addScreenState(FirstRun) { screenState in
screenState.noop(to: BrowserTab)
screenState.tap(app.textFields["url"], to: URLBarOpen)
}
map.addScreenState(WebPageLoading) { screenState in
screenState.dismissOnUse = true
// Would like to use app.otherElements.deviceStatusBars.networkLoadingIndicators.element
// but this means exposing some of SnapshotHelper to another target.
// screenState.onEnterWaitFor("exists != true",
// element: app.progressIndicators.element(boundBy: 0))
screenState.noop(to: BrowserTab)
}
map.addScreenState(BrowserTab) { screenState in
screenState.onEnter { userState in
userState.url = app.textFields["url"].value as? String
}
screenState.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu)
screenState.tap(app.textFields["url"], to: URLBarOpen)
screenState.gesture(forAction: TestActions.LoadURLByPasting, TestActions.LoadURL) { userState in
UIPasteboard.general.string = userState.url ?? defaultURL
app.textFields["url"].press(forDuration: 1.0)
app.tables["Context Menu"].cells["menu-PasteAndGo"].firstMatch.tap()
}
}
map.addScreenState(URLBarOpen) { screenState in
screenState.gesture(forAction: TestActions.LoadURLByTyping, TestActions.LoadURL) { userState in
let urlString = userState.url ?? defaultURL
app.textFields["address"].typeText("\(urlString)\r")
}
}
map.addScreenAction(TestActions.LoadURL, transitionTo: WebPageLoading)
map.addScreenState(BrowserTabMenu) { screenState in
screenState.dismissOnUse = true
screenState.onEnterWaitFor(element: app.tables["Context Menu"])
screenState.tap(app.tables.cells["Settings"], to: SettingsScreen)
screenState.tap(app.cells["menu-NightMode"], forAction: TestActions.ToggleNightMode, transitionTo: BrowserTabMenu) { userState in
userState.nightMode = !userState.nightMode
}
screenState.backAction = {
if isTablet {
// There is no Cancel option in iPad.
app.otherElements["PopoverDismissRegion"].tap()
} else {
app.buttons["PhotonMenu.close"].tap()
}
}
}
let navigationControllerBackAction = {
app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap()
}
map.addScreenState(SettingsScreen) { screenState in
let table = app.tables["AppSettingsTableViewController.tableView"]
screenState.onEnterWaitFor(element: table)
screenState.tap(table.cells["TouchIDPasscode"], to: PasscodeSettingsOff, if: "passcode == nil")
screenState.tap(table.cells["TouchIDPasscode"], to: PasscodeSettingsOn, if: "passcode != nil")
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(PasscodeSettingsOn) { screenState in
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(PasscodeSettingsOff) { screenState in
screenState.tap(app.staticTexts["Turn Passcode On"], to: SetPasscodeScreen)
screenState.backAction = navigationControllerBackAction
}
map.addScreenState(SetPasscodeScreen) { screenState in
screenState.backAction = navigationControllerBackAction
}
return map
}
| mpl-2.0 | 4b6b2ec773e2dc65477b815864760093 | 38.094697 | 174 | 0.680748 | 5.094274 | false | true | false | false |
JK-V/Swift | Ratings/Ratings/PlayersTableViewController.swift | 1 | 3425 | //
// PlayersTableViewController.swift
// Ratings
//
// Created by Persistent on 05/07/16.
// Copyright © 2016 JaysSwiftProject. All rights reserved.
//
import UIKit
class PlayersTableViewController: UITableViewController {
var players:[Player] = playersData
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return players.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PlayerCell", forIndexPath: indexPath)
as! PlayerCell
let player = players[indexPath.row] as Player
cell.player = player
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 2dc6a68c9582e1db01bc0cd2a300e07c | 32.568627 | 157 | 0.67757 | 5.650165 | false | false | false | false |
instacrate/tapcrate-api | Sources/api/Models/Pictures/CustomerPicture.swift | 1 | 1763 | //
// CustomerPicture.swift
// App
//
// Created by Hakon Hanesand on 6/11/17.
//
import Vapor
import FluentProvider
final class CustomerPicture: PictureBase {
let storage = Storage()
static var permitted: [String] = ["customer_id", "url"]
let customer_id: Identifier
let url: String
static func pictures(for owner: Identifier) throws -> Query<CustomerPicture> {
return try self.makeQuery().filter("customer_id", owner.int)
}
init(node: Node) throws {
url = try node.extract("url")
if let context = node.context as? ParentContext<Customer> {
customer_id = context.parent_id
} else {
customer_id = try node.extract("customer_id")
}
createdAt = try? node.extract(CustomerPicture.createdAtKey)
updatedAt = try? node.extract(CustomerPicture.updatedAtKey)
id = try? node.extract("id")
}
func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"url" : .string(url)
]).add(objects: [
"id" : id,
"customer_id" : customer_id,
CustomerPicture.createdAtKey : createdAt,
CustomerPicture.updatedAtKey : updatedAt
])
}
class func prepare(_ database: Database) throws {
try database.create(CustomerPicture.self) { picture in
picture.id()
picture.string("url")
picture.parent(Customer.self)
}
}
static func revert(_ database: Database) throws {
try database.delete(CustomerPicture.self)
}
}
extension CustomerPicture: Protected {
func owners() throws -> [ModelOwner] {
return [ModelOwner(modelType: Customer.self, id: customer_id)]
}
}
| mit | cedd300a113836f2c9795a1d356fe444 | 24.926471 | 82 | 0.606353 | 4.197619 | false | false | false | false |
mcudich/TemplateKit | Source/Utilities/XMLDocument.swift | 1 | 2550 | //
// XMLDocument.swift
// TemplateKit
//
// Created by Matias Cudich on 9/25/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import Foundation
class XMLElement: Equatable {
var name: String
var value: String?
weak var parent: XMLElement?
lazy var children = [XMLElement]()
lazy var attributes = [String: String]()
init(name: String, attributes: [String: String]) {
self.name = name
self.attributes = attributes
}
func addChild(name: String, attributes: [String: String]) -> XMLElement {
let element = XMLElement(name: name, attributes: attributes)
element.parent = self
children.append(element)
return element
}
}
func ==(lhs: XMLElement, rhs: XMLElement) -> Bool {
return lhs.name == rhs.name && lhs.attributes == rhs.attributes && lhs.children == rhs.children
}
enum XMLError: Error {
case parserError(String)
}
class XMLDocument: NSObject, XMLParserDelegate {
let data: Data
private(set) var root: XMLElement?
private var currentParent: XMLElement?
private var currentElement: XMLElement?
private var currentValue = ""
private var parseError: Error?
init(data: Data) throws {
self.data = data
super.init()
try parse()
}
private func parse() throws {
let parser = XMLParser(data: data)
parser.delegate = self
guard parser.parse() else {
guard let error = parseError else {
throw XMLError.parserError("Failure parsing: \(parseError?.localizedDescription)")
}
throw error
}
}
@objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElement = currentParent?.addChild(name: elementName, attributes: attributeDict) ?? XMLElement(name: elementName, attributes: attributeDict)
if root == nil {
root = currentElement!
}
currentParent = currentElement
}
@objc func parser(_ parser: XMLParser, foundCharacters string: String) {
currentValue += string
let newValue = currentValue.trimmingCharacters(in: .whitespacesAndNewlines)
currentElement?.value = newValue.isEmpty ? nil : newValue
}
@objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentParent = currentParent?.parent
currentElement = nil
currentValue = ""
}
@objc func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
self.parseError = parseError
}
}
| mit | 837095dfe4ec033ab41310c9f8e47065 | 27.010989 | 177 | 0.699098 | 4.511504 | false | false | false | false |
richardbuckle/Laurine | Example/Laurine/Classes/Views/Cells/ContributorCell.swift | 1 | 2266 | //
// PersonCell.swift
// Laurine Example Project
//
// Created by Jiří Třečák.
// Copyright © 2015 Jiri Trecak. All rights reserved.
//
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Imports
import Foundation
import UIKit
import Haneke
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Definitions
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Extension
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Protocols
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Implementation
class ContributorCell: UITableViewCell {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
@IBOutlet private weak var personNameLb : UILabel!
@IBOutlet private weak var personContributions : UILabel!
@IBOutlet private weak var personIconIV : UIImageView!
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Actions
func configureWithContributor(contributor : Contributor) {
// Set username
self.personNameLb.text = contributor.username
// Set number of contribution
self.personContributions.text = contributor.contributions == 1 ?
Localizations.Contributors.Contributor.Contributed.Singular :
Localizations.Contributors.Contributor.Contributed.Plural(contributor.contributions)
// Set profile picture, if available
if let profilePictureURL = NSURL(string: contributor.avatarURL) {
self.personIconIV.hnk_setImageFromURL(profilePictureURL)
}
}
}
| mit | 17f3d0e6e739e2dcf49b838501719a71 | 30.388889 | 124 | 0.374779 | 4.493042 | false | false | false | false |
HighBay/EasyTimer | Sources/EasyTimer.swift | 2 | 6295 | //
// EasyTimer.swift
// EasyTimer
//
// Created by Niklas Fahl on 3/2/16.
// Copyright © 2016 Niklas. All rights reserved.
//
import Foundation
// MARK: - NSTimeInterval Extension for easy timer functionality
extension TimeInterval {
/// Create a timer that will call `block` once or repeatedly in specified time intervals.
///
/// - Note: The timer won't fire until it's scheduled on the run loop. To start it use the start function.
/// Use the delay or interval functions to create and schedule a timer in one step.
///
/// - Parameters:
/// - repeats: Bool representing if timer repeats.
/// - delays: Bool representing if timer executes immediately
/// - block: Code in block will run in every timer repetition.
/// - returns: A new NSTimer instance
func timer(repeats: Bool, delays: Bool, _ block: @escaping () -> Void) -> Timer {
if !delays {
block()
}
if repeats {
return CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + self, self, 0, 0) { _ in
block()
}
} else {
return CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + self, 0, 0, 0) { _ in
block()
}
}
}
/// Create a timer that will call `block` once or repeatedly in specified time intervals.
///
/// - Note: The timer won't fire until it's scheduled on the run loop. To start it use the start function.
/// Use the delay or interval functions to create and schedule a timer in one step.
///
/// - Parameters:
/// - repeats: Bool representing if timer repeats.
/// - block: Code in block will run in every timer repetition. (NSTimer available as parameter in block)
/// - returns: A new NSTimer instance
func timer(repeats: Bool, delays: Bool, _ block: @escaping (Timer) -> Void) -> Timer {
if repeats {
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + self, self, 0, 0) { timer in
block(timer!)
}
if !delays {
block(timer!)
}
return timer!
} else {
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + self, 0, 0, 0) { timer in
block(timer!)
}
if !delays {
block(timer!)
}
return timer!
}
}
/// Create and schedule a timer that will call `block` once with delay of time interval it is called on.
///
/// - Parameters:
/// - block: Code in `block` will run once after delay.
/// - returns: A new NSTimer instance
public func delay(block: @escaping () -> Void) -> Timer {
let timer = self.timer(repeats: false, delays: true, block)
timer.start()
return timer
}
/// Create and schedule a timer that will call `block` once with delay of time interval it is called on.
///
/// - Parameters:
/// - block: Code in `block` will run once after delay. (NSTimer available as parameter in `block`)
/// - returns: A new NSTimer instance
public func delay(block: @escaping (Timer) -> Void) -> Timer {
let timer = self.timer(repeats: false, delays: true, block)
timer.start()
return timer
}
/// Create and schedule a timer that will call `block` repeatedly in time interval it is called on without delay.
///
/// - Parameters:
/// - block: Code in `block` will run in every timer repetition.
/// - returns: A new NSTimer instance
public func interval(block: @escaping () -> Void) -> Timer {
let timer = self.timer(repeats: true, delays: false, block)
timer.start()
return timer
}
/// Create and schedule a timer that will call `block` repeatedly in time interval it is called on without delay.
///
/// - Parameters:
/// - block: Code in `block` will run in every timer repetition. (NSTimer available as parameter in `block`)
/// - returns: A new NSTimer instance
public func interval(block: @escaping (Timer) -> Void) -> Timer {
let timer = self.timer(repeats: true, delays: false, block)
timer.start()
return timer
}
/// Create and schedule a timer that will call `block` repeatedly in time interval it is called on delayed by the same time interval.
///
/// - Parameters:
/// - block: Code in `block` will run in every timer repetition.
/// - returns: A new NSTimer instance
public func delayedInterval(block: @escaping () -> Void) -> Timer {
let timer = self.timer(repeats: true, delays: true, block)
timer.start()
return timer
}
/// Create and schedule a timer that will call `block` repeatedly in time interval it is called on delayed by the same time interval.
///
/// - Parameters:
/// - block: Code in `block` will run in every timer repetition. (NSTimer available as parameter in `block`)
/// - returns: A new NSTimer instance
public func delayedInterval(block: @escaping (Timer) -> Void) -> Timer {
let timer = self.timer(repeats: true, delays: true, block)
timer.start()
return timer
}
}
// MARK: - NSTimer Extension for timer start and cancel functionality
extension Timer {
/// Schedules this timer on the run loop
///
/// By default, the timer is scheduled on the current run loop for the default mode.
/// Specify `runLoop` or `modes` to override these defaults.
public func start(runLoop: RunLoop = RunLoop.current) {
runLoop.add(self, forMode: RunLoopMode.defaultRunLoopMode)
}
/// Remove this timer from the run loop
///
/// By default, the timer is removed from the current run loop for the default mode.
/// Specify `runLoop` or `modes` to override these defaults.
public func stop(runLoop: RunLoop = RunLoop.current) {
self.invalidate()
CFRunLoopRemoveTimer(runLoop.getCFRunLoop(), self, CFRunLoopMode.defaultMode)
}
}
| bsd-3-clause | b6259249eb39f0e125f670371daef60d | 39.87013 | 137 | 0.611376 | 4.577455 | false | false | false | false |
Szaq/swift-cl | SwiftCL/Memory.swift | 1 | 837 | //
// Buffer.swift
// ReceiptRecognizer
//
// Created by Lukasz Kwoska on 03/12/14.
// Copyright (c) 2014 Spinal Development. All rights reserved.
//
import Foundation
import OpenCL
public class Memory {
public let id: cl_mem
public let size: UInt
public init(id: cl_mem, hostPtr: UnsafeMutablePointer<Void> = nil) {
self.id = id
data = hostPtr
size = 0
}
public let data: UnsafeMutablePointer<Void>
public init(context:Context, flags: Int32, size: UInt, hostPtr: UnsafeMutablePointer<Void> = nil) throws {
data = hostPtr
self.size = size
let ptr: UnsafeMutablePointer<Void> = ((flags & CL_MEM_USE_HOST_PTR) != 0) ? data : nil
var status: cl_int = 0
self.id = clCreateBuffer(context.id, cl_mem_flags(flags), Int(size), ptr, &status)
try CLError.check(status)
}
} | mit | e95b8413f4e6e3645a690a54262d08c7 | 23.647059 | 108 | 0.661888 | 3.458678 | false | false | false | false |
producthunt/PHImageKit | PHImageKit/Categories/UIView+ImageKit.swift | 1 | 3610 | //
// UIView+ImageKit.swift
// PHImageKit
//
// Copyright (c) 2016 Product Hunt (http://producthunt.com)
//
// 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
extension UIView {
func ik_setConstraintsToSuperview() {
guard let superview = superview else {
return
}
self.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)
let leftConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)
let rightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0)
superview.addConstraints([topConstraint, bottomConstraint, leftConstraint, rightConstraint])
}
func ik_setConstraintsToSuperviewCenter(_ size: CGSize) {
guard let superview = superview else {
return
}
self.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: size.width)
let heightConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: size.height)
let centerXConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: superview, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
superview.addConstraints([widthConstraint, heightConstraint, centerXConstraint, centerYConstraint])
}
}
| mit | dcae329a89688689feac82b7d3fe267b | 59.166667 | 242 | 0.766759 | 5.239478 | false | false | false | false |
inkyfox/SwiftySQL | Sources/SQLIn.swift | 3 | 1163 | //
// SQLIn.swift
// SwiftySQL
//
// Created by Yongha Yoo (inkyfox) on 2016. 10. 24..
// Copyright © 2016년 Gen X Hippies Company. All rights reserved.
//
import Foundation
public struct SQLIn: SQLOperaorExprType, SQLValueType, SQLConditionType, SQLAliasable {
let expr: SQLExprType
let isIn: Bool
let table: SQLSourceTableType
public init(_ expr: SQLExprType, in table: SQLSourceTableType) {
self.expr = expr
self.isIn = true
self.table = table
}
public init(_ expr: SQLExprType, notIn table: SQLSourceTableType) {
self.expr = expr
self.isIn = false
self.table = table
}
}
extension SQLExprType {
public func `in`(_ table: SQLSourceTableType) -> SQLIn {
return SQLIn(self, in: table)
}
public func `in`(_ exprs: SQLExprType...) -> SQLIn {
return SQLIn(self, in: SQLTuple(exprs))
}
public func notIn(_ table: SQLSourceTableType) -> SQLIn {
return SQLIn(self, notIn: table)
}
public func notIn(_ exprs: SQLExprType...) -> SQLIn {
return SQLIn(self, notIn: SQLTuple(exprs))
}
}
| mit | 3b928caaed0dc42a078ccc3b1a0a9faf | 22.673469 | 87 | 0.612931 | 3.694268 | false | false | false | false |
nanjingboy/SwiftImageSlider | Source/ImageSliderView.swift | 1 | 3356 | import UIKit
open class ImageSliderView: UIView, UIScrollViewDelegate, ImageSliderCellDelegate {
fileprivate var currentIndex: Int
fileprivate var sliderCells: [ImageSliderCell] = []
fileprivate var isUpdatingCellFrames = false
open var delegate: ImageSliderViewDelegate?
open let scrollView = UIScrollView()
open override var bounds: CGRect {
didSet {
updateCellFrames()
}
}
public init(currntIndex: Int, imageUrls: [String]) {
self.currentIndex = currntIndex
super.init(frame: CGRect.zero)
initialize(imageUrls)
}
public required init?(coder aDecoder: NSCoder) {
self.currentIndex = 0
super.init(coder: aDecoder)
initialize([])
}
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (isUpdatingCellFrames) {
isUpdatingCellFrames = false
return
}
self.scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0)
let width = self.scrollView.frame.width
let index = Int(floor((self.scrollView.contentOffset.x - width / 2) / width) + 1)
if (currentIndex != index) {
switchImage(index)
}
}
func initialize(_ imageUrls: [String]) {
clipsToBounds = false
scrollView.scrollsToTop = false
scrollView.isPagingEnabled = true
scrollView.delegate = self
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.autoresizesSubviews = false
scrollView.autoresizingMask = UIViewAutoresizing()
scrollView.translatesAutoresizingMaskIntoConstraints = false
for imageUrl in imageUrls {
let sliderCell = ImageSliderCell(imageUrl: imageUrl)
sliderCell.delegate = self
sliderCells.append(sliderCell)
scrollView.addSubview(sliderCell)
}
addSubview(scrollView)
}
func updateCellFrames() {
let pageCount = sliderCells.count
let sliderViewFrame = bounds
isUpdatingCellFrames = true
scrollView.frame = sliderViewFrame
scrollView.contentSize = CGSize(width: sliderViewFrame.size.width * CGFloat(pageCount),
height: sliderViewFrame.size.height * CGFloat(pageCount))
scrollView.contentOffset = CGPoint(x: CGFloat(currentIndex) * sliderViewFrame.size.width, y: 0)
let scrollViewBounds = scrollView.bounds
for index in 0 ..< pageCount {
let sliderCell = sliderCells[index]
sliderCell.frame = CGRect(x: scrollViewBounds.width * CGFloat(index),
y: scrollViewBounds.minY,
width: scrollViewBounds.width,
height: scrollViewBounds.height)
}
switchImage(currentIndex)
}
func switchImage(_ index: Int) {
let sliderCell = sliderCells[index]
sliderCell.loadImage()
currentIndex = index
delegate?.imageSliderViewImageSwitch(index, count: sliderCells.count, imageUrl: sliderCell.imageUrl)
}
func imageSliderCellSingleTap(_ tap: UITapGestureRecognizer) {
delegate?.imageSliderViewSingleTap(tap)
}
}
| mit | 62b0b40ae6f750349b7ac12b703f0f60 | 33.597938 | 108 | 0.6323 | 5.3696 | false | false | false | false |
xwu/swift | test/Generics/generic_types.swift | 1 | 6155 | // RUN: %target-typecheck-verify-swift
protocol MyFormattedPrintable {
func myFormat() -> String
}
func myPrintf(_ format: String, _ args: MyFormattedPrintable...) {}
extension Int : MyFormattedPrintable {
func myFormat() -> String { return "" }
}
struct S<T : MyFormattedPrintable> {
var c : T
static func f(_ a: T) -> T {
return a
}
func f(_ a: T, b: Int) {
return myPrintf("%v %v %v", a, b, c)
}
}
func makeSInt() -> S<Int> {}
typealias SInt = S<Int>
var a : S<Int> = makeSInt()
a.f(1,b: 2)
var b : Int = SInt.f(1)
struct S2<T> {
@discardableResult
static func f() -> T {
S2.f()
}
}
struct X { }
var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}}
enum Optional<T> {
case element(T)
case none
init() { self = .none }
init(_ t: T) { self = .element(t) }
}
typealias OptionalInt = Optional<Int>
var uniontest1 : (Int) -> Optional<Int> = OptionalInt.element
var uniontest2 : Optional<Int> = OptionalInt.none
var uniontest3 = OptionalInt(1)
// FIXME: Stuff that should work, but doesn't yet.
// var uniontest4 : OptInt = .none
// var uniontest5 : OptInt = .Some(1)
func formattedTest<T : MyFormattedPrintable>(_ a: T) {
myPrintf("%v", a)
}
struct formattedTestS<T : MyFormattedPrintable> {
func f(_ a: T) {
formattedTest(a)
}
}
struct GenericReq<T : IteratorProtocol, U : IteratorProtocol>
where T.Element == U.Element {
}
func getFirst<R : IteratorProtocol>(_ r: R) -> R.Element {
var r = r
return r.next()!
}
func testGetFirst(ir: Range<Int>) {
_ = getFirst(ir.makeIterator()) as Int
}
struct XT<T> {
init(t : T) {
prop = (t, t)
}
static func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
class YT<T> {
init(_ t : T) {
prop = (t, t)
}
deinit {}
class func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
struct ZT<T> {
var x : T, f : Float
}
struct Dict<K, V> {
subscript(key: K) -> V { get {} set {} }
}
class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}}
subscript(key: K) -> V { get {} set {} }
}
typealias XI = XT<Int>
typealias YI = YT<Int>
typealias ZI = ZT<Int>
var xi = XI(t: 17)
var yi = YI(17)
var zi = ZI(x: 1, f: 3.0)
var i : Int = XI.f()
i = XI.f()
i = xi.g()
i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}}
i = yi.g()
var xif : (XI) -> () -> Int = XI.g
var gif : (YI) -> () -> Int = YI.g
var ii : (Int, Int) = xi.prop
ii = yi.prop
xi.prop = ii
yi.prop = ii
var d1 : Dict<String, Int>
var d2 : Dictionary<String, Int>
d1["hello"] = d2["world"]
i = d2["blarg"]
struct RangeOfPrintables<R : Sequence>
where R.Iterator.Element : MyFormattedPrintable {
var r : R
func format() -> String {
var s : String
for e in r {
s = s + e.myFormat() + " "
}
return s
}
}
struct Y {}
struct SequenceY : Sequence, IteratorProtocol {
typealias Iterator = SequenceY
typealias Element = Y
func next() -> Element? { return Y() }
func makeIterator() -> Iterator { return self }
}
func useRangeOfPrintables(_ roi : RangeOfPrintables<[Int]>) {
var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'Sequence'}}
var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'SequenceY.Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}}
}
var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}}
var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}{{21-28=}}
var notgenericNested : Array<Int<Float>> // expected-error{{cannot specialize non-generic type 'Int'}}{{33-40=}}
// Make sure that redundant typealiases (that map to the same
// underlying type) don't break protocol conformance or use.
class XArray : ExpressibleByArrayLiteral {
typealias Element = Int
init() { }
required init(arrayLiteral elements: Int...) { }
}
class YArray : XArray {
typealias Element = Int
required init(arrayLiteral elements: Int...) {
super.init()
}
}
var yarray : YArray = [1, 2, 3]
var xarray : XArray = [1, 2, 3]
// Type parameters can be referenced only via unqualified name lookup
struct XParam<T> { // expected-note{{'XParam' declared here}}
func foo(_ x: T) {
_ = x as T
}
static func bar(_ x: T) {
_ = x as T
}
}
var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of generic struct 'generic_types.XParam<Swift.Int>'}}
// Diagnose failure to meet a superclass requirement.
class X1 { }
class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}}
class X3 { }
var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}}
protocol P {
associatedtype AssocP
}
protocol Q {
associatedtype AssocQ
}
struct X4 : P, Q {
typealias AssocP = Int
typealias AssocQ = String
}
struct X5<T, U> where T: P, T: Q, T.AssocP == T.AssocQ { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}}
var y: X5<X4, Int> // expected-error{{'X5' requires the types 'X4.AssocP' (aka 'Int') and 'X4.AssocQ' (aka 'String') be equivalent}}
// Recursive generic signature validation.
class Top {}
class Bottom<T : Bottom<Top>> {}
// expected-error@-1 {{'Bottom' requires that 'Top' inherit from 'Bottom<Top>'}}
// expected-note@-2 {{requirement specified as 'T' : 'Bottom<Top>' [with T = Top]}}
// expected-error@-3 {{generic class 'Bottom' has self-referential generic requirements}}
// expected-note@-4 {{while resolving type 'Bottom<Top>'}}
// expected-note@-5 {{through reference here}}
// Invalid inheritance clause
struct UnsolvableInheritance1<T : T.A> {}
// expected-error@-1 {{'A' is not a member type of type 'T'}}
struct UnsolvableInheritance2<T : U.A, U : T.A> {}
// expected-error@-1 {{'A' is not a member type of type 'U'}}
// expected-error@-2 {{'A' is not a member type of type 'T'}}
enum X7<T> where X7.X : G { case X } // expected-error{{enum case 'X' is not a member type of 'X7<T>'}}
// expected-error@-1{{cannot find type 'G' in scope}}
| apache-2.0 | 901dd7c799b13f183a8aeb8d9d71d0d7 | 23.919028 | 148 | 0.636068 | 3.065239 | false | false | false | false |
xwu/swift | test/Generics/protocol_type_aliases.swift | 4 | 3392 | // RUN: %target-typecheck-verify-swift
// RUN: %target-typecheck-verify-swift -debug-generic-signatures > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
func sameType<T>(_: T.Type, _: T.Type) {}
protocol P {
associatedtype A // expected-note{{'A' declared here}}
typealias X = A
}
protocol Q {
associatedtype B: P
}
// CHECK-LABEL: .requirementOnNestedTypeAlias@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Q, τ_0_0.B.A == Int>
func requirementOnNestedTypeAlias<T>(_: T) where T: Q, T.B.X == Int {}
struct S<T> {}
protocol P2 {
associatedtype A
typealias X = S<A>
}
protocol Q2 {
associatedtype B: P2
associatedtype C
}
// CHECK-LABEL: .requirementOnConcreteNestedTypeAlias@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0.C == S<τ_0_0.B.A>>
func requirementOnConcreteNestedTypeAlias<T>(_: T) where T: Q2, T.C == T.B.X {}
// CHECK-LABEL: .concreteRequirementOnConcreteNestedTypeAlias@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0.C == τ_0_0.B.A>
func concreteRequirementOnConcreteNestedTypeAlias<T>(_: T) where T: Q2, S<T.C> == T.B.X {}
// expected-warning@-1 {{neither type in same-type constraint ('S<T.C>' or 'T.B.X' (aka 'S<T.B.A>')) refers to a generic parameter or associated type}}
// Incompatible concrete typealias types are flagged as such
protocol P3 {
typealias T = Int
}
protocol Q3: P3 { // expected-error{{generic signature requires types 'Int'}}
typealias T = Float
}
protocol P3_1 {
typealias T = Float
}
protocol Q3_1: P3, P3_1 {} // expected-error{{generic signature requires types 'Float'}}
// Subprotocols can force associated types in their parents to be concrete, and
// this should be understood for types constrained by the subprotocols.
protocol Q4: P {
typealias A = Int // expected-warning{{typealias overriding associated type 'A' from protocol 'P'}}
}
protocol Q5: P {
typealias X = Int
}
// fully generic functions that manipulate the archetypes in a P
func getP_A<T: P>(_: T.Type) -> T.A.Type { return T.A.self }
func getP_X<T: P>(_: T.Type) -> T.X.Type { return T.X.self }
// ... which we use to check if the compiler is following through the concrete
// same-type constraints implied by the subprotocols.
func checkQ4_A<T: Q4>(x: T.Type) { sameType(getP_A(x), Int.self) }
func checkQ4_X<T: Q4>(x: T.Type) { sameType(getP_X(x), Int.self) }
// FIXME: these do not work, seemingly mainly due to the 'recursive decl validation'
// FIXME in GenericSignatureBuilder.cpp.
/*
func checkQ5_A<T: Q5>(x: T.Type) { sameType(getP_A(x), Int.self) }
func checkQ5_X<T: Q5>(x: T.Type) { sameType(getP_X(x), Int.self) }
*/
// Typealiases happen to allow imposing same type requirements between parent
// protocols
protocol P6_1 {
associatedtype A // expected-note{{'A' declared here}}
}
protocol P6_2 {
associatedtype B
}
protocol Q6: P6_1, P6_2 {
typealias A = B // expected-warning{{typealias overriding associated type}}
}
func getP6_1_A<T: P6_1>(_: T.Type) -> T.A.Type { return T.A.self }
func getP6_2_B<T: P6_2>(_: T.Type) -> T.B.Type { return T.B.self }
func checkQ6<T: Q6>(x: T.Type) {
sameType(getP6_1_A(x), getP6_2_B(x))
}
protocol P7 {
typealias A = Int
}
protocol P7a : P7 {
associatedtype A // expected-warning{{associated type 'A' is redundant with type 'A' declared in inherited protocol 'P7'}}
}
| apache-2.0 | 9e6ec69b34d32210b229c76a8231919d | 30.598131 | 151 | 0.677906 | 3.032287 | false | false | false | false |
swizzlr/Moya | Source/ReactiveCocoa/Moya+ReactiveCocoa.swift | 2 | 1889 | import Foundation
import ReactiveCocoa
import Alamofire
/// Subclass of MoyaProvider that returns SignalProducer instances when requests are made. Much better than using completion closures.
public class ReactiveCocoaMoyaProvider<Target where Target: MoyaTarget>: MoyaProvider<Target> {
/// Initializes a reactive provider.
override public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = Alamofire.Manager.sharedInstance,
plugins: [Plugin<Target>] = []) {
super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins)
}
/// Designated request-making method.
public func request(token: Target) -> SignalProducer<MoyaResponse, NSError> {
// Creates a producer that starts a request each time it's started.
return SignalProducer { [weak self] observer, requestDisposable in
let cancellableToken = self?.request(token) { data, statusCode, response, error in
if let error = error {
observer.sendFailed(error as NSError)
} else {
if let data = data, let statusCode = statusCode {
observer.sendNext(MoyaResponse(statusCode: statusCode, data: data, response: response))
}
observer.sendCompleted()
}
}
requestDisposable.addDisposable {
// Cancel the request
cancellableToken?.cancel()
}
}
}
public func request(token: Target) -> RACSignal {
return toRACSignal(request(token))
}
}
| mit | 5b5998a29a7a0b2da8060cf551df80f4 | 43.97619 | 150 | 0.641609 | 5.903125 | false | false | false | false |
martinpucik/VIPER-Example | VIPER-Example/Modules/TakeOverview/View/CropViewController.swift | 1 | 3484 | //
// CropViewController.swift
// oneprove-ios
//
// Created by Lukáš Tesař on 01.02.17.
// Copyright © 2017 Oneprove. All rights reserved.
//
import UIKit
class CropViewController: UIViewController {
// MARK: - VIPER
var presenter: TakeOverviewPresenterInterface?
// MARK: - Variables
fileprivate var sourceImageView: UIImageView?
fileprivate var croppedImage: UIImage?
var overviewImage: UIImage?
fileprivate var initialRect: CGRect = .zero
fileprivate var finalRect: CGRect = .zero
fileprivate let cameraToolBarHeight: CGFloat = 120.0
fileprivate let navBarHeight: CGFloat = 80.0
fileprivate var cropped: Bool = false
// MARK: - Outlets
@IBOutlet weak var actionButton: UIButton!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
presenter?.viewDidAppear()
}
// MARK: - User Actions
@IBAction func actionButtonPressed(_ sender: UIButton) {
if cropped {
dismiss()
} else {
crop()
}
}
@IBAction func closeButtonTapped(_ sender: UIButton) {
presenter?.doneButtonTapped()
}
func crop() {
guard let presenter = presenter else { return }
updateActionButtonAccesibilityToCrop(enable: false)
let croppedImage = presenter.zoomImage
UIView.transition(with: sourceImageView!, duration: 0.3, options: .transitionCrossDissolve, animations: {
self.sourceImageView!.image = croppedImage
self.croppedImage = croppedImage
})
}
func dismiss() {
presenter?.doneButtonTapped()
}
}
extension CropViewController: CropViewInterface {
var cropImage: UIImage? {
return self.croppedImage
}
}
extension CropViewController: ViewProtocol {
func showFailure(withMessage message: String) {
// Show failure alert here
debugPrint("Showing failure: \(message)")
}
func showSuccess(withMessage message: String) {
// Show Success alert here
debugPrint("Showing success: \(message)")
}
}
fileprivate extension CropViewController {
func setupLayout() {
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
initSourceImageView()
setCroppedImageFrames()
updateActionButtonAccesibilityToCrop(enable: true)
}
func initSourceImageView() {
sourceImageView = UIImageView.init(frame: CGRect(x: 0, y: navBarHeight, width: self.view.bounds.size.width, height: self.view.bounds.size.height - cameraToolBarHeight - navBarHeight))
sourceImageView?.contentMode = .scaleAspectFit
sourceImageView?.clipsToBounds = true
view.addSubview(sourceImageView!)
if let overviewImage = overviewImage {
sourceImageView?.image = overviewImage
}
}
func setCroppedImageFrames() {
initialRect = sourceImageView!.frame
finalRect = sourceImageView!.frame
}
func updateActionButtonAccesibilityToCrop(enable: Bool) {
if enable {
actionButton.setTitle("CHECK & CROP", for: .normal)
cropped = false
} else {
actionButton.setTitle("CONTINUE", for: .normal)
cropped = true
}
}
}
| mit | 74a2a769cc57e3e27f53a70b7bb8bf06 | 28 | 191 | 0.64023 | 5.125184 | false | false | false | false |
ptangen/equityStatus | EquityStatus/QuestionMeasureView.swift | 1 | 13525 | //
// QuestionMeasureView.swift
// EquityStatus
//
// Created by Paul Tangen on 1/27/17.
// Copyright © 2017 Paul Tangen. All rights reserved.
//
import UIKit
import SQLite
class QuestionMeasureView: UIView, UITextViewDelegate {
weak var delegate: MeasureDetailViewDelegate?
let store = DataStore.sharedInstance
var company: Company!
var measure = String()
var measureLongNameLabel = UILabel()
var statusLabel = UILabel()
var statusIcon = UILabel()
var statusValueDesc = UILabel()
var qStatusPicker = UISegmentedControl()
var qAnswerView = UITextView()
var qAnswerViewDidChange = false
let companiesTable = Table("companiesTable")
let tickerCol = Expression<String>("tickerCol")
let q1_answerCol = Expression<String?>("q1_answerCol")
let q2_answerCol = Expression<String?>("q2_answerCol")
let q3_answerCol = Expression<String?>("q3_answerCol")
let q4_answerCol = Expression<String?>("q4_answerCol")
let q5_answerCol = Expression<String?>("q5_answerCol")
let q6_answerCol = Expression<String?>("q6_answerCol")
let own_answerCol = Expression<String?>("own_answerCol")
let q1_passedCol = Expression<Bool?>("q1_passedCol")
let q2_passedCol = Expression<Bool?>("q2_passedCol")
let q3_passedCol = Expression<Bool?>("q3_passedCol")
let q4_passedCol = Expression<Bool?>("q4_passedCol")
let q5_passedCol = Expression<Bool?>("q5_passedCol")
let q6_passedCol = Expression<Bool?>("q6_passedCol")
let own_passedCol = Expression<Bool?>("own_passedCol")
override init(frame:CGRect){
super.init(frame: frame)
self.pageLayout()
// configure segmented control to pick status for the measure
self.qStatusPicker.insertSegment(withTitle: "?", at: 0, animated: true)
self.qStatusPicker.insertSegment(withTitle: "p", at: 1, animated: true)
self.qStatusPicker.insertSegment(withTitle: "f", at: 2, animated: true)
//self.qStatusPicker.setTitleTextAttributes([ NSAttributedString.Key.font: UIFont(name: Constants.iconFont.fontAwesome.rawValue, size: Constants.iconSize.small.rawValue) ], for: .normal)
let segmentButtonWidth = UIScreen.main.bounds.width / 4
self.qStatusPicker.setWidth(segmentButtonWidth, forSegmentAt: 0)
self.qStatusPicker.setWidth(segmentButtonWidth, forSegmentAt: 1)
self.qStatusPicker.setWidth(segmentButtonWidth, forSegmentAt: 2)
self.qStatusPicker.tintColor = UIColor(named: .blue)
self.qStatusPicker.addTarget(self, action: #selector(self.statusValueChanged), for: .valueChanged)
self.qAnswerView.delegate = self
}
@objc func statusValueChanged(_ sender:UISegmentedControl!) {
self.qAnswerView.resignFirstResponder()
switch sender.selectedSegmentIndex {
case 1:
self.updateQStatus(passedOptional: true)
case 2:
self.updateQStatus(passedOptional: false)
default:
self.updateQStatus(passedOptional: nil)
}
}
func updateQStatus(passedOptional: Bool?) {
let database = DBUtilities.getDBConnection()
let selectedTickerQuestion = self.companiesTable.filter(self.tickerCol == self.company.ticker)
do {
//get the column to update and submit the query
try database.run(selectedTickerQuestion.update(getMeasurePassedColumn(measure: measure) <- passedOptional))
self.setMeasurePassedObjectProperty(measure: measure, passed: passedOptional)
Utilities.getStatusIcon(status: passedOptional, uiLabel: self.statusIcon)
} catch {
print(error)
}
}
func updateQAnswer(answer: String) {
let database = DBUtilities.getDBConnection()
let selectedTickerQuestion = self.companiesTable.filter(self.tickerCol == self.company.ticker)
do {
//get the column to update and submit the query
try database.run(selectedTickerQuestion.update(getMeasureAnswerColumn(measure: measure) <- answer))
// update the object property TODO: use setter
self.setMeasureAnswerObjectProperty(measure: measure, answer: answer)
} catch {
print(error)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func getStatusDesc(passed: Bool?) -> String {
if let passedUnwrapped = passed {
return passedUnwrapped.description
} else {
return "no data"
}
}
func setTextInQAnswerView(textToDisplay: String) {
// set the comment in the qAnswerView
if textToDisplay.isEmpty {
self.qAnswerView.text = "Comments"
self.qAnswerView.textColor = UIColor(named: .disabledText)
} else {
self.qAnswerView.text = textToDisplay
self.qAnswerView.textColor = UIColor.black
}
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == UIColor(named: .disabledText) {
self.qAnswerView.text = nil
self.qAnswerView.textColor = UIColor.black
}
}
func textViewDidChange(_ textView: UITextView) {
self.qAnswerViewDidChange = true
}
func textViewDidEndEditing(_ textView: UITextView) {
// send text to the DB
self.qAnswerViewDidChange ? self.updateQAnswer(answer: textView.text) : ()
if textView.text.isEmpty {
textView.text = "Comment"
textView.textColor = UIColor(named: .disabledText)
}
}
func pageLayout() {
// measureLongNameLabel
self.addSubview(self.measureLongNameLabel)
self.measureLongNameLabel.translatesAutoresizingMaskIntoConstraints = false
self.measureLongNameLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 30).isActive = true
self.measureLongNameLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10).isActive = true
self.measureLongNameLabel.preferredMaxLayoutWidth = UIScreen.main.bounds.width - 20
self.measureLongNameLabel.font = UIFont(name: Constants.appFont.bold.rawValue, size: Constants.fontSize.small.rawValue)
self.measureLongNameLabel.numberOfLines = 0
// statusLabel
self.addSubview(self.statusLabel)
self.statusLabel.translatesAutoresizingMaskIntoConstraints = false
self.statusLabel.topAnchor.constraint(equalTo: self.measureLongNameLabel.bottomAnchor, constant: 30).isActive = true
self.statusLabel.leftAnchor.constraint(equalTo: self.measureLongNameLabel.leftAnchor).isActive = true
self.statusLabel.font = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.small.rawValue)
// statusIcon
self.addSubview(self.statusIcon)
self.statusIcon.translatesAutoresizingMaskIntoConstraints = false
self.statusIcon.topAnchor.constraint(equalTo: self.statusLabel.topAnchor, constant: 0).isActive = true
self.statusIcon.leftAnchor.constraint(equalTo: self.statusLabel.rightAnchor, constant: 8).isActive = true
self.statusIcon.font = UIFont(name: Constants.iconFont.fontAwesome.rawValue, size: Constants.iconSize.xsmall.rawValue)
// statusValueDesc
self.addSubview(self.statusValueDesc)
self.statusValueDesc.translatesAutoresizingMaskIntoConstraints = false
self.statusValueDesc.topAnchor.constraint(equalTo: self.statusIcon.topAnchor, constant: 0).isActive = true
self.statusValueDesc.leftAnchor.constraint(equalTo: self.statusIcon.rightAnchor, constant: 8).isActive = true
self.statusValueDesc.font = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.small.rawValue)
// qStatusPicker
self.addSubview(self.qStatusPicker)
self.qStatusPicker.translatesAutoresizingMaskIntoConstraints = false
self.qStatusPicker.topAnchor.constraint(equalTo: self.statusValueDesc.bottomAnchor, constant: 40).isActive = true
self.qStatusPicker.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.qStatusPicker.heightAnchor.constraint(equalToConstant: 50).isActive = true
self.addSubview(self.qAnswerView)
self.qAnswerView.translatesAutoresizingMaskIntoConstraints = false
self.qAnswerView.topAnchor.constraint(equalTo: self.qStatusPicker.bottomAnchor, constant: 30).isActive = true
self.qAnswerView.leftAnchor.constraint(equalTo: self.qStatusPicker.leftAnchor, constant: -30).isActive = true
self.qAnswerView.rightAnchor.constraint(equalTo: self.qStatusPicker.rightAnchor, constant: 30).isActive = true
self.qAnswerView.heightAnchor.constraint(equalToConstant: 100).isActive = true
self.qAnswerView.font = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.small.rawValue)
self.qAnswerView.layer.borderColor = UIColor(named: .blue).cgColor
self.qAnswerView.layer.borderWidth = 1.0
}
func getMeasureResultsAndSetLabelText(passed: Bool?, longName: String, answer: String?) {
if let passedUnwrapped = passed {
if passedUnwrapped {
self.qStatusPicker.selectedSegmentIndex = 1
} else {
self.qStatusPicker.selectedSegmentIndex = 2
}
} else {
self.qStatusPicker.selectedSegmentIndex = 0
}
self.measureLongNameLabel.text = longName
Utilities.getStatusIcon(status: passed, uiLabel: self.statusIcon)
if let answerUnwrapped = answer {
self.setTextInQAnswerView(textToDisplay: answerUnwrapped)
}
}
func setResultsLabelsForMeasure(measure: String) {
self.statusLabel.text = "Status:"
let measureInfo = self.store.measureInfo[measure]!
let questions_passed:[String: Bool?] = [
"q1" : self.company.q1_passed,
"q2" : self.company.q2_passed,
"q3" : self.company.q3_passed,
"q4" : self.company.q4_passed,
"q5" : self.company.q5_passed,
"q6" : self.company.q6_passed,
"own" : self.company.own_passed
]
let questions_answer:[String: String?] = [
"q1" : self.company.q1_answer,
"q2" : self.company.q2_answer,
"q3" : self.company.q3_answer,
"q4" : self.company.q4_answer,
"q5" : self.company.q5_answer,
"q6" : self.company.q6_answer,
"own" : self.company.own_answer
]
self.getMeasureResultsAndSetLabelText(
passed: questions_passed[measure]!, longName: measureInfo["longName"]!, answer: questions_answer[measure]!
)
}
func getMeasurePassedColumn(measure: String) -> Expression<Bool?> {
// get column to update
switch measure {
case "q1":
return self.q1_passedCol
case "q2":
return self.q2_passedCol
case "q3":
return self.q3_passedCol
case "q4":
return self.q4_passedCol
case "q5":
return self.q5_passedCol
case "q6":
return self.q6_passedCol
case "own":
return self.own_passedCol
default:
return Expression<Bool?>("")
}
}
func getMeasureAnswerColumn(measure: String) -> Expression<String?> {
// get column to update
switch measure {
case "q1":
return self.q1_answerCol
case "q2":
return self.q2_answerCol
case "q3":
return self.q3_answerCol
case "q4":
return self.q4_answerCol
case "q5":
return self.q5_answerCol
case "q6":
return self.q6_answerCol
case "own":
return self.own_answerCol
default:
return Expression<String?>("")
}
}
func setMeasurePassedObjectProperty(measure: String, passed: Bool?) {
// update object value
switch measure {
case "q1":
self.company.q1_passed = passed
case "q2":
self.company.q2_passed = passed
case "q3":
self.company.q3_passed = passed
case "q4":
self.company.q4_passed = passed
case "q5":
self.company.q5_passed = passed
case "q6":
self.company.q6_passed = passed
case "own":
self.company.own_passed = passed
default:
break
}
}
func setMeasureAnswerObjectProperty(measure: String, answer: String?) {
// update object value
switch measure {
case "q1":
self.company.q1_answer = answer
case "q2":
self.company.q2_answer = answer
case "q3":
self.company.q3_answer = answer
case "q4":
self.company.q4_answer = answer
case "q5":
self.company.q5_answer = answer
case "q6":
self.company.q6_answer = answer
case "own":
self.company.own_answer = answer
default:
break
}
}
}
| apache-2.0 | 3de41b886191ebf99673d407797e3994 | 38.776471 | 194 | 0.636202 | 4.382372 | false | false | false | false |
ylovesy/CodeFun | mayu/RemoveDuplicatesFromSortedArray.swift | 1 | 811 | import Foundation
/*
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
*/
private class Solution {
func removeDuplicates(_ nums: inout [Int]) -> Int {
if nums.count == 0 {
return 0
}
var curIndex = 0
for val in nums {
if nums[curIndex] < val {
curIndex += 1
nums[curIndex] = val
}
}
return curIndex + 1
}
}
| apache-2.0 | cf91e49c958c3ce416835a5f814c7437 | 32.791667 | 160 | 0.617756 | 4.407609 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Lint/YodaConditionRule.swift | 1 | 4754 | import SwiftSyntax
struct YodaConditionRule: OptInRule, ConfigurationProviderRule, SwiftSyntaxRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "yoda_condition",
name: "Yoda condition rule",
description: "The constant literal should be placed on the right-hand side of the comparison operator.",
kind: .lint,
nonTriggeringExamples: [
Example("if foo == 42 {}\n"),
Example("if foo <= 42.42 {}\n"),
Example("guard foo >= 42 else { return }\n"),
Example("guard foo != \"str str\" else { return }"),
Example("while foo < 10 { }\n"),
Example("while foo > 1 { }\n"),
Example("while foo + 1 == 2 {}"),
Example("if optionalValue?.property ?? 0 == 2 {}"),
Example("if foo == nil {}"),
Example("if flags & 1 == 1 {}"),
Example("if true {}", excludeFromDocumentation: true),
Example("if true == false || b, 2 != 3, {}", excludeFromDocumentation: true)
],
triggeringExamples: [
Example("if ↓42 == foo {}\n"),
Example("if ↓42.42 >= foo {}\n"),
Example("guard ↓42 <= foo else { return }\n"),
Example("guard ↓\"str str\" != foo else { return }"),
Example("while ↓10 > foo { }"),
Example("while ↓1 < foo { }"),
Example("if ↓nil == foo {}"),
Example("while ↓1 > i + 5 {}"),
Example("if ↓200 <= i && i <= 299 || ↓600 <= i {}")
])
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
YodaConditionRuleVisitor(viewMode: .sourceAccurate)
}
}
private final class YodaConditionRuleVisitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: IfStmtSyntax) {
visit(conditions: node.conditions)
}
override func visitPost(_ node: GuardStmtSyntax) {
visit(conditions: node.conditions)
}
override func visitPost(_ node: RepeatWhileStmtSyntax) {
visit(condition: node.condition)
}
override func visitPost(_ node: WhileStmtSyntax) {
visit(conditions: node.conditions)
}
private func visit(conditions: ConditionElementListSyntax) {
for condition in conditions.compactMap({ $0.condition.as(ExprSyntax.self) }) {
visit(condition: condition)
}
}
private func visit(condition: ExprSyntax) {
guard let children = condition.as(SequenceExprSyntax.self)?.elements.children(viewMode: .sourceAccurate) else {
return
}
let comparisonOperators = children
.compactMap { $0.as(BinaryOperatorExprSyntax.self) }
.filter { ["==", "!=", ">", "<", ">=", "<="].contains($0.operatorToken.text) }
for comparisonOperator in comparisonOperators {
let rhsIdx = children.index(after: comparisonOperator.index)
if children[rhsIdx].isLiteral {
let afterRhsIndex = children.index(after: rhsIdx)
guard children.endIndex != rhsIdx, afterRhsIndex != nil else {
// This is already the end of the expression.
continue
}
if children[afterRhsIndex].isLogicalBinaryOperator {
// Next token is an operator with weaker binding. Thus, the literal is unique on the
// right-hand side of the comparison operator.
continue
}
}
let lhsIdx = children.index(before: comparisonOperator.index)
let lhs = children[lhsIdx]
if lhs.isLiteral {
if children.startIndex == lhsIdx || children[children.index(before: lhsIdx)].isLogicalBinaryOperator {
// Literal is at the very beginning of the expression or the previous token is an operator with
// weaker binding. Thus, the literal is unique on the left-hand side of the comparison operator.
violations.append(lhs.positionAfterSkippingLeadingTrivia)
}
}
}
}
}
private extension Syntax {
var isLiteral: Bool {
`is`(IntegerLiteralExprSyntax.self)
|| `is`(FloatLiteralExprSyntax.self)
|| `is`(BooleanLiteralExprSyntax.self)
|| `is`(StringLiteralExprSyntax.self)
|| `is`(NilLiteralExprSyntax.self)
}
var isLogicalBinaryOperator: Bool {
guard let binaryOperator = `as`(BinaryOperatorExprSyntax.self) else {
return false
}
return ["&&", "||"].contains(binaryOperator.operatorToken.text)
}
}
| mit | 90507854b09041bae28ad259f45cc6ba | 39.810345 | 119 | 0.575623 | 4.900621 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Documentation/RuleListDocumentation.swift | 1 | 4164 | import Foundation
/// User-facing documentation for a SwiftLint RuleList.
public struct RuleListDocumentation {
private let ruleDocumentations: [RuleDocumentation]
/// Creates a RuleListDocumentation instance from a RuleList.
///
/// - parameter list: A RuleList to document.
public init(_ list: RuleList) {
ruleDocumentations = list.list
.sorted { $0.0 < $1.0 }
.map { RuleDocumentation($0.value) }
}
/// Write the rule list documentation as markdown files to the specified directory.
///
/// - parameter url: Local URL for directory where the markdown files for this documentation should be saved.
///
/// - throws: Throws if the files could not be written to.
public func write(to url: URL) throws {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
func write(_ text: String, toFile file: String) throws {
try text.write(to: url.appendingPathComponent(file), atomically: false, encoding: .utf8)
}
try write(indexContents, toFile: "Rule Directory.md")
try write(swiftSyntaxDashboardContents, toFile: "Swift Syntax Dashboard.md")
for doc in ruleDocumentations {
try write(doc.fileContents, toFile: doc.fileName)
}
}
// MARK: - Private
private var indexContents: String {
let defaultRuleDocumentations = ruleDocumentations.filter { !$0.isOptInRule }
let optInRuleDocumentations = ruleDocumentations.filter { $0.isOptInRule }
return """
# Rule Directory
## Default Rules
\(defaultRuleDocumentations
.map { "* `\($0.ruleIdentifier)`: \($0.ruleName)" }
.joined(separator: "\n"))
## Opt-In Rules
\(optInRuleDocumentations
.map { "* `\($0.ruleIdentifier)`: \($0.ruleName)" }
.joined(separator: "\n"))
"""
}
private var swiftSyntaxDashboardContents: String {
let linterRuleDocumentations = ruleDocumentations.filter(\.isLinterRule)
let rulesUsingSourceKit = linterRuleDocumentations.filter(\.usesSourceKit)
let rulesNotUsingSourceKit = linterRuleDocumentations.filter { !$0.usesSourceKit }
let percentUsingSourceKit = Int(rulesUsingSourceKit.count * 100 / linterRuleDocumentations.count)
return """
# Swift Syntax Dashboard
Efforts are actively under way to migrate most rules off SourceKit to use SwiftSyntax instead.
Rules written using SwiftSyntax tend to be significantly faster and have fewer false positives
than rules that use SourceKit to get source structure information.
\(rulesUsingSourceKit.count) out of \(linterRuleDocumentations.count) (\(percentUsingSourceKit)%)
of SwiftLint's linter rules use SourceKit.
## Rules Using SourceKit
### Enabled By Default (\(rulesUsingSourceKit.filter(\.isEnabledByDefault).count))
\(rulesUsingSourceKit
.filter(\.isEnabledByDefault)
.map { "* `\($0.ruleIdentifier)`: \($0.ruleName)" }
.joined(separator: "\n"))
### Opt-In (\(rulesUsingSourceKit.filter(\.isDisabledByDefault).count))
\(rulesUsingSourceKit
.filter(\.isDisabledByDefault)
.map { "* `\($0.ruleIdentifier)`: \($0.ruleName)" }
.joined(separator: "\n"))
## Rules Not Using SourceKit
### Enabled By Default (\(rulesNotUsingSourceKit.filter(\.isEnabledByDefault).count))
\(rulesNotUsingSourceKit
.filter(\.isEnabledByDefault)
.map { "* `\($0.ruleIdentifier)`: \($0.ruleName)" }
.joined(separator: "\n"))
### Opt-In (\(rulesNotUsingSourceKit.filter(\.isDisabledByDefault).count))
\(rulesNotUsingSourceKit
.filter(\.isDisabledByDefault)
.map { "* `\($0.ruleIdentifier)`: \($0.ruleName)" }
.joined(separator: "\n"))
"""
}
}
| mit | 663ca8d92d5b41ec7058c5ed1e07e3ba | 37.555556 | 113 | 0.60951 | 4.85881 | false | false | false | false |
22377832/ccyswift | CoreDataFind/CoreDataFind/AppDelegate.swift | 1 | 6433 | //
// AppDelegate.swift
// CoreDataFind
//
// Created by sks on 17/2/24.
// Copyright © 2017年 chen. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let entityName = NSStringFromClass(Person.classForCoder())
func createNewPerson(_ name: String, age: Int64) -> Bool{
let context = persistentContainer.viewContext
let person = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! Person
person.name = name
person.age = age
do {
try context.save()
return true
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
return false
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
_ = createNewPerson("Danny", age: 18)
_ = createNewPerson("Tom", age: 20)
for _ in 0..<10{
_ = createNewPerson("Candy", age: Int64(arc4random_uniform(120)))
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let ageSort = NSSortDescriptor(key: "age", ascending: true)
fetchRequest.sortDescriptors = [ageSort]
do {
let persons = try persistentContainer.viewContext.fetch(fetchRequest) as! [Person]
if persons.count > 0{
var counter = 0
for person in persons{
//print(person.name ?? "noname")
print(person.age)
counter += 1
// persistentContainer.viewContext.delete(person)
// if person.isDeleted{
// print("delete succeed.")
// }
print("-------------")
}
print(counter)
saveContext()
}
} catch {
print(error)
}
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.
self.saveContext()
}
// MARK: - Core Data stack
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: "CoreDataFind")
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
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
print("save succeed.")
} 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 error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 01ea5e4ce32ab5680bb0fce322b6c97d | 41.582781 | 285 | 0.627838 | 5.771993 | false | false | false | false |
bigxodus/candlelight | candlelight/screen/main/view/BookmarkViewCell.swift | 1 | 666 | import UIKit
class BookmarkViewCell: UICollectionViewCell {
var textLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
let leftMargin = 20.0 as CGFloat
textLabel = UILabel(frame: CGRect(x: leftMargin, y: 0, width: frame.size.width - leftMargin, height: frame.size.height))
textLabel.textAlignment = .left
textLabel.textColor = UIColor(red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0)
contentView.addSubview(textLabel)
}
func setText(_ text: String) {
textLabel.text = text
}
} | apache-2.0 | 24a4994f60870805c2502eedba3f8ba3 | 26.791667 | 128 | 0.644144 | 4.036364 | false | false | false | false |
Prodisky/LASS-Dial | Data.swift | 1 | 5872 | //
// Data.swift
// LASS Dial
//
// Created by Paul Wu on 2016/2/1.
// Copyright © 2016年 Prodisky Inc. All rights reserved.
//
import UIKit
import CoreLocation
class Data: NSObject {
static let shared = Data()
struct Item {
var dataName = ""
var dataMin:CGFloat = 0
var dataMax:CGFloat = 0
var dataValue:CGFloat = 0
var dataString = ""
var dataFraction:CGFloat = 0
var dataUnit = ""
var siteName = ""
var siteLocation = CLLocation()
var siteDistance:Double = 0
var publishTime = ""
var colorR:CGFloat = 0
var colorG:CGFloat = 0
var colorB:CGFloat = 0
var colorA:CGFloat = 0
}
// MARK: -
private let dataURL = "http://www.prodisky.com/LASS/"
//預設位置座標 - 地圖的台灣預設中間點 - 信義鄉
private(set) var location:CLLocation = CLLocation(latitude: 23.597651, longitude: 120.997932)
private let defaults = NSUserDefaults()
var locationUpdate:(()->())?
let locationManager = CLLocationManager()
// MARK: -
func getItems(got:(([String])->Void)) {
guard let URL = NSURL(string: dataURL) else { return }
let request = NSURLRequest(URL: URL)
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
let session = NSURLSession(configuration: configuration, delegate:nil, delegateQueue:NSOperationQueue.mainQueue())
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
guard let gotData = data else { return }
do {
let gotObject = try NSJSONSerialization.JSONObjectWithData(gotData, options: .MutableContainers)
if let items = gotObject as? [String] {
got(items)
return
}
} catch { }
})
task.resume()
}
func getItem(data:String, got:((Item)->Void)) {
guard let URL = NSURL(string:"\(dataURL)?lat=\(self.location.coordinate.latitude)&lng=\(self.location.coordinate.longitude)&data=\(data)") else { return }
let request = NSURLRequest(URL: URL)
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.requestCachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
let session = NSURLSession(configuration: configuration, delegate:nil, delegateQueue:NSOperationQueue.mainQueue())
let task = session.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
guard let gotData = data else { return }
do {
let gotObject = try NSJSONSerialization.JSONObjectWithData(gotData, options: .MutableContainers)
if let item = gotObject as? Dictionary<String, AnyObject> {
guard let dataName = item["DataName"] as? String else { return }
guard let dataMin = item["DataMin"] as? CGFloat else { return }
guard let dataMax = item["DataMax"] as? CGFloat else { return }
guard let dataValue = item["DataValue"] as? CGFloat else { return }
guard let dataUnit = item["DataUnit"] as? String else { return }
guard let siteName = item["SiteName"] as? String else { return }
guard let siteLat = item["SiteLat"] as? Double else { return }
guard let siteLng = item["SiteLng"] as? Double else { return }
guard let publishTime = item["PublishTime"] as? String else { return }
guard let color = item["Color"] as? String else { return }
let colorRGBA = color.stringByReplacingOccurrencesOfString(" ", withString: "").componentsSeparatedByString(",")
if colorRGBA.count != 4 { return }
let dataString = dataValue == CGFloat(Int(dataValue)) ? String(Int(dataValue)) : String(dataValue)
let dataFraction = (dataMax-dataMin) > 0 ? (CGFloat(dataValue) - dataMin) / (dataMax-dataMin) : 0
let siteLocation:CLLocation = CLLocation(latitude: siteLat, longitude: siteLng)
let siteDistance = siteLocation.distanceFromLocation(Data.shared.location)
let colorR = CGFloat(Float(colorRGBA[0])!/Float(255))
let colorG = CGFloat(Float(colorRGBA[1])!/Float(255))
let colorB = CGFloat(Float(colorRGBA[2])!/Float(255))
let colorA = CGFloat(Float(colorRGBA[3])!)
got(Item(dataName: dataName, dataMin: dataMin, dataMax: dataMax, dataValue: dataValue, dataString: dataString, dataFraction: dataFraction, dataUnit: dataUnit, siteName: siteName, siteLocation: siteLocation, siteDistance: siteDistance, publishTime: publishTime, colorR: colorR, colorG: colorG, colorB: colorB, colorA: colorA))
return
}
} catch { }
})
task.resume()
}
// MARK: -
override init() {
super.init()
//若存在上次位置,就不使用預設值
if let lastLatitude = defaults.objectForKey("lastLatitude") as? String ,
let lastLongitude = defaults.objectForKey("lastLongitude") as? String {
location = CLLocation(latitude: Double(lastLatitude)!, longitude: Double(lastLongitude)!)
}
locationManager.delegate = self
locationManager.distanceFilter = 10
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters //kCLLocationAccuracyBest
}
deinit {
defaults.synchronize()
}
}
// MARK: CLLocationManagerDelegate
extension Data : CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let firstLocation = locations.first else { return }
location = firstLocation
defaults.setObject("\(location.coordinate.latitude)", forKey: "lastLatitude")
defaults.setObject("\(location.coordinate.longitude)", forKey: "lastLongitude")
defaults.synchronize()
if let locationUpdate = self.locationUpdate { locationUpdate() }
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
locationManager.requestLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
NSLog(" CLLocationManager didFailWithError Error \(error)")
}
}
| mit | e39f041464fe91339d7076e889db2bbd | 39.852113 | 330 | 0.72091 | 4.00069 | false | true | false | false |
mactive/rw-courses-note | AdvancedSwift3/Optional101 copy.playground/Contents.swift | 1 | 524 | //: Playground - noun: a place where people can play
//: http://www.jianshu.com/p/3c4e7dd6844f
import UIKit
var str = "Hello, playground"
var None:String? = Optional.none
print("None is \(None)")
None = "Something"
print("None is \(None)")
let beSure = None!
struct Jackson {
var pet: Pet?
var home: String
}
struct Pet {
var favoriteToy: String
var age: Int
}
let ppet:Pet = Pet(favoriteToy: "yoyo", age: 5)
let jackon: Jackson = Jackson(pet: ppet, home: "liaocheng")
print(jackon.pet?.favoriteToy) | mit | e7fbbe2254121c89df9b1172cde87012 | 17.103448 | 59 | 0.675573 | 2.895028 | false | false | false | false |
RxSwiftCommunity/RxSwiftExt | Tests/RxSwift/CountTests.swift | 2 | 5288 | //
// CountTests.swift
// RxSwiftExt
//
// Created by Fred on 06/11/2018.
// Copyright © 2018 RxSwift Community. All rights reserved.
//
import XCTest
import RxSwift
import RxSwiftExt
import RxTest
class CountTests: XCTestCase {
func testCountOne() {
let value = 0
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.from([value])
.count()
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 1),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountJust() {
let value = 1
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.just(value)
.count()
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 1),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountOf() {
let value = 2
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.of(value)
.count()
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 1),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountArrayOne() {
let values = [3, 4]
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.from(values)
.count()
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 2),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountArrayTwo() {
let values = [5, 6, 7]
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.just(values)
.count()
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 1),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountArrayEmpty() {
let values = [Int]()
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.from(values)
.count()
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 0),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountNestedArray() {
let values = [[8], [9, 10], [11, 12, 13, 14]]
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.from(values)
.count()
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 3),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountPredicateEmptyOne() {
let values = [15, 16, 17]
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.from(values)
.count { $0 > 20 }
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 0),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountPredicateEmptyTwo() {
let values = [Int]()
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.from(values)
.count { $0 < 10 }
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 0),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountPredicatePartial() {
let values = [18, 19, 20, 21]
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.from(values)
.count { $0 % 2 == 0 }
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 2),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
func testCountPredicateAll() {
let values = [22, 23, 24, 25]
let scheduler = TestScheduler(initialClock: 0)
let observer = scheduler.createObserver(Int.self)
_ = Observable.from(values)
.count { $0 > 20 }
.subscribe(observer)
scheduler.start()
let correct = Recorded.events([
.next(0, 4),
.completed(0)
])
XCTAssertEqual(observer.events, correct)
}
}
| mit | 3263f507e76c3c22db4a3aa99fc56063 | 22.602679 | 60 | 0.545489 | 4.546002 | false | true | false | false |
chenchangqing/ioscomponents | SelectionCollectionView/SelectionCollectionView/Source/OrderedDictionary/OrderedDictionary.swift | 1 | 6396 | //
// OrderedDictionary.swift
// OrderedDictionary
//
// Created by Lukas Kubanek on 29/08/15.
// Copyright © 2015 Lukas Kubanek. All rights reserved.
//
public struct OrderedDictionary<Key: Hashable, Value>: CollectionType, ArrayLiteralConvertible, CustomStringConvertible {
// MARK: - Initialization
public init() {
self.orderedKeys = []
self.keysToValues = [:]
}
public init(elements: [Element]) {
self.init()
for element in elements {
self[element.0] = element.1
}
}
public init(arrayLiteral elements: Element...) {
self.init(elements: elements)
}
// MARK: - Type Aliases
public typealias Element = (Key, Value)
public typealias Index = Int
// MARK: - Managing Content Using Keys
public subscript(key: Key) -> Value? {
get {
return keysToValues[key]
}
set(newValue) {
if let newValue = newValue {
updateValue(newValue, forKey: key)
} else {
removeValueForKey(key)
}
}
}
public func containsKey(key: Key) -> Bool {
return orderedKeys.contains(key)
}
public mutating func updateValue(value: Value, forKey key: Key) -> Value? {
if orderedKeys.contains(key) {
guard let currentValue = keysToValues[key] else {
fatalError("Inconsistency error occured in OrderedDictionary")
}
keysToValues[key] = value
return currentValue
} else {
orderedKeys.append(key)
keysToValues[key] = value
return nil
}
}
public mutating func removeValueForKey(key: Key) -> Value? {
if let index = orderedKeys.indexOf(key) {
guard let currentValue = keysToValues[key] else {
fatalError("Inconsistency error occured in OrderedDictionary")
}
orderedKeys.removeAtIndex(index)
keysToValues[key] = nil
return currentValue
} else {
return nil
}
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = true) {
orderedKeys.removeAll(keepCapacity: keepCapacity)
keysToValues.removeAll(keepCapacity: keepCapacity)
}
// MARK: - Managing Content Using Indexes
public subscript(index: Index) -> Element {
get {
guard let element = elementAtIndex(index) else {
fatalError("OrderedDictionary index out of range")
}
return element
}
set(newValue) {
updateElement(newValue, atIndex: index)
}
}
public func indexForKey(key: Key) -> Index? {
return orderedKeys.indexOf(key)
}
public func elementAtIndex(index: Index) -> Element? {
guard orderedKeys.indices.contains(index) else { return nil }
let key = orderedKeys[index]
guard let value = self.keysToValues[key] else {
fatalError("Inconsistency error occured in OrderedDictionary")
}
return (key, value)
}
public mutating func insertElement(newElement: Element, atIndex index: Index) -> Value? {
guard index >= 0 else {
fatalError("Negative OrderedDictionary index is out of range")
}
guard index <= count else {
fatalError("OrderedDictionary index out of range")
}
let (key, value) = (newElement.0, newElement.1)
let adjustedIndex: Int
let currentValue: Value?
if let currentIndex = orderedKeys.indexOf(key) {
currentValue = keysToValues[key]
adjustedIndex = (currentIndex < index - 1) ? index - 1 : index
orderedKeys.removeAtIndex(currentIndex)
keysToValues[key] = nil
} else {
currentValue = nil
adjustedIndex = index
}
orderedKeys.insert(key, atIndex: adjustedIndex)
keysToValues[key] = value
return currentValue
}
public mutating func updateElement(element: Element, atIndex index: Index) -> Element? {
guard let currentElement = elementAtIndex(index) else {
fatalError("OrderedDictionary index out of range")
}
let (newKey, newValue) = (element.0, element.1)
orderedKeys[index] = newKey
keysToValues[newKey] = newValue
return currentElement
}
public mutating func removeAtIndex(index: Index) -> Element? {
if let element = elementAtIndex(index) {
orderedKeys.removeAtIndex(index)
keysToValues.removeValueForKey(element.0)
return element
} else {
return nil
}
}
// MARK: - Description
public var description: String {
let content = map({ "\($0.0): \($0.1)" }).joinWithSeparator(", ")
return "[\(content)]"
}
// MARK: - Backing Store
private var orderedKeys: [Key]
private var keysToValues: [Key: Value]
// MARK: - SequenceType & Indexable Conformance
public func generate() -> AnyGenerator<Element> {
var nextIndex = 0
let lastIndex = self.count
return anyGenerator {
guard nextIndex < lastIndex else { return nil }
let nextKey = self.orderedKeys[nextIndex]
guard let nextValue = self.keysToValues[nextKey] else {
fatalError("Inconsistency error occured in OrderedDictionary")
}
let element = (nextKey, nextValue)
nextIndex++
return element
}
}
public var startIndex: Index { return orderedKeys.startIndex }
public var endIndex: Index { return orderedKeys.endIndex }
}
public func == <Key: Equatable, Value: Equatable>(lhs: OrderedDictionary<Key, Value>, rhs: OrderedDictionary<Key, Value>) -> Bool {
return lhs.orderedKeys == rhs.orderedKeys && lhs.keysToValues == rhs.keysToValues
}
| apache-2.0 | 41de3e502673be35619ffe2c7016a6e9 | 28.068182 | 131 | 0.557623 | 5.338063 | false | false | false | false |
vincent78/blackLand | blackland/Double.swift | 1 | 2408 | //
// Double.swift
// blackland
//
// Created by vincent on 15/11/30.
// Copyright © 2015年 fruit. All rights reserved.
//
import Foundation
public extension Double {
/**
Absolute value.
:returns: fabs(self)
*/
public func abs () -> Double {
return Foundation.fabs(self)
}
/**
Squared root.
:returns: sqrt(self)
*/
public func sqrt () -> Double {
return Foundation.sqrt(self)
}
/**
Rounds self to the largest integer <= self.
:returns: floor(self)
*/
public func floor () -> Double {
return Foundation.floor(self)
}
/**
Rounds self to the smallest integer >= self.
:returns: ceil(self)
*/
public func ceil () -> Double {
return Foundation.ceil(self)
}
/**
Rounds self to the nearest integer.
:returns: round(self)
*/
public func round () -> Double {
return Foundation.round(self)
}
/**
Clamps self to a specified range.
:param: min Lower bound
:param: max Upper bound
:returns: Clamped value
*/
public func clamp (min: Double, _ max: Double) -> Double {
return Swift.max(min, Swift.min(max, self))
}
/**
Just like round(), except it supports rounding to an arbitrary number, not just 1
Be careful about rounding errors
:params: increment the increment to round to
*/
public func roundToNearest(increment: Double) -> Double {
let remainder = self % increment
return remainder < increment / 2 ? self - remainder : self - remainder + increment
}
/**
Random double between min and max (inclusive).
:params: min
:params: max
:returns: Random number
*/
public static func random(min: Double = 0, max: Double) -> Double {
let diff = max - min;
let rand = Double(arc4random() % (UInt32(RAND_MAX) + 1))
return ((rand / Double(RAND_MAX)) * diff) + min;
}
}
// MARK: - 类型转换
public extension Double
{
/**
毫秒数转成日期
- returns: <#return value description#>
*/
public func toDate() -> NSDate {
return NSDate(timeIntervalSince1970: (self/1000));
}
public func toString() -> String {
return String(self)
}
}
| apache-2.0 | f091040be027e25a0b801380a5c4608d | 20.663636 | 90 | 0.552665 | 4.270609 | false | false | false | false |
Mikelulu/BaiSiBuDeQiJie | LKBS/Pods/BMPlayer/Source/Default/BMPlayerManager.swift | 1 | 1228 | //
// BMPlayerManager.swift
// Pods
//
// Created by BrikerMan on 16/5/21.
//
//
import UIKit
import AVFoundation
import NVActivityIndicatorView
public let BMPlayerConf = BMPlayerManager.shared
public enum BMPlayerTopBarShowCase: Int {
case always = 0 /// 始终显示
case horizantalOnly = 1 /// 只在横屏界面显示
case none = 2 /// 不显示
}
open class BMPlayerManager {
/// 单例
open static let shared = BMPlayerManager()
/// tint color
open var tintColor = UIColor.white
/// Loader
open var loaderType = NVActivityIndicatorType.ballRotateChase
/// should auto play
open var shouldAutoPlay = true
open var topBarShowInCase = BMPlayerTopBarShowCase.always
open var animateDelayTimeInterval = TimeInterval(5)
/// should show log
open var allowLog = false
internal static func asset(for resouce: BMPlayerResourceDefinition) -> AVURLAsset {
return AVURLAsset(url: resouce.url, options: resouce.options)
}
/**
打印log
- parameter info: log信息
*/
func log(_ info:String) {
if allowLog {
print(info)
}
}
}
| mit | 921020c59b9b7481a063fdb9c5343c63 | 20.178571 | 87 | 0.624789 | 4.297101 | false | false | false | false |
BridgeTheGap/KRAnimationKit | KRAnimationKit/UIViewExtension/UIView+OriginAnim.swift | 1 | 4352 | //
// UIView+OriginAnim.swift
// KRAnimationKit
//
// Created by Joshua Park on 15/10/2019.
//
import UIKit
import KRTimingFunction
// MARK: - Origin
public extension UIView {
// MARK: - Animate
@discardableResult
func animate(
x: CGFloat,
duration: Double,
function: FunctionType = .linear,
reverses: Bool = false,
repeatCount: Float = 0.0,
completion: (() -> Void)? = nil)
-> String
{
let animDesc = AnimationDescriptor(
view: self,
delay: 0.0,
property: .originX,
endValue: x,
duration: duration,
function: function)
return KRAnimation.animate(
animDesc,
reverses: reverses,
repeatCount: repeatCount,
completion: completion)
}
@discardableResult
func animate(
y: CGFloat,
duration: Double,
function: FunctionType = .linear,
reverses: Bool = false,
repeatCount: Float = 0.0,
completion: (() -> Void)? = nil)
-> String
{
let animDesc = AnimationDescriptor(
view: self,
delay: 0.0,
property: .originY,
endValue: y,
duration: duration,
function: function)
return KRAnimation.animate(
animDesc,
reverses: reverses,
repeatCount: repeatCount,
completion: completion)
}
@discardableResult
func animateOrigin(
_ x: CGFloat,
_ y: CGFloat,
duration: Double,
function: FunctionType = .linear,
reverses: Bool = false,
repeatCount: Float = 0.0,
completion: (() -> Void)? = nil)
-> String
{
return animate(
origin: CGPoint(x: x, y: y),
duration: duration,
function: function,
reverses: reverses,
repeatCount: repeatCount,
completion: completion)
}
@discardableResult
func animate(
origin: CGPoint,
duration: Double,
function: FunctionType = .linear,
reverses: Bool = false,
repeatCount: Float = 0.0,
completion: (() -> Void)? = nil)
-> String
{
let endValue = NSValue(cgPoint: origin)
let animDesc = AnimationDescriptor(
view: self,
delay: 0.0,
property: .origin,
endValue: endValue,
duration: duration,
function: function)
return KRAnimation.animate(
animDesc,
reverses: reverses,
repeatCount: repeatCount,
completion: completion)
}
// MARK: - Chain
func chain(
x: CGFloat,
duration: Double,
function: FunctionType = .linear)
-> [AnimationDescriptor]
{
return [
AnimationDescriptor(
view: self,
delay: 0.0,
property: .originX,
endValue: x,
duration: duration,
function: function),
]
}
func chain(
y: CGFloat,
duration: Double,
function: FunctionType = .linear)
-> [AnimationDescriptor]
{
return [
AnimationDescriptor(
view: self,
delay: 0.0,
property: .originY,
endValue: y,
duration: duration,
function: function),
]
}
func chain(
x: CGFloat,
y: CGFloat,
duration: Double,
function: FunctionType = .linear)
-> [AnimationDescriptor]
{
return chain(origin: CGPoint(x: x, y: y), duration: duration, function: function)
}
func chain(
origin: CGPoint,
duration: Double,
function: FunctionType = .linear)
-> [AnimationDescriptor]
{
let endValue = NSValue(cgPoint: origin)
return [
AnimationDescriptor(
view: self,
delay: 0.0,
property: .origin,
endValue: endValue,
duration: duration,
function: function),
]
}
}
| mit | 12aab5a78a340ba9814e642ef6ae002b | 23.587571 | 89 | 0.490579 | 5.090058 | 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.