repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
RDCEP/ggcmi | bin/metrics.isi1/metrics.isi1.swift | 1 | 610 | type file;
app (file o) metricsisi1 (string model, string gcm, string crop, string co2) {
metricsisi1 model gcm crop co2 stdout = @o;
}
string models[] = strsplit(arg("models"), ",");
string gcms[] = strsplit(arg("gcms"), ",");
string crops[] = strsplit(arg("crops"), ",");
string co2s[] = strsplit(arg("co2s"), ",");
foreach m in models {
foreach g in gcms {
foreach c in crops {
foreach co in co2s {
file logfile <single_file_mapper; file=strcat("logs/", m, ".", g, ".", c, ".", co, ".txt")>;
logfile = metricsisi1(m, g, c, co);
}
}
}
}
| agpl-3.0 |
sfurlani/addsumfun | Add Sum Fun/Add Sum Fun/Game.swift | 1 | 1846 | //
// Game.swift
// Add Sum Fun
//
// Created by SFurlani on 8/26/15.
// Copyright © 2015 Dig-It! Games. All rights reserved.
//
import Foundation
import CoreGraphics
protocol GameType {
var equations: [EquationType] { get }
var answers: [AnswerType] { get }
var currentEquation: EquationType? { get }
func score() -> CGFloat?
mutating func addNewRound() -> ()
mutating func addNewAnswer(answer: UInt) -> AnswerType?
}
extension GameType {
var currentEquation: EquationType? {
guard equations.count > answers.count else {
return nil
}
return equations[answers.count]
}
func score() -> CGFloat? {
guard equations.count == answers.count else {
return nil
}
let correct = answers.reduce(0) { (count: UInt, answer: AnswerType) -> UInt in
return count + (answer.isCorrect() ? 1 : 0)
}
return CGFloat(correct) / CGFloat(equations.count)
}
}
class GameData : GameType {
private(set) var equations: [EquationType]
private(set) var answers: [AnswerType]
let roundSize: UInt
init(roundSize: UInt = 5) {
self.roundSize = roundSize
equations = self.roundSize.repeatMap { (index: UInt) in
return Addition()
}
answers = [AnswerType]()
}
func addNewRound() {
equations = equations + roundSize.repeatMap { (index: UInt) in
return Addition()
}
}
func addNewAnswer(answer: UInt) -> AnswerType? {
if let equation = currentEquation {
let answer = Answer(entered:answer, equation: equation)
answers.append(answer)
return answer
}
else {
return nil
}
}
}
| mit |
Eonil/ClangWrapper.Swift | ClangWrapper/RefQualifierKind.swift | 1 | 1053 | //
// RefQualifierKind.swift
// ClangWrapper
//
// Created by Hoon H. on 2015/01/22.
// Copyright (c) 2015 Eonil. All rights reserved.
//
public enum RefQualifierKind: UInt32 {
/// No ref-qualifier was provided.
case None = 0
/// An lvalue ref-qualifier was provided (&).
case LValue
/// An rvalue ref-qualifier was provided (&&).
case RValue
}
extension RefQualifierKind {
static func fromRaw(raw r:CXRefQualifierKind) -> RefQualifierKind {
return self.init(raw: r)
}
/// Doesn't work well in Swift 1.2.
/// Use `fromRaw` instead of.
init(raw: CXRefQualifierKind) {
switch raw.rawValue {
case CXRefQualifier_None.rawValue: self = None
case CXRefQualifier_LValue.rawValue: self = LValue
case CXRefQualifier_RValue.rawValue: self = RValue
default:
fatalError("Unknown `CXRefQualifierKind` value: \(raw)")
}
}
var raw:CXRefQualifierKind {
get {
switch self {
case .None: return CXRefQualifier_None
case .LValue: return CXRefQualifier_LValue
case .RValue: return CXRefQualifier_RValue
}
}
}
} | mit |
craaron/ioscreator | IOS8SwiftSnapBehaviourTutorial/IOS8SwiftSnapBehaviourTutorialTests/IOS8SwiftSnapBehaviourTutorialTests.swift | 40 | 976 | //
// IOS8SwiftSnapBehaviourTutorialTests.swift
// IOS8SwiftSnapBehaviourTutorialTests
//
// Created by Arthur Knopper on 10/11/14.
// Copyright (c) 2014 Arthur Knopper. All rights reserved.
//
import UIKit
import XCTest
class IOS8SwiftSnapBehaviourTutorialTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
kleiram/Faker | Source/Classes/Internet.swift | 1 | 9276 | // Internet.swift
//
// Copyright (c) 2014–2015 Apostle (http://apostle.nl)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public class Internet {
// MARK: Provider
public class Provider {
public init() {
// noop
}
func urlFormats() -> [String] {
return [
"http://\(Internet.domainName())",
"http://www.\(Internet.domainName())",
"http://www.\(Internet.domainName())/\(Internet.slug())",
"http://www.\(Internet.domainName())/\(Internet.slug())",
"https://www.\(Internet.domainName())/\(Internet.slug())",
"http://www.\(Internet.domainName())/\(Internet.slug()).html",
"http://\(Internet.domainName())/\(Internet.slug())",
"http://\(Internet.domainName())/\(Internet.slug())",
"http://\(Internet.domainName())/\(Internet.slug()).html",
"https://\(Internet.domainName())/\(Internet.slug()).html",
]
}
func emailFormats() -> [String] {
return [
"\(Internet.username())@\(Internet.domainName())",
"\(Internet.username())@\(Internet.freeEmailDomain())",
"\(Internet.username())@\(Internet.safeEmailDomain())",
]
}
func usernameFormats() -> [String] {
return [
"\(Person.lastName()).\(Person.firstName())",
"\(Person.firstName()).\(Person.lastName())",
"\(Person.firstName())##",
"?\(Person.lastName())",
]
}
func tlds() -> [String] {
return [ "com", "com", "com", "com", "com", "com", "biz", "info", "net", "org" ]
}
func freeEmailDomains() -> [String] {
return [
"gmail.com",
"yahoo.com",
"hotmail.com",
]
}
}
// MARK: Variables
public static var provider : Provider?
// MARK: Generators
/**
Generate a random e-mail address.
- note: There is a chance that this e-mail address is actually in use,
if you want to send e-mail, use the `safeEmail` method instead.
- returns: Returns a random e-mail address.
*/
public class func email() -> String {
return dataProvider().emailFormats().random()!
}
/**
Generate a random safe e-mail address.
- returns: Returns a random safe e-mail address.
*/
public class func safeEmail() -> String {
return "\(username())@\(safeEmailDomain())"
}
/**
Generate a random free e-mail address.
- note: There is a chance that this e-mail address is actually in use,
if you want to send e-mail, use the `safeEmail` method instead.
- returns: Returns a random free e-mail address.
*/
public class func freeEmail() -> String {
return "\(username())@\(freeEmailDomain())"
}
/**
Generate a random company e-mail address.
- note: There is a chance that this e-mail address is actually in use,
if you want to send e-mail, use the `safeEmail` method instead.
- returns: Returns a random company e-mail address.
*/
public class func companyEmail() -> String {
return "\(username())@\(domainName())"
}
/**
Generate a random free e-mail domain.
- returns: Returns a random free e-mail domain.
*/
public class func freeEmailDomain() -> String {
return dataProvider().freeEmailDomains().random()!
}
/**
Generate a random safe e-mail domain.
- returns: Returns a random safe e-mail domain.
*/
public class func safeEmailDomain() -> String {
return [ "example.com", "example.org", "example.net" ].random()!
}
/**
Generate a random username.
- returns: Returns a random username.
*/
public class func username() -> String {
let result = dataProvider().usernameFormats().random()!
return result.numerify().lexify().lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: ".")
}
/**
Generate a random password of at least `minLength` and at most
`maxLength` characters.
- parameter minLength: The minimum length of the password.
- parameter maxLength: The maximum length of the password.
- returns: Returns a password of at least `minLength` and at most
`maxLength` characters.
*/
public class func password(minLength : Int = 6, maxLength : Int = 20) -> String {
let format = Array(count: Int.random(minLength, max: maxLength), repeatedValue: "*").joinWithSeparator("")
return format.lexify()
}
/**
Generate a random domain name.
- returns: Returns a random domain name.
*/
public class func domainName() -> String {
return "\(domainWord()).\(tld())"
}
/**
Generate a random domain word.
- returns: Returns a random domain word.
*/
public class func domainWord() -> String {
return "\(Person.lastName())".lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: "-")
}
/**
Generate a random top-level domain (TLD).
- returns: Returns a random TLD.
*/
public class func tld() -> String {
return dataProvider().tlds().random()!
}
/**
Generate a random URL.
- returns: Returns a random URL.
*/
public class func url() -> String {
return dataProvider().urlFormats().random()!
}
/**
Generate a random slug.
- parameter nbWords: The number of words the slug should contain.
- parameter variable: If `true`, the number of sentences will vary
between +/- 40% of `nbSentences`.
- returns: Returns a random slug of `nbWords` words.
*/
public class func slug(nbWords : Int = 6, variable : Bool = true) -> String {
if nbWords <= 0 {
return ""
}
return Lorem.words(variable ? nbWords.randomize(40) : nbWords).joinWithSeparator("-").lowercaseString
}
/**
Generate a random IPv4 address.
- returns: Returns a random IPv4 address.
*/
public class func ipv4() -> String {
return [
Int.random(0, max: 255),
Int.random(0, max: 255),
Int.random(0, max: 255),
Int.random(0, max: 255)
].map(String.init).joinWithSeparator(".")
}
/**
Generate a random IPv6 address.
- returns: Returns a random IPv6 address.
*/
public class func ipv6() -> String {
let components = (0..<8).map { _ in Int.random(0, max: 65535) }
return components.map({ String(format: "%04x", arguments: [ $0 ]) }).joinWithSeparator(":")
}
/**
Generate a random local IPv4 address.
- returns: Returns a random local IPv4 address.
*/
public class func localIpv4() -> String {
var prefix : String = ""
var components : [String] = [String]()
if Int.random(0, max: 1) == 0 {
prefix = "10."
components = (0..<3).map({ _ in Int.random(0, max: 255) }).map(String.init)
} else {
prefix = "192.168."
components = (0..<2).map({ _ in Int.random(0, max: 255) }).map(String.init)
}
return prefix + components.joinWithSeparator(".")
}
/**
Generate a random MAC address.
- returns: Returns a random MAC address.
*/
public class func mac() -> String {
let components = (0..<6).map { _ in Int.random(0, max: 255) }
return components.map({ String(format: "%02X", arguments: [ $0 ]) }).joinWithSeparator(":")
}
private class func dataProvider() -> Provider {
return provider ?? Provider()
}
}
| mit |
clappr/clappr-ios | Tests/Clappr_Tests/Classes/Plugin/Playback/AVFoundationPlaybackStopActionTests.swift | 1 | 2157 | import Quick
import Nimble
@testable import Clappr
class AVFoundationPlaybackStopActionTests: QuickSpec {
override func spec() {
describe(".AVFoundationPlaybackStopActionTests") {
describe("when stop is called") {
it("updates state to idle") {
let avfoundationPlayback = AVFoundationPlayback(options: [:])
avfoundationPlayback.player = PlayerMock()
avfoundationPlayback.state = .playing
avfoundationPlayback.stop()
expect(avfoundationPlayback.state).to(equal(.idle))
}
context("#events") {
it("triggers willStop event") {
var didCallWillStop = false
let baseObject = BaseObject()
let avfoundationPlayback = AVFoundationPlayback(options: [:])
avfoundationPlayback.player = PlayerMock()
avfoundationPlayback.state = .playing
baseObject.listenTo(avfoundationPlayback, event: .willStop) { _ in
didCallWillStop = true
}
avfoundationPlayback.stop()
expect(didCallWillStop).to(beTrue())
}
it("triggers didStop event") {
var didCallDidStop = false
let baseObject = BaseObject()
let avfoundationPlayback = AVFoundationPlayback(options: [:])
avfoundationPlayback.player = PlayerMock()
avfoundationPlayback.state = .playing
baseObject.listenTo(avfoundationPlayback, event: .didStop) { _ in
didCallDidStop = true
}
avfoundationPlayback.stop()
expect(didCallDidStop).to(beTrue())
}
}
}
}
}
}
| bsd-3-clause |
rhodgkins/RDHCollectionViewTableLayout | Examples/Tests/RDHTableLayoutTests.swift | 1 | 719 | //
// RDHCollectionViewTableLayoutDemoTests.swift
// RDHCollectionViewTableLayoutDemoTests
//
// Created by Richard Hodgkins on 06/06/2015.
// Copyright (c) 2015 Rich H. All rights reserved.
//
import UIKit
import XCTest
@testable import RDHCollectionViewTableLayout
class RDHCollectionViewTableLayoutDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
}
}
| mit |
lennet/languini | app/LanguageQuiz/LanguageQuiz/ShadowView.swift | 1 | 1201 | //
// ShadowView.swift
// Languini
//
// Created by Leo Thomas on 03/07/15.
// Copyright (c) 2015 Coding Da Vinci. All rights reserved.
//
import UIKit
//@IBDesignable // not supported for iOS 7
class ShadowView: UIView {
var color: UIColor = UIColor(red: 0.295, green: 0.695, blue: 0.900, alpha: 0.970)
var radius: CGFloat = 1
var opacity: CGFloat = 0.8
var shadowOffset: CGSize = CGSize(width: 2, height: 2)
var shadowBrightness: CGFloat = 0.5
func setShadow() {
self.backgroundColor = color
self.layer.shadowColor = shadowColor()
self.layer.shadowOpacity = Float(opacity);
self.layer.shadowRadius = radius
self.layer.shadowOffset = shadowOffset
}
func shadowColor() -> CGColorRef {
var hue: CGFloat = 0
var saturation: CGFloat = 0
var brightness: CGFloat = 0
var alpha: CGFloat = 0
color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return UIColor(hue: hue, saturation: saturation, brightness: (brightness * shadowBrightness), alpha: alpha).CGColor
}
override func awakeFromNib() {
setShadow()
}
}
| bsd-2-clause |
kingcos/CS193P_2017 | Calculator/Calculator/ViewController.swift | 1 | 4091 | //
// ViewController.swift
// Calculator
//
// Created by 买明 on 15/02/2017.
// Copyright © 2017 买明. All rights reserved.
// [Powered by kingcos](https://github.com/kingcos/CS193P_2017)
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
private var brain = CalculatorBrain()
// 存储属性
var userIsInTheMiddleOfTyping = false
// 计算属性
var displayValue: Double {
get {
return Double(display.text!)!
}
set {
display.text = String(newValue)
}
}
@IBAction func touchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTyping {
let textCurrentlyInDisplay = display.text!
display.text = textCurrentlyInDisplay + digit
} else {
display.text = digit
userIsInTheMiddleOfTyping = true
}
}
@IBAction func performOperation(_ sender: UIButton) {
if userIsInTheMiddleOfTyping {
brain.setOperand(displayValue)
userIsInTheMiddleOfTyping = false
}
if let mathematicalSymbol = sender.currentTitle {
brain.performOperation(mathematicalSymbol)
}
if let result = brain.result {
displayValue = result
}
}
// Lecture 12
private func showSizeClasses() {
if !userIsInTheMiddleOfTyping {
display.textAlignment = .center
display.text = "width " + traitCollection.horizontalSizeClass.description
+ " height " + traitCollection.verticalSizeClass.description
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showSizeClasses()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (coordinator) in
self.showSizeClasses()
}, completion: nil)
}
override func viewDidLoad() {
// brain.addUnaryOperation(named: "✅") { (value) -> Double in
// return sqrt(value)
// }
// brain.addUnaryOperation(named: "✅") {
// return sqrt($0)
// }
// brain.addUnaryOperation(named: "✅") {
// self.display.textColor = UIColor.green
// return sqrt($0)
// }
// weak
// brain.addUnaryOperation(named: "✅") { [weak self] in
// // self 为 Optional
// self?.display.textColor = UIColor.green
// return sqrt($0)
// }
//
// brain.addUnaryOperation(named: "✅") { [weak weakSelf = self] in
// weakSelf?.display.textColor = UIColor.green
// return sqrt($0)
// }
// unowned
// brain.addUnaryOperation(named: "✅") { [me = self] in
// me.display.textColor = UIColor.green
// return sqrt($0)
// }
//
// brain.addUnaryOperation(named: "✅") { [unowned me = self] in
// me.display.textColor = UIColor.green
// return sqrt($0)
// }
//
// brain.addUnaryOperation(named: "✅") { [unowned self = self] in
// self.display.textColor = UIColor.green
// return sqrt($0)
// }
brain.addUnaryOperation(named: "✅") { [unowned self] in
self.display.textColor = UIColor.green
return sqrt($0)
}
}
}
// Lecture 12
extension UIUserInterfaceSizeClass: CustomStringConvertible {
public var description: String {
switch self {
case .compact:
return "Compact"
case .regular:
return "Regular"
case .unspecified:
return "??"
}
}
}
| mit |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document5.playgroundchapter/Pages/Challenge2.playgroundpage/Sources/Assessments.swift | 1 | 2785 | //
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let solution: String? = nil
import PlaygroundSupport
public func assessmentPoint() -> AssessmentResults {
let checker = ContentsChecker(contents: PlaygroundPage.current.text)
pageIdentifier = "Boxed_In"
var hints = [
"Any tile in the square could have a gem, an open switch, or a closed switch. First, write a function called `checkTile()` to check for each possibility on a single tile.",
"You'll need to use your function to check every tile. Is there an easy way to do that?",
"Try using a loop that repeats a set of commands to complete one corner of the puzzle each time.",
"This puzzle is a **Challenge** and has no provided solution. Strengthen your coding skills by creating your own approach to solve it."
]
let customFunction = checker.customFunctions.first ?? ""
let success: String
if checker.didUseForLoop == false && checker.numberOfStatements > 12 {
success = "### Oops! \nYou completed the puzzle, but you forgot to include a [for loop](glossary://for%20loop). You ran \(checker.numberOfStatements) lines of code, but with a for loop, you’d need only 12. \n\nYou can try again or move on. \n\n[**Next Page**](@next)"
}
else if checker.didUseForLoop == true && checker.didUseConditionalStatement == false {
success = "Congrats! \nYou managed to solve the puzzle by using a [for loop](glossary://for%20loop), but you didn’t include [conditional code](glossary://conditional%20code). Using `if` statements makes your code more intelligent and allows it to respond to changes in your environment. \n\nYou can try again or move on. \n\n[**Next Page**](@next)"
}
else if checker.didUseForLoop == true && checker.didUseConditionalStatement == true && checker.functionCallCount(forName: customFunction) == 0 {
success = "### Great work! \nYour solution used both for loops and [conditional code](glossary://conditional%20code), incredible tools that make your code more intelligent and let you avoid repeating the same set of commands many times. However, you can improve your solution by writing your own custom function to check an individual tile for a gem or a closed switch. As an added challenge, try solving the puzzle by writing a custom function. Feel free to move on whenever you are ready. \n\n[**Next Page**](@next)"
} else {
success = "### Fantastic! \nYour solution is incredible. You've come a long way, learning conditional code and combining your new skills with functions and `for` loops! \n\n[**Next Page**](@next)"
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
| mit |
SAP/IssieBoard | EducKeyboard/ConfigItem.swift | 1 | 3833 | //
// ConfigItem.swift
// MasterDetailsHelloWorld
//
// Created by Sasson, Kobi on 3/14/15.
// Copyright (c) 2015 Sasson, Kobi. All rights reserved.
//
import Foundation
import UIKit
enum ControlsType {
case TextInput
case ColorPicker
}
enum ConfigItemType{
case String
case Color
case Picker
case FontPicker
case Templates
}
class ConfigItem {
var UserSettings: NSUserDefaults
let key: String
let title: String
let type: ConfigItemType
let defaultValue: AnyObject?
var value: AnyObject? {
get{
switch self.type{
case .String:
if let val = UserSettings.stringForKey(self.key) {
return val
} else{
return self.defaultValue
}
case .Color:
if let val = UserSettings.stringForKey(self.key) {
return UIColor(string: val)
} else{
return defaultValue
}
case .Templates:
if let val = UserSettings.stringForKey(self.key) {
return val
} else {
return self.defaultValue
}
default:
if let val = UserSettings.stringForKey(self.key) {
return val
} else{
return self.defaultValue
}
}
}
set {
switch self.type{
case .String:
UserSettings.setObject(newValue, forKey: self.key)
UserSettings.synchronize()
case .Color:
if let color = (newValue as! UIColor).stringValue {
if(self.key == "ISSIE_KEYBOARD_KEYS_COLOR"){
UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET1_KEYS_COLOR")
UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET2_KEYS_COLOR")
UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET3_KEYS_COLOR")
UserSettings.synchronize()
}
else if(self.key == "ISSIE_KEYBOARD_TEXT_COLOR"){
UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET1_TEXT_COLOR")
UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET2_TEXT_COLOR")
UserSettings.setObject(color, forKey: "ISSIE_KEYBOARD_CHARSET3_TEXT_COLOR")
UserSettings.synchronize()
}
else
{
UserSettings.setObject(color, forKey: self.key)
UserSettings.synchronize()
}
}
default:
UserSettings.setObject(newValue, forKey: self.key)
UserSettings.synchronize()
}
}
}
init(key:String ,title: String, defaultValue: AnyObject?, type: ConfigItemType ){
UserSettings = NSUserDefaults(suiteName: "group.com.sap.i012387.HashtagPOC")!
self.key = key
self.title = title
self.type = type
self.defaultValue = defaultValue
switch self.type{
case .String:
UserSettings.setObject(defaultValue, forKey: self.key)
UserSettings.synchronize()
case .Color:
if let color = (defaultValue as! UIColor).stringValue {
UserSettings.setObject(color, forKey: self.key)
UserSettings.synchronize()
}
default:
UserSettings.setObject(defaultValue, forKey: self.key)
UserSettings.synchronize()
}
}
} | apache-2.0 |
plantain-00/demo-set | swift-demo/NewsCatcher/Ridge/Ridge/PlainTextParser.swift | 1 | 878 | //
// PlainTextParser.swift
// Ridge
//
// Created by 姚耀 on 15/1/30.
// Copyright (c) 2015年 姚耀. All rights reserved.
//
import Foundation
class PlainTextParser: ParserBase {
init(strings: [String], index: Int, endIndex: Int, depth: Int) {
self.depth = depth
super.init(strings: strings, index: index, endIndex: endIndex)
}
private let depth: Int
var plainText: PlainText?
override func parse() {
var result = StringStatic.empty
do {
result += strings[index]
index++
} while index < endIndex
&& strings[index] != StringStatic.lessThan
let t = result.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if t != StringStatic.empty {
plainText = PlainText(text: result, depth: depth)
}
}
} | mit |
yanagiba/swift-ast | Tests/ParserTests/Expression/ParserTryOperatorExpressionTests.swift | 2 | 2818 | /*
Copyright 2016 Ryuichi Intellectual Property and the Yanagiba project contributors
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 XCTest
@testable import AST
class ParserTryOperatorExpressionTests: XCTestCase {
func testTry() {
parseExpressionAndTest("try foo", "try foo", testClosure: { expr in
guard let tryOpExpr = expr as? TryOperatorExpression,
case .try(let tryExpr) = tryOpExpr.kind else {
XCTFail("Failed in getting a try operator expression")
return
}
XCTAssertTrue(tryExpr is IdentifierExpression)
})
}
func testForcedTry() {
parseExpressionAndTest("try! foo", "try! foo")
}
func testOptionalTry() {
parseExpressionAndTest("try? foo", "try? foo")
}
func testTryBinaryExpressions() {
parseExpressionAndTest("try foo = bar == true", "try foo = bar == true", testClosure: { expr in
guard let tryOpExpr = expr as? TryOperatorExpression,
case .try(let tryExpr) = tryOpExpr.kind else {
XCTFail("Failed in getting a try operator expression")
return
}
XCTAssertTrue(tryExpr is SequenceExpression)
})
}
func testTryScopes() {
parseExpressionAndTest(
"try someThrowingFunction() + anotherThrowingFunction()",
"try someThrowingFunction() + anotherThrowingFunction()")
parseExpressionAndTest(
"try (someThrowingFunction() + anotherThrowingFunction())",
"try (someThrowingFunction() + anotherThrowingFunction())")
parseExpressionAndTest(
"(try someThrowingFunction()) + anotherThrowingFunction()",
"(try someThrowingFunction()) + anotherThrowingFunction()")
}
func testSourceRange() {
let testExprs: [(testString: String, expectedEndColumn: Int)] = [
("try foo", 8),
("try? foo", 9),
("try! foo", 9),
]
for t in testExprs {
parseExpressionAndTest(t.testString, t.testString, testClosure: { expr in
XCTAssertEqual(expr.sourceRange, getRange(1, 1, 1, t.expectedEndColumn))
})
}
}
static var allTests = [
("testTry", testTry),
("testForcedTry", testForcedTry),
("testOptionalTry", testOptionalTry),
("testTryBinaryExpressions", testTryBinaryExpressions),
("testTryScopes", testTryScopes),
("testSourceRange", testSourceRange),
]
}
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/00984-swift-constraints-constraintsystem-simplifyconstraint.swift | 1 | 443 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let c : String = nil
struct A {
func a<h : a
| apache-2.0 |
ben-ng/swift | validation-test/compiler_crashers_fixed/25935-swift-metatypetype-get.swift | 1 | 432 | // 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class A{class g{let:A.b}class b<T
| apache-2.0 |
adrfer/swift | validation-test/Evolution/test_global_stored_to_computed.swift | 1 | 1924 | // RUN: rm -rf %t && mkdir -p %t/before && mkdir -p %t/after
// RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -D BEFORE -c %S/Inputs/global_stored_to_computed.swift -o %t/before/global_stored_to_computed.o
// RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -D BEFORE -c %S/Inputs/global_stored_to_computed.swift -o %t/before/global_stored_to_computed.o
// RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -D AFTER -c %S/Inputs/global_stored_to_computed.swift -o %t/after/global_stored_to_computed.o
// RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -D AFTER -c %S/Inputs/global_stored_to_computed.swift -o %t/after/global_stored_to_computed.o
// RUN: %target-build-swift -D BEFORE -c %s -I %t/before -o %t/before/main.o
// RUN: %target-build-swift -D AFTER -c %s -I %t/after -o %t/after/main.o
// RUN: %target-build-swift %t/before/global_stored_to_computed.o %t/before/main.o -o %t/before_before
// RUN: %target-build-swift %t/before/global_stored_to_computed.o %t/after/main.o -o %t/before_after
// RUN: %target-build-swift %t/after/global_stored_to_computed.o %t/before/main.o -o %t/after_before
// RUN: %target-build-swift %t/after/global_stored_to_computed.o %t/after/main.o -o %t/after_after
// RUN: %target-run %t/before_before
// RUN: %target-run %t/before_after
// RUN: %target-run %t/after_before
// RUN: %target-run %t/after_after
import StdlibUnittest
import global_stored_to_computed
var GlobalStoredToComputed = TestSuite("GlobalStoredToComputed")
GlobalStoredToComputed.test("ChangeStoredToComputed") {
do {
@inline(never) func increment(inout x: Int) {
x += 1
}
expectEqual(globalStoredToComputed, 0)
increment(&globalStoredToComputed)
expectEqual(globalStoredToComputed, 1)
globalStoredToComputed = 0xbadf00d
expectEqual(globalStoredToComputed, 0xbadf00d)
}
}
runAllTests()
| apache-2.0 |
adrfer/swift | test/SourceKit/Indexing/index_with_clang_module.swift | 12 | 884 | // RUN: %sourcekitd-test -req=index %s -- %s -F %S/../Inputs/libIDE-mock-sdk \
// RUN: %mcp_opt %clang-importer-sdk | FileCheck %s
import Foo
func foo(a: FooClassDerived) {
a.fooInstanceFunc0()
fooFunc1(0)
}
// CHECK: key.kind: source.lang.swift.import.module.clang
// CHECK-NEXT: key.name: "Foo"
// CHECK-NEXT: key.filepath: "{{.*[/\\]}}Foo{{.*}}.pcm"
// CHECK-NEXT-NOT: key.hash:
// CHECK: key.kind: source.lang.swift.ref.class
// CHECK-NEXT: key.name: "FooClassDerived"
// CHECK-NEXT: key.usr: "c:objc(cs)FooClassDerived"
// CHECK: key.kind: source.lang.swift.ref.function.method.instance
// CHECK-NEXT: key.name: "fooInstanceFunc0()"
// CHECK-NEXT: key.usr: "c:objc(cs)FooClassDerived(im)fooInstanceFunc0"
// CHECK: key.kind: source.lang.swift.ref.function.free
// CHECK-NEXT: key.name: "fooFunc1(_:)"
// CHECK-NEXT: key.usr: "c:@F@fooFunc1"
| apache-2.0 |
adrfer/swift | test/ClangModules/no-import-objc.swift | 20 | 244 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -I %S/Inputs/no-import-objc %s -verify
// REQUIRES: objc_interop
// Note that we don't import ObjectiveC.
import People
class MyFrank : Frank {
override func frank() {}
} | apache-2.0 |
cxpyear/ZSZQApp | spdbapp/spdbapp/Classes/Controller/RegisViewController.swift | 1 | 8995 | //
// RegisViewController.swift
// spdbapp
//
// Created by GBTouchG3 on 15/6/26.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
import Alamofire
import SnapKit
class RegisViewController: UIViewController, UIAlertViewDelegate, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet weak var viewparent: UIView!
@IBOutlet weak var mainSignInUserTv: UITableView!
@IBOutlet weak var searchbar: UISearchBar!
@IBOutlet weak var cover: UIButton!
@IBOutlet weak var txtPassword: UITextField!
@IBOutlet weak var loginView: UIView!
@IBOutlet weak var lblShowError: UILabel!
var cellIdentify = "maincell"
var password = Int()
var userName = String()
@IBOutlet weak var btnEnterPassword: UIButton!
@IBOutlet weak var btnCancelEnterPassword: UIButton!
// var enterPassword = EnterPasswordView()
var kbHeight: CGFloat!
var allMembers = NSMutableArray()
var currentChangeAlert = UIAlertView()
var searchText: String = "" {
didSet{
self.allMembers.removeAllObjects()
// println("text = \(self.searchText)")
for var i = 0 ; i < totalMembers.count ;i++ {
var member = GBMember(keyValues: totalMembers[i])
var name = member.name.lowercaseString
searchText = searchText.lowercaseString
if name.contains(searchText){
self.allMembers.addObject(member)
}
}
self.mainSignInUserTv.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
totalMembers = current.member
self.btnEnterPassword.layer.cornerRadius = 8
self.btnCancelEnterPassword.layer.cornerRadius = 8
initSubViewFrame()
self.btnEnterPassword.addTarget(self, action: "checkPassword", forControlEvents: UIControlEvents.TouchUpInside)
self.btnCancelEnterPassword.addTarget(self, action: "cancelEnterPassword", forControlEvents: UIControlEvents.TouchUpInside)
}
func initSubViewFrame(){
// topBarView = TopbarView.getTopBarView(self)
// self.view.addSubview(topBarView)
mainSignInUserTv.rowHeight = 65
mainSignInUserTv.tableFooterView = UIView(frame: CGRectZero)
mainSignInUserTv.registerNib(UINib(nibName: "SignInTableviewCell", bundle: nil), forCellReuseIdentifier: cellIdentify)
self.cover.hidden = true
self.cover.addTarget(self, action: "coverClick", forControlEvents: UIControlEvents.TouchUpInside)
self.loginView.hidden = true
self.loginView.layer.cornerRadius = 10
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name:UIKeyboardWillHideNotification, object: nil)
}
override func shouldAutorotate() -> Bool {
self.view.endEditing(true)
return true
}
func cancelEnterPassword(){
self.loginView.hidden = true
self.txtPassword.text = ""
self.view.endEditing(true)
}
func checkPassword(){
println("password = \(self.password)")
if self.txtPassword.text.isEmpty {
return
}
var dict = NSDictionary(contentsOfFile: memberInfoPath)
if let pwdValue = (dict?.valueForKey("password"))?.integerValue{
if let txtPwdValue = self.txtPassword.text.toInt(){
if pwdValue == txtPwdValue{
bNeedLogin = false
var agendaVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SignInAgenda") as! AgendaViewController
self.presentViewController(agendaVC, animated: true, completion: nil)
self.lblShowError.text = ""
}else{
bNeedLogin = true
self.txtPassword.text = ""
self.lblShowError.text = "密码错误,请重试..."
}
}
}else{
bNeedLogin = true
self.txtPassword.text = ""
self.lblShowError.text = "密码错误,请重试..."
}
}
// func textFieldDidEndEditing(textField: UITextField) {
//
// self.checkPassword()
//
// }
// func textFieldShouldReturn(textField: UITextField) -> Bool {
// if textField == self.txtPassword{
// self.txtPassword.resignFirstResponder()
// }
//
// return true
// }
// override func prefersStatusBarHidden() -> Bool {
// return true
// }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
var rowCount = self.searchbar.text.length > 0 ? self.allMembers.count : totalMembers.count
return rowCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var anyData: AnyObject = (self.searchbar.text.length > 0) ? allMembers[indexPath.row] : totalMembers[indexPath.row]
var gbMember = GBMember(keyValues: anyData)
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentify, forIndexPath: indexPath) as! SignInTableviewCell
cell.lblSignInUserId.text = gbMember.name
cell.btnSignIn.tag = indexPath.row
cell.btnSignIn.addTarget(self, action: "signInClick:", forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func saveMemberToDic(mb: GBMember) -> Bool {
var dict = NSMutableDictionary()
dict["id"] = mb.id
dict["name"] = mb.name
dict["type"] = mb.type
dict["role"] = mb.role
dict["password"] = mb.password
dict["username"] = mb.username
self.password = mb.password
member = mb
var success = dict.writeToFile(memberInfoPath, atomically: true)
return success
}
func signInClick(sender: UIButton){
self.loginView.hidden = false
var mb: GBMember = self.searchbar.text.length > 0 ? GBMember(keyValues: allMembers[sender.tag]) : GBMember(keyValues: totalMembers[sender.tag])
password = mb.password
userName = mb.username
var success = saveMemberToDic(mb)
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.text = ""
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.cover.hidden = false
self.cover.alpha = 0.8
})
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.text = ""
self.cover.hidden = true
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if count(searchText) > 0 {
self.cover.hidden = true
self.searchText = searchText
}else{
self.cover.hidden = false
self.searchText = ""
}
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.text = ""
self.searchbar.resignFirstResponder()
self.cover.hidden = true
}
func coverClick(){
searchbar.text = ""
self.cover.hidden = true
self.searchbar.resignFirstResponder()
}
func keyboardWillHide(sender: NSNotification) {
self.animateTextField(false)
}
func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
kbHeight = (keyboardSize.width > keyboardSize.height) ? (keyboardSize.height * 0.5) : 0
self.animateTextField(true)
}
}
}
func animateTextField(up: Bool) {
var movement = (up ? -kbHeight : kbHeight)
// println("movement = \(movement)")
UIView.animateWithDuration(0.3, animations: {
self.loginView.frame = CGRectOffset(self.loginView.frame, 0, movement)
})
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| bsd-3-clause |
LoganWright/vapor | Sources/Development/Controllers/UserController.swift | 1 | 1291 | import Vapor
class UserController: Controller {
required init(application: Application) {
Log.info("User controller created")
}
/**
Display many instances
*/
func index(_ request: Request) throws -> ResponseRepresentable {
return Json([
"controller": "MyController.index"
])
}
/**
Create a new instance.
*/
func store(_ request: Request) throws -> ResponseRepresentable {
return Json([
"controller": "MyController.store"
])
}
/**
Show an instance.
*/
func show(_ request: Request, item user: User) throws -> ResponseRepresentable {
//User can be used like JSON with JsonRepresentable
return Json([
"controller": "MyController.show",
"user": user
])
}
/**
Update an instance.
*/
func update(_ request: Request, item user: User) throws -> ResponseRepresentable {
//Testing JsonRepresentable
return user.makeJson()
}
/**
Delete an instance.
*/
func destroy(_ request: Request, item user: User) throws -> ResponseRepresentable {
//User is ResponseRepresentable by proxy of JsonRepresentable
return user
}
}
| mit |
lukerdeluker/bagabaga | Source/Timeline.swift | 1 | 6967 | //
// Timeline.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`.
public srublic struct Timeline {
/// The time the request was initialized.
public let requestStartTime: CFAbsoluteTime
/// The time the first bytes were received from or sent to the server.
public let initialResponseTime: CFAbsoluteTime
/// The time when the request was completed.
public let requestCompletedTime: CFAbsoluteTime
/// The time when the response serialization was completed.
public let serializationCompletedTime: CFAbsoluteTime
/// The time interval in seconds from the time the request started to the initial response from the server.
public let latency: TimeInterval
/// The time interval in seconds from the time the request started to the time the request completed.
public let requestDuration: TimeInterval
/// The time interval in seconds from the time the request completed to the time response serialization completed.
public let serializationDuration: TimeInterval
/// The time interval in seconds from the time the request started to the time response serialization completed.
public let totalDuration: TimeInterval
/// Creates a new `Timeline` instance with the specified request times.
///
/// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`.
/// - parameter initialResponseTime: The time the first bytes were received from or sent to the server.
/// Defaults to `0.0`.
/// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`.
/// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults
/// to `0.0`.
///
/// - returns: The new `Timeline` instance.
public init(
duping: CFAbsoluteTime = 1,
requestStartTime: CFAbsoluteTime = 0.0,
initialResponseTime: CFAbsoluteTime = 0.0,
requestCompletedTime: CFAbsoluteTime = 0.0,
serializationCompletedTime: CFAbsoluteTime = 0.0)
{
self.requestStartTime = requestStartTime
self.initialResponseTime = initialResponseTime
self.requestCompletedTime = requestCompletedTime
self.serializationCompletedTime = serializationCompletedTime
self.latency = initialResponseTime - requestStartTime
self.requestDuration = requestCompletedTime - requestStartTime
self.serializationDuration = serializationCompletedTime - requestCompletedTime
self.totalDuration = serializationCompletedTime - requestStartTime
}
}
// MARK: - CustomStringConvertible
extension Timeline: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes the latency, the request
/// duration and the total duration.
public var description: String {
let latency = String(format: "%.3f", self.latency)
let requestDuration = String(format: "%.3f", self.requestDuration)
let serializationDuration = String(format: "%.3f", self.serializationDuration)
let totalDuration = String(format: "%.3f", self.totalDuration)
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
let timings = [
"\"Latency\": " + latency + " secs",
"\"Request Duration\": " + requestDuration + " secs",
"\"Serialization Duration\": " + serializationDuration + " secs",
"\"Total Duration\": " + totalDuration + " secs"
]
return "Timeline: { " + timings.joined(separator: ", ") + " }"
}
}
// MARK: - CustomDebugStringConvertible
extension Timeline: CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes the request start time, the
/// initial response time, the request completed time, the serialization completed time, the latency, the request
/// duration and the total duration.
public var debugDescription: String {
let requestStartTime = String(format: "%.3f", self.requestStartTime)
let initialResponseTime = String(format: "%.3f", self.initialResponseTime)
let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime)
let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime)
let latency = String(format: "%.3f", self.latency)
let requestDuration = String(format: "%.3f", self.requestDuration)
let serializationDuration = String(format: "%.3f", self.serializationDuration)
let totalDuration = String(format: "%.3f", self.totalDuration)
// NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is
// fixed, we should move back to string interpolation by reverting commit 7d4a43b1.
let timings = [
"\"Request Start Time\": " + requestStartTime,
"\"Initial Response Time\": " + initialResponseTime,
"\"Request Completed Time\": " + requestCompletedTime,
"\"Serialization Completed Time\": " + serializationCompletedTime,
"\"Latency\": " + latency + " secs",
"\"Request Duration\": " + requestDuration + " secs",
"\"Serialization Duration\": " + serializationDuration + " secs",
"\"Total Duration\": " + totalDuration + " secs"
]
return "Timeline: { " + timings.joined(separator: ", ") + " }"
}
}
| mit |
inquisitiveSoft/Syml-Theme-Editor | Syml Theme Editor/NSColor.swift | 1 | 599 | //
// NSColor.swift
// Syml Theme Editor
//
// Created by Harry Jordan on 21/11/2015.
// Copyright © 2015 Inquisitive Software. All rights reserved.
//
import AppKit
extension NSColor {
func commaSeperatedValues() -> String {
// Look for RGBA first
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
let color = colorUsingColorSpace(NSColorSpace.deviceRGBColorSpace()) ?? .magentaColor()
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return String(format: "%.5f, %.5f, %.5f, %.5f", red, green, blue, alpha)
}
} | mit |
KrishMunot/swift | test/SILOptimizer/sil_locations.swift | 6 | 987 | // RUN: %target-swift-frontend -primary-file %s -emit-sil -emit-verbose-sil | FileCheck %s
func searchForMe(_ x: Float) -> Float {
return x
}
@_transparent func baz(_ x: Float) -> Float {
return searchForMe(x);
}
@_transparent func bar(_ x: Float, _ b: Bool) -> Float {
if b {
return baz(x)
}
return x
// CHECK-LABEL: _TF13sil_locations3bar
// CHECK: function_ref @_TF13sil_locations11searchForMe{{.*}} line:13:12:minlined
// CHECK: apply {{.*}} line:13:12:minlined
}
func testMandatoryInlining(_ x: Float, b: Bool) -> Float {
return bar(x, b)
// CHECK-LABEL: _TF13sil_locations21testMandatoryInlining
// CHECK: function_ref @_TF13sil_locations11searchFor{{.*}} line:22:10:minlined
// CHECK: apply {{.*}} line:22:10:minlined
// CHECK: br {{.*}} line:22:10:minlined
// CHECK: br {{.*}} line:22:10:minlined
}
| apache-2.0 |
ZhangHangwei/100_days_Swift | Project_12/Project_11/NewItemViewController.swift | 1 | 819 | //
// NewItemViewController.swift
// Project_11
//
// Created by 章航伟 on 26/01/2017.
// Copyright © 2017 Harvie. All rights reserved.
//
import UIKit
class NewItemViewController: UIViewController {
var compeletion: ((_ newItem: String) -> Void)?
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension NewItemViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.text!.isEmpty {
return false
}
if let compeletion = compeletion {
compeletion(textField.text!)
}
navigationController!.popViewController(animated: true)
return true
}
}
| mit |
ruslanskorb/CoreStore | Sources/CoreStore+Querying.swift | 1 | 24853 | //
// CoreStore+Querying.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
// MARK: - CoreStore
@available(*, deprecated, message: "Call methods directly from the DataStack instead")
extension CoreStore {
/**
Using the `CoreStoreDefaults.dataStack`, fetches the `DynamicObject` instance in the `DataStack`'s context from a reference created from a transaction or from a different managed object context.
- parameter object: a reference to the object created/fetched outside the `DataStack`
- returns: the `DynamicObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/
public static func fetchExisting<O: DynamicObject>(_ object: O) -> O? {
return CoreStoreDefaults.dataStack.fetchExisting(object)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the `DynamicObject` instance in the `DataStack`'s context from an `NSManagedObjectID`.
- parameter objectID: the `NSManagedObjectID` for the object
- returns: the `DynamicObject` instance if the object exists in the `DataStack`, or `nil` if not found.
*/
public static func fetchExisting<O: DynamicObject>(_ objectID: NSManagedObjectID) -> O? {
return CoreStoreDefaults.dataStack.fetchExisting(objectID)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the `DynamicObject` instances in the `DataStack`'s context from references created from a transaction or from a different managed object context.
- parameter objects: an array of `DynamicObject`s created/fetched outside the `DataStack`
- returns: the `DynamicObject` array for objects that exists in the `DataStack`
*/
public static func fetchExisting<O: DynamicObject, S: Sequence>(_ objects: S) -> [O] where S.Iterator.Element == O {
return CoreStoreDefaults.dataStack.fetchExisting(objects)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the `DynamicObject` instances in the `DataStack`'s context from a list of `NSManagedObjectID`.
- parameter objectIDs: the `NSManagedObjectID` array for the objects
- returns: the `DynamicObject` array for objects that exists in the `DataStack`
*/
public static func fetchExisting<O: DynamicObject, S: Sequence>(_ objectIDs: S) -> [O] where S.Iterator.Element == NSManagedObjectID {
return CoreStoreDefaults.dataStack.fetchExisting(objectIDs)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the first `DynamicObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchOne<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> O? {
return try CoreStoreDefaults.dataStack.fetchOne(from, fetchClauses)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the first `DynamicObject` instance that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the first `DynamicObject` instance that satisfies the specified `FetchClause`s, or `nil` if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchOne<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> O? {
return try CoreStoreDefaults.dataStack.fetchOne(from, fetchClauses)
}
/**
Fetches the first `DynamicObject` instance that satisfies the specified `FetchChainableBuilderType` built from a chain of clauses.
```
let youngestTeen = dataStack.fetchOne(
From<MyPersonEntity>()
.where(\.age > 18)
.orderBy(.ascending(\.age))
)
```
- parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses
- returns: the first `DynamicObject` instance that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchOne<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> B.ObjectType? {
return try CoreStoreDefaults.dataStack.fetchOne(clauseChain)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches all `DynamicObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchAll<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> [O] {
return try CoreStoreDefaults.dataStack.fetchAll(from, fetchClauses)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches all `DynamicObject` instances that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: all `DynamicObject` instances that satisfy the specified `FetchClause`s, or an empty array if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchAll<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> [O] {
return try CoreStoreDefaults.dataStack.fetchAll(from, fetchClauses)
}
/**
Fetches all `DynamicObject` instances that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses.
```
let people = dataStack.fetchAll(
From<MyPersonEntity>()
.where(\.age > 18)
.orderBy(.ascending(\.age))
)
```
- parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses
- returns: all `DynamicObject` instances that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchAll<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> [B.ObjectType] {
return try CoreStoreDefaults.dataStack.fetchAll(clauseChain)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the number of `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchCount<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> Int {
return try CoreStoreDefaults.dataStack.fetchCount(from, fetchClauses)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the number of `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the number of `DynamicObject`s that satisfy the specified `FetchClause`s
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchCount<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> Int {
return try CoreStoreDefaults.dataStack.fetchCount(from, fetchClauses)
}
/**
Fetches the number of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses.
```
let numberOfAdults = dataStack.fetchCount(
From<MyPersonEntity>()
.where(\.age > 18)
.orderBy(.ascending(\.age))
)
```
- parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses
- returns: the number of `DynamicObject`s that satisfy the specified `FetchChainableBuilderType`
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchCount<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> Int {
return try CoreStoreDefaults.dataStack.fetchCount(clauseChain)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchObjectID<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> NSManagedObjectID? {
return try CoreStoreDefaults.dataStack.fetchObjectID(from, fetchClauses)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchClause`s, or `nil` if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchObjectID<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> NSManagedObjectID? {
return try CoreStoreDefaults.dataStack.fetchObjectID(from, fetchClauses)
}
/**
Fetches the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchChainableBuilderType` built from a chain of clauses.
```
let youngestTeenID = dataStack.fetchObjectID(
From<MyPersonEntity>()
.where(\.age > 18)
.orderBy(.ascending(\.age))
)
```
- parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses
- returns: the `NSManagedObjectID` for the first `DynamicObject` that satisfies the specified `FetchChainableBuilderType`, or `nil` if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchObjectID<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> NSManagedObjectID? {
return try CoreStoreDefaults.dataStack.fetchObjectID(clauseChain)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchObjectIDs<O>(_ from: From<O>, _ fetchClauses: FetchClause...) throws -> [NSManagedObjectID] {
return try CoreStoreDefaults.dataStack.fetchObjectIDs(from, fetchClauses)
}
/**
Using the `CoreStoreDefaults.dataStack`, fetches the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- parameter from: a `From` clause indicating the entity type
- parameter fetchClauses: a series of `FetchClause` instances for the fetch request. Accepts `Where`, `OrderBy`, and `Tweak` clauses.
- returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchClause`s, or an empty array if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchObjectIDs<O>(_ from: From<O>, _ fetchClauses: [FetchClause]) throws -> [NSManagedObjectID] {
return try CoreStoreDefaults.dataStack.fetchObjectIDs(from, fetchClauses)
}
/**
Fetches the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchChainableBuilderType` built from a chain of clauses.
```
let idsOfAdults = transaction.fetchObjectIDs(
From<MyPersonEntity>()
.where(\.age > 18)
.orderBy(.ascending(\.age))
)
```
- parameter clauseChain: a `FetchChainableBuilderType` built from a chain of clauses
- returns: the `NSManagedObjectID` for all `DynamicObject`s that satisfy the specified `FetchChainableBuilderType`, or an empty array if no match was found
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func fetchObjectIDs<B: FetchChainableBuilderType>(_ clauseChain: B) throws -> [NSManagedObjectID] {
return try CoreStoreDefaults.dataStack.fetchObjectIDs(clauseChain)
}
/**
Using the `CoreStoreDefaults.dataStack`, queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select<U>` parameter.
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func queryValue<O, U: QueryableAttributeType>(_ from: From<O>, _ selectClause: Select<O, U>, _ queryClauses: QueryClause...) throws -> U? {
return try CoreStoreDefaults.dataStack.queryValue(from, selectClause, queryClauses)
}
/**
Using the `CoreStoreDefaults.dataStack`, queries aggregate values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query, or `nil` if no match was found. The type of the return value is specified by the generic type of the `Select<U>` parameter.
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func queryValue<O, U: QueryableAttributeType>(_ from: From<O>, _ selectClause: Select<O, U>, _ queryClauses: [QueryClause]) throws -> U? {
return try CoreStoreDefaults.dataStack.queryValue(from, selectClause, queryClauses)
}
/**
Queries a property value or aggregate as specified by the `QueryChainableBuilderType` built from a chain of clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
```
let averageAdultAge = dataStack.queryValue(
From<MyPersonEntity>()
.select(Int.self, .average(\.age))
.where(\.age > 18)
)
```
- parameter clauseChain: a `QueryChainableBuilderType` indicating the property/aggregate to fetch and the series of queries for the request.
- returns: the result of the the query as specified by the `QueryChainableBuilderType`, or `nil` if no match was found.
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func queryValue<B: QueryChainableBuilderType>(_ clauseChain: B) throws -> B.ResultType? where B.ResultType: QueryableAttributeType {
return try CoreStoreDefaults.dataStack.queryValue(clauseChain)
}
/**
Using the `CoreStoreDefaults.dataStack`, queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func queryAttributes<O>(_ from: From<O>, _ selectClause: Select<O, NSDictionary>, _ queryClauses: QueryClause...) throws -> [[String: Any]] {
return try CoreStoreDefaults.dataStack.queryAttributes(from, selectClause, queryClauses)
}
/**
Using the `CoreStoreDefaults.dataStack`, queries a dictionary of attribute values as specified by the `QueryClause`s. Requires at least a `Select` clause, and optional `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
- parameter from: a `From` clause indicating the entity type
- parameter selectClause: a `Select<U>` clause indicating the properties to fetch, and with the generic type indicating the return type.
- parameter queryClauses: a series of `QueryClause` instances for the query request. Accepts `Where`, `OrderBy`, `GroupBy`, and `Tweak` clauses.
- returns: the result of the the query. The type of the return value is specified by the generic type of the `Select<U>` parameter.
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func queryAttributes<O>(_ from: From<O>, _ selectClause: Select<O, NSDictionary>, _ queryClauses: [QueryClause]) throws -> [[String: Any]] {
return try CoreStoreDefaults.dataStack.queryAttributes(from, selectClause, queryClauses)
}
/**
Queries a dictionary of attribute values or as specified by the `QueryChainableBuilderType` built from a chain of clauses.
A "query" differs from a "fetch" in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.
```
let results = dataStack.queryAttributes(
From<MyPersonEntity>()
.select(
NSDictionary.self,
.attribute(\.age, as: "age"),
.count(\.age, as: "numberOfPeople")
)
.groupBy(\.age)
)
for dictionary in results! {
let age = dictionary["age"] as! Int
let count = dictionary["numberOfPeople"] as! Int
print("There are \(count) people who are \(age) years old."
}
```
- parameter clauseChain: a `QueryChainableBuilderType` indicating the properties to fetch and the series of queries for the request.
- returns: the result of the the query as specified by the `QueryChainableBuilderType`
- throws: `CoreStoreError.persistentStoreNotFound` if the specified entity could not be found in any store's schema.
*/
public static func queryAttributes<B: QueryChainableBuilderType>(_ clauseChain: B) throws -> [[String: Any]] where B.ResultType == NSDictionary {
return try CoreStoreDefaults.dataStack.queryAttributes(clauseChain)
}
}
| mit |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Editor/Controller/Photo/PhotoEditorViewController.swift | 1 | 18504 | //
// PhotoEditorViewController.swift
// HXPHPicker
//
// Created by Slience on 2021/1/9.
//
import UIKit
import Photos
#if canImport(Kingfisher)
import Kingfisher
#endif
open class PhotoEditorViewController: BaseViewController {
public weak var delegate: PhotoEditorViewControllerDelegate?
/// 配置
public let config: PhotoEditorConfiguration
/// 当前编辑的图片
public private(set) var image: UIImage!
/// 来源
public let sourceType: EditorController.SourceType
/// 当前编辑状态
public var state: State { pState }
/// 上一次的编辑结果
public let editResult: PhotoEditResult?
/// 确认/取消之后自动退出界面
public var autoBack: Bool = true
public var finishHandler: FinishHandler?
public var cancelHandler: CancelHandler?
public typealias FinishHandler = (PhotoEditorViewController, PhotoEditResult?) -> Void
public typealias CancelHandler = (PhotoEditorViewController) -> Void
/// 编辑image
/// - Parameters:
/// - image: 对应的 UIImage
/// - editResult: 上一次编辑结果
/// - config: 编辑配置
public init(
image: UIImage,
editResult: PhotoEditResult? = nil,
config: PhotoEditorConfiguration
) {
PhotoManager.shared.appearanceStyle = config.appearanceStyle
PhotoManager.shared.createLanguageBundle(languageType: config.languageType)
sourceType = .local
self.image = image
self.config = config
self.editResult = editResult
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = config.modalPresentationStyle
}
#if HXPICKER_ENABLE_PICKER
/// 当前编辑的PhotoAsset对象
public private(set) var photoAsset: PhotoAsset!
/// 编辑 PhotoAsset
/// - Parameters:
/// - photoAsset: 对应数据的 PhotoAsset
/// - editResult: 上一次编辑结果
/// - config: 编辑配置
public init(
photoAsset: PhotoAsset,
editResult: PhotoEditResult? = nil,
config: PhotoEditorConfiguration
) {
PhotoManager.shared.appearanceStyle = config.appearanceStyle
PhotoManager.shared.createLanguageBundle(languageType: config.languageType)
sourceType = .picker
requestType = 1
needRequest = true
self.config = config
self.editResult = editResult
self.photoAsset = photoAsset
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = config.modalPresentationStyle
}
#endif
#if canImport(Kingfisher)
/// 当前编辑的网络图片地址
public private(set) var networkImageURL: URL?
/// 编辑网络图片
/// - Parameters:
/// - networkImageURL: 对应的网络地址
/// - editResult: 上一次编辑结果
/// - config: 编辑配置
public init(
networkImageURL: URL,
editResult: PhotoEditResult? = nil,
config: PhotoEditorConfiguration
) {
PhotoManager.shared.appearanceStyle = config.appearanceStyle
PhotoManager.shared.createLanguageBundle(languageType: config.languageType)
sourceType = .network
requestType = 2
needRequest = true
self.networkImageURL = networkImageURL
self.config = config
self.editResult = editResult
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = config.modalPresentationStyle
}
#endif
var pState: State = .normal
var filterHDImage: UIImage?
var mosaicImage: UIImage?
var thumbnailImage: UIImage!
var transitionalImage: UIImage?
var transitionCompletion: Bool = true
var isFinishedBack: Bool = false
private var needRequest: Bool = false
private var requestType: Int = 0
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
lazy var imageView: PhotoEditorView = {
let imageView = PhotoEditorView(
editType: .image,
cropConfig: config.cropping,
mosaicConfig: config.mosaic,
brushConfig: config.brush,
exportScale: config.scale,
editedImageURL: config.editedImageURL
)
imageView.editorDelegate = self
return imageView
}()
var topViewIsHidden: Bool = false
@objc func singleTap() {
if state == .cropping {
return
}
imageView.deselectedSticker()
func resetOtherOption() {
if let option = currentToolOption {
if option.type == .graffiti {
imageView.drawEnabled = true
}else if option.type == .mosaic {
imageView.mosaicEnabled = true
}
}
showTopView()
}
if isFilter {
isFilter = false
resetOtherOption()
hiddenFilterView()
imageView.canLookOriginal = false
return
}
if showChartlet {
imageView.isEnabled = true
showChartlet = false
resetOtherOption()
hiddenChartletView()
return
}
if topViewIsHidden {
showTopView()
}else {
hidenTopView()
}
}
/// 裁剪确认视图
public lazy var cropConfirmView: EditorCropConfirmView = {
let cropConfirmView = EditorCropConfirmView.init(config: config.cropConfimView, showReset: true)
cropConfirmView.alpha = 0
cropConfirmView.isHidden = true
cropConfirmView.delegate = self
return cropConfirmView
}()
public lazy var toolView: EditorToolView = {
let toolView = EditorToolView.init(config: config.toolView)
toolView.delegate = self
return toolView
}()
public lazy var topView: UIView = {
let view = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 44))
let cancelBtn = UIButton.init(frame: CGRect(x: 0, y: 0, width: 57, height: 44))
cancelBtn.setImage(UIImage.image(for: "hx_editor_back"), for: .normal)
cancelBtn.addTarget(self, action: #selector(didBackButtonClick), for: .touchUpInside)
view.addSubview(cancelBtn)
return view
}()
@objc func didBackButtonClick() {
transitionalImage = image
cancelHandler?(self)
didBackClick(true)
}
func didBackClick(_ isCancel: Bool = false) {
imageView.imageResizerView.stopShowMaskBgTimer()
if let type = currentToolOption?.type {
switch type {
case .graffiti:
hiddenBrushColorView()
case .mosaic:
hiddenMosaicToolView()
default:
break
}
}
if isCancel {
delegate?.photoEditorViewController(didCancel: self)
}
if autoBack {
if let navigationController = navigationController, navigationController.viewControllers.count > 1 {
navigationController.popViewController(animated: true)
}else {
dismiss(animated: true, completion: nil)
}
}
}
public lazy var topMaskLayer: CAGradientLayer = {
let layer = PhotoTools.getGradientShadowLayer(true)
return layer
}()
lazy var brushSizeView: BrushSizeView = {
let lineWidth = imageView.brushLineWidth + 4
let view = BrushSizeView(frame: CGRect(origin: .zero, size: CGSize(width: lineWidth, height: lineWidth)))
return view
}()
public lazy var brushColorView: PhotoEditorBrushColorView = {
let view = PhotoEditorBrushColorView(config: config.brush)
view.delegate = self
view.alpha = 0
view.isHidden = true
return view
}()
var showChartlet: Bool = false
lazy var chartletView: EditorChartletView = {
let view = EditorChartletView(
config: config.chartlet,
editorType: .photo
)
view.delegate = self
return view
}()
public lazy var cropToolView: PhotoEditorCropToolView = {
var showRatios = true
if config.cropping.fixedRatio || config.cropping.isRoundCrop {
showRatios = false
}
let view = PhotoEditorCropToolView.init(
showRatios: showRatios,
scaleArray: config.cropping.aspectRatios
)
view.delegate = self
view.themeColor = config.cropping.aspectRatioSelectedColor
view.alpha = 0
view.isHidden = true
return view
}()
lazy var mosaicToolView: PhotoEditorMosaicToolView = {
let view = PhotoEditorMosaicToolView(selectedColor: config.toolView.toolSelectedColor)
view.delegate = self
view.alpha = 0
view.isHidden = true
return view
}()
var isFilter = false
var filterImage: UIImage?
lazy var filterView: PhotoEditorFilterView = {
let view = PhotoEditorFilterView(
filterConfig: config.filter,
hasLastFilter: editResult?.editedData.hasFilter ?? false
)
view.delegate = self
return view
}()
var imageInitializeCompletion = false
var orientationDidChange: Bool = false
var imageViewDidChange: Bool = true
var currentToolOption: EditorToolOptions?
var toolOptions: EditorToolView.Options = []
open override func viewDidLoad() {
super.viewDidLoad()
for options in config.toolView.toolOptions {
switch options.type {
case .graffiti:
toolOptions.insert(.graffiti)
case .chartlet:
toolOptions.insert(.chartlet)
case .text:
toolOptions.insert(.text)
case .cropSize:
toolOptions.insert(.cropSize)
case .mosaic:
toolOptions.insert(.mosaic)
case .filter:
toolOptions.insert(.filter)
case .music:
toolOptions.insert(.music)
default:
break
}
}
let singleTap = UITapGestureRecognizer.init(target: self, action: #selector(singleTap))
singleTap.delegate = self
view.addGestureRecognizer(singleTap)
view.isExclusiveTouch = true
view.backgroundColor = .black
view.clipsToBounds = true
view.addSubview(imageView)
view.addSubview(toolView)
if toolOptions.contains(.cropSize) {
view.addSubview(cropConfirmView)
view.addSubview(cropToolView)
}
if config.fixedCropState {
pState = .cropping
toolView.alpha = 0
toolView.isHidden = true
topView.alpha = 0
topView.isHidden = true
}else {
pState = config.state
if toolOptions.contains(.graffiti) {
view.addSubview(brushColorView)
}
if toolOptions.contains(.chartlet) {
view.addSubview(chartletView)
}
if toolOptions.contains(.mosaic) {
view.addSubview(mosaicToolView)
}
if toolOptions.contains(.filter) {
view.addSubview(filterView)
}
}
view.layer.addSublayer(topMaskLayer)
view.addSubview(topView)
if needRequest {
if requestType == 1 {
#if HXPICKER_ENABLE_PICKER
requestImage()
#endif
}else if requestType == 2 {
#if canImport(Kingfisher)
requestNetworkImage()
#endif
}
}else {
if !config.fixedCropState {
localImageHandler()
}
}
}
open override func deviceOrientationWillChanged(notify: Notification) {
orientationDidChange = true
imageViewDidChange = false
if showChartlet {
singleTap()
}
imageView.undoAllDraw()
if toolOptions.contains(.graffiti) {
brushColorView.canUndo = imageView.canUndoDraw
}
imageView.undoAllMosaic()
if toolOptions.contains(.mosaic) {
mosaicToolView.canUndo = imageView.canUndoMosaic
}
imageView.undoAllSticker()
imageView.reset(false)
imageView.finishCropping(false)
if config.fixedCropState {
return
}
pState = .normal
croppingAction()
}
open override func deviceOrientationDidChanged(notify: Notification) {
// orientationDidChange = true
// imageViewDidChange = false
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
toolView.frame = CGRect(
x: 0,
y: view.height - UIDevice.bottomMargin - 50,
width: view.width,
height: 50 + UIDevice.bottomMargin
)
toolView.reloadContentInset()
topView.width = view.width
topView.height = navigationController?.navigationBar.height ?? 44
let cancelButton = topView.subviews.first
cancelButton?.x = UIDevice.leftMargin
if let modalPresentationStyle = navigationController?.modalPresentationStyle,
UIDevice.isPortrait {
if modalPresentationStyle == .fullScreen || modalPresentationStyle == .custom {
topView.y = UIDevice.generalStatusBarHeight
}
}else if (modalPresentationStyle == .fullScreen || modalPresentationStyle == .custom) && UIDevice.isPortrait {
topView.y = UIDevice.generalStatusBarHeight
}
topMaskLayer.frame = CGRect(x: 0, y: 0, width: view.width, height: topView.frame.maxY + 10)
let cropToolFrame = CGRect(x: 0, y: toolView.y - 60, width: view.width, height: 60)
if toolOptions.contains(.cropSize) {
cropConfirmView.frame = toolView.frame
cropToolView.frame = cropToolFrame
cropToolView.updateContentInset()
}
if toolOptions.contains(.graffiti) {
brushColorView.frame = CGRect(x: 0, y: toolView.y - 85, width: view.width, height: 85)
}
if toolOptions.contains(.mosaic) {
mosaicToolView.frame = cropToolFrame
}
if toolOptions.isSticker {
setChartletViewFrame()
}
if toolOptions.contains(.filter) {
setFilterViewFrame()
}
if !imageView.frame.equalTo(view.bounds) && !imageView.frame.isEmpty && !imageViewDidChange {
imageView.frame = view.bounds
imageView.reset(false)
imageView.finishCropping(false)
orientationDidChange = true
}else {
imageView.frame = view.bounds
}
if !imageInitializeCompletion {
if !needRequest || image != nil {
imageView.setImage(image)
// setFilterImage()
if let editedData = editResult?.editedData {
imageView.setEditedData(editedData: editedData)
if toolOptions.contains(.graffiti) {
brushColorView.canUndo = imageView.canUndoDraw
}
if toolOptions.contains(.mosaic) {
mosaicToolView.canUndo = imageView.canUndoMosaic
}
}
imageInitializeCompletion = true
if transitionCompletion {
initializeStartCropping()
}
}
}
if orientationDidChange {
imageView.orientationDidChange()
if config.fixedCropState {
imageView.startCropping(false)
}
orientationDidChange = false
imageViewDidChange = true
}
}
func initializeStartCropping() {
if !imageInitializeCompletion || state != .cropping {
return
}
imageView.startCropping(true)
croppingAction()
}
func setChartletViewFrame() {
var viewHeight = config.chartlet.viewHeight
if viewHeight > view.height {
viewHeight = view.height * 0.6
}
if showChartlet {
chartletView.frame = CGRect(
x: 0,
y: view.height - viewHeight - UIDevice.bottomMargin,
width: view.width,
height: viewHeight + UIDevice.bottomMargin
)
}else {
chartletView.frame = CGRect(
x: 0,
y: view.height,
width: view.width,
height: viewHeight + UIDevice.bottomMargin
)
}
}
func setFilterViewFrame() {
if isFilter {
filterView.frame = CGRect(
x: 0,
y: view.height - 150 - UIDevice.bottomMargin,
width: view.width,
height: 150 + UIDevice.bottomMargin
)
}else {
filterView.frame = CGRect(
x: 0,
y: view.height + 10,
width: view.width,
height: 150 + UIDevice.bottomMargin
)
}
}
open override var prefersStatusBarHidden: Bool {
return config.prefersStatusBarHidden
}
open override var prefersHomeIndicatorAutoHidden: Bool {
false
}
open override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge {
.all
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if navigationController?.topViewController != self &&
navigationController?.viewControllers.contains(self) == false {
navigationController?.setNavigationBarHidden(false, animated: true)
}
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if navigationController?.viewControllers.count == 1 {
navigationController?.setNavigationBarHidden(true, animated: false)
}else {
navigationController?.setNavigationBarHidden(true, animated: true)
}
}
func setImage(_ image: UIImage) {
self.image = image
}
}
| mit |
srn214/Floral | Floral/Floral/Classes/Module/Community(研究院)/Controller/Other/LDTeacherCourseController.swift | 1 | 3053 | //
// LDTeacherCourseController.swift
// Floral
//
// Created by LDD on 2019/7/21.
// Copyright © 2019 文刂Rn. All rights reserved.
//
import UIKit
import RxCocoa
import Differentiator
import RxDataSources
class LDTeacherCourseController: CollectionViewController<LDTeacherCourseVM> {
let teacherId = BehaviorRelay<String>(value: "")
override func viewDidLoad() {
super.viewDidLoad()
}
override func setupUI() {
super.setupUI()
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: k_Margin_Fifteen, right: 0)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(cellWithClass: LDRecommendCell.self)
collectionView.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: LDRecommendReusableView.self)
collectionView.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: LDRecommendBannerReusableView.self)
collectionView.refreshHeader = RefreshNormalHeader()
collectionView.refreshFooter = RefreshFooter()
beginHeaderRefresh()
}
override func bindVM() {
super.bindVM()
//设置代理
collectionView.rx.setDelegate(self)
.disposed(by: rx.disposeBag)
let input = LDTeacherCourseVM.Input(teacherId: teacherId.value)
let output = viewModel.transform(input: input)
output.items.drive(collectionView.rx.items) { (cv, row, item) in
let cell = cv.dequeueReusableCell(withClass: LDRecommendCell.self, for: IndexPath(item: row, section: 0))
cell.info = (item.title, item.teacher, item.imgUrl)
return cell
}
.disposed(by: rx.disposeBag)
}
}
extension LDTeacherCourseController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let row: CGFloat = 3
let w = Int((ScreenWidth - autoDistance(5) * (row - 1)) / row)
return CGSize(width: CGFloat(w), height: autoDistance(200))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return k_Margin_Fifteen
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return autoDistance(5)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: ScreenWidth, height: k_Margin_Fifteen)
}
}
| mit |
tkremenek/swift | test/IRGen/autolink-force-link.swift | 13 | 1753 | // RUN: %empty-directory(%t)
// RUN: %swift -disable-legacy-type-info -target x86_64-apple-macosx10.9 -parse-stdlib -autolink-force-load -module-name TEST -module-link-name TEST -emit-ir %s %S/../Inputs/empty.swift | %FileCheck -check-prefix=CHECK-WMO %s
// CHECK-WMO: source_filename = "<swift-imported-modules>"
// CHECK-WMO: @"_swift_FORCE_LOAD_$_TEST"
// CHECK-WMO-NOT: source_filename
// RUN: %swift -disable-legacy-type-info -target x86_64-apple-macosx10.9 -parse-stdlib -autolink-force-load -module-name TEST -module-link-name TEST -emit-ir -num-threads 1 %s %S/../Inputs/empty.swift | %FileCheck -check-prefix=CHECK-WMO-THREADED %s
// CHECK-WMO-THREADED: source_filename = "<swift-imported-modules>"
// CHECK-WMO-THREADED: @"_swift_FORCE_LOAD_$_TEST"
// CHECK-WMO-THREADED: source_filename = "<swift-imported-modules>"
// CHECK-WMO-THREADED: @"_swift_FORCE_LOAD_$_TEST"
// RUN: %swift -disable-legacy-type-info -target x86_64-apple-macosx10.9 -parse-stdlib -autolink-force-load -module-name TEST -module-link-name TEST -emit-ir -primary-file %s %S/../Inputs/empty.swift | %FileCheck -check-prefix=CHECK-SINGLE-FILE-FIRST %s
// RUN: %swift -disable-legacy-type-info -target x86_64-apple-macosx10.9 -parse-stdlib -autolink-force-load -module-name TEST -module-link-name TEST -emit-ir %S/../Inputs/empty.swift -primary-file %s | %FileCheck -check-prefix=CHECK-SINGLE-FILE-SECOND %s
// CHECK-SINGLE-FILE-FIRST: source_filename = "<swift-imported-modules>"
// CHECK-SINGLE-FILE-FIRST: @"_swift_FORCE_LOAD_$_TEST"
// CHECK-SINGLE-FILE-FIRST-NOT: source_filename
// CHECK-SINGLE-FILE-SECOND: source_filename = "<swift-imported-modules>"
// CHECK-SINGLE-FILE-SECOND: @"_swift_FORCE_LOAD_$_TEST"
// CHECK-SINGLE-FILE-SECOND-NOT: source_filename
| apache-2.0 |
Urinx/Vu | 唯舞/唯舞/SearchViewController.swift | 2 | 4895 | //
// SecondViewController.swift
// 唯舞
//
// Created by Eular on 15/8/15.
// Copyright © 2015年 Eular. All rights reserved.
//
import UIKit
class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UIScrollViewDelegate {
@IBOutlet weak var searchBox: UISearchBar!
@IBOutlet weak var searchTableView: UITableView!
let videoSegueIdentifier = "jumpToVideo"
var searchVideoList = [VideoModel]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
searchBox.keyboardAppearance = .Dark
searchBox.delegate = self
searchTableView.dataSource = self
searchTableView.delegate = self
searchTableView.hidden = true
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchVideoList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath)
let row = indexPath.row
let video = searchVideoList[row]
let imgUI = cell.viewWithTag(1) as! UIImageView
let titleUI = cell.viewWithTag(2) as! UILabel
let viewUI = cell.viewWithTag(3) as! UILabel
let commentUI = cell.viewWithTag(4) as! UILabel
imgUI.imageFromUrl(video.thumbnail)
titleUI.text = video.title
viewUI.text = video.views
commentUI.text = video.comments
return cell
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
searchVideoList.removeAll()
if let searchKey = searchBar.text {
loadSearchVideoListData(searchKey)
}
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
searchTableView.hidden = true
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
searchBox.resignFirstResponder()
}
// func scrollViewDidScroll(scrollView: UIScrollView) {
// searchBox.center.y = sy - scrollView.contentOffset.y
// }
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == videoSegueIdentifier {
let vc = segue.destinationViewController as! VideoViewController
let indexPath = searchTableView.indexPathForSelectedRow
vc.curVideo = searchVideoList[indexPath!.row]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
searchBox.resignFirstResponder()
}
func loadSearchVideoListData(key: String) {
let url = NSURL(string: "http://urinx.sinaapp.com/vu.json?search=\(key)")
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url!), queue: NSOperationQueue()) { (resp: NSURLResponse?, data: NSData?, err: NSError?) -> Void in
if let vData = data {
do {
let vuJson = try NSJSONSerialization.JSONObjectWithData(vData, options: NSJSONReadingOptions.AllowFragments)
let newList = vuJson.objectForKey("new")!
for i in newList as! NSArray {
let title = i.objectForKey("title") as! String
let src = i.objectForKey("src") as! String
let thumbnail = i.objectForKey("thumbnail") as! String
let views = i.objectForKey("views") as! String
let comments = i.objectForKey("comments") as! String
let time = i.objectForKey("time") as! String
self.searchVideoList.append(VideoModel(title: title, src: src, thumbnail: thumbnail, views: views, comments: comments, time: time))
}
} catch {
// ...
}
}
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
if self.searchVideoList.count == 0 {
self.view.makeToast(message: "换个关键词试试~ ^_^")
}
self.searchTableView.reloadData()
self.searchTableView.hidden = false
})
}
}
}
| apache-2.0 |
noppoMan/aws-sdk-swift | Sources/Soto/Services/AutoScaling/AutoScaling_API.swift | 1 | 46643 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
@_exported import SotoCore
/*
Client object for interacting with AWS AutoScaling service.
Amazon EC2 Auto Scaling Amazon EC2 Auto Scaling is designed to automatically launch or terminate EC2 instances based on user-defined scaling policies, scheduled actions, and health checks. Use this service with AWS Auto Scaling, Amazon CloudWatch, and Elastic Load Balancing. For more information, including information about granting IAM users required permissions for Amazon EC2 Auto Scaling actions, see the Amazon EC2 Auto Scaling User Guide.
*/
public struct AutoScaling: AWSService {
// MARK: Member variables
public let client: AWSClient
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the AutoScaling client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
service: "autoscaling",
serviceProtocol: .query,
apiVersion: "2011-01-01",
endpoint: endpoint,
errorType: AutoScalingErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Attaches one or more EC2 instances to the specified Auto Scaling group. When you attach instances, Amazon EC2 Auto Scaling increases the desired capacity of the group by the number of instances being attached. If the number of instances being attached plus the desired capacity of the group exceeds the maximum size of the group, the operation fails. If there is a Classic Load Balancer attached to your Auto Scaling group, the instances are also registered with the load balancer. If there are target groups attached to your Auto Scaling group, the instances are also registered with the target groups. For more information, see Attach EC2 Instances to Your Auto Scaling Group in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func attachInstances(_ input: AttachInstancesQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "AttachInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Attaches one or more target groups to the specified Auto Scaling group. To describe the target groups for an Auto Scaling group, call the DescribeLoadBalancerTargetGroups API. To detach the target group from the Auto Scaling group, call the DetachLoadBalancerTargetGroups API. With Application Load Balancers and Network Load Balancers, instances are registered as targets with a target group. With Classic Load Balancers, instances are registered with the load balancer. For more information, see Attaching a Load Balancer to Your Auto Scaling Group in the Amazon EC2 Auto Scaling User Guide.
public func attachLoadBalancerTargetGroups(_ input: AttachLoadBalancerTargetGroupsType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AttachLoadBalancerTargetGroupsResultType> {
return self.client.execute(operation: "AttachLoadBalancerTargetGroups", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// To attach an Application Load Balancer or a Network Load Balancer, use the AttachLoadBalancerTargetGroups API operation instead. Attaches one or more Classic Load Balancers to the specified Auto Scaling group. Amazon EC2 Auto Scaling registers the running instances with these Classic Load Balancers. To describe the load balancers for an Auto Scaling group, call the DescribeLoadBalancers API. To detach the load balancer from the Auto Scaling group, call the DetachLoadBalancers API. For more information, see Attaching a Load Balancer to Your Auto Scaling Group in the Amazon EC2 Auto Scaling User Guide.
public func attachLoadBalancers(_ input: AttachLoadBalancersType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AttachLoadBalancersResultType> {
return self.client.execute(operation: "AttachLoadBalancers", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes one or more scheduled actions for the specified Auto Scaling group.
public func batchDeleteScheduledAction(_ input: BatchDeleteScheduledActionType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchDeleteScheduledActionAnswer> {
return self.client.execute(operation: "BatchDeleteScheduledAction", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates or updates one or more scheduled scaling actions for an Auto Scaling group. If you leave a parameter unspecified when updating a scheduled scaling action, the corresponding value remains unchanged.
public func batchPutScheduledUpdateGroupAction(_ input: BatchPutScheduledUpdateGroupActionType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchPutScheduledUpdateGroupActionAnswer> {
return self.client.execute(operation: "BatchPutScheduledUpdateGroupAction", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Cancels an instance refresh operation in progress. Cancellation does not roll back any replacements that have already been completed, but it prevents new replacements from being started. For more information, see Replacing Auto Scaling Instances Based on an Instance Refresh.
public func cancelInstanceRefresh(_ input: CancelInstanceRefreshType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CancelInstanceRefreshAnswer> {
return self.client.execute(operation: "CancelInstanceRefresh", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Completes the lifecycle action for the specified token or instance with the specified result. This step is a part of the procedure for adding a lifecycle hook to an Auto Scaling group: (Optional) Create a Lambda function and a rule that allows CloudWatch Events to invoke your Lambda function when Amazon EC2 Auto Scaling launches or terminates instances. (Optional) Create a notification target and an IAM role. The target can be either an Amazon SQS queue or an Amazon SNS topic. The role allows Amazon EC2 Auto Scaling to publish lifecycle notifications to the target. Create the lifecycle hook. Specify whether the hook is used when the instances launch or terminate. If you need more time, record the lifecycle action heartbeat to keep the instance in a pending state. If you finish before the timeout period ends, complete the lifecycle action. For more information, see Amazon EC2 Auto Scaling Lifecycle Hooks in the Amazon EC2 Auto Scaling User Guide.
public func completeLifecycleAction(_ input: CompleteLifecycleActionType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CompleteLifecycleActionAnswer> {
return self.client.execute(operation: "CompleteLifecycleAction", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates an Auto Scaling group with the specified name and attributes. If you exceed your maximum limit of Auto Scaling groups, the call fails. To query this limit, call the DescribeAccountLimits API. For information about updating this limit, see Amazon EC2 Auto Scaling Service Quotas in the Amazon EC2 Auto Scaling User Guide. For introductory exercises for creating an Auto Scaling group, see Getting Started with Amazon EC2 Auto Scaling and Tutorial: Set Up a Scaled and Load-Balanced Application in the Amazon EC2 Auto Scaling User Guide. For more information, see Auto Scaling Groups in the Amazon EC2 Auto Scaling User Guide. Every Auto Scaling group has three size parameters (DesiredCapacity, MaxSize, and MinSize). Usually, you set these sizes based on a specific number of instances. However, if you configure a mixed instances policy that defines weights for the instance types, you must specify these sizes with the same units that you use for weighting instances.
@discardableResult public func createAutoScalingGroup(_ input: CreateAutoScalingGroupType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "CreateAutoScalingGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a launch configuration. If you exceed your maximum limit of launch configurations, the call fails. To query this limit, call the DescribeAccountLimits API. For information about updating this limit, see Amazon EC2 Auto Scaling Service Quotas in the Amazon EC2 Auto Scaling User Guide. For more information, see Launch Configurations in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func createLaunchConfiguration(_ input: CreateLaunchConfigurationType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "CreateLaunchConfiguration", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates or updates tags for the specified Auto Scaling group. When you specify a tag with a key that already exists, the operation overwrites the previous tag definition, and you do not get an error message. For more information, see Tagging Auto Scaling Groups and Instances in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func createOrUpdateTags(_ input: CreateOrUpdateTagsType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "CreateOrUpdateTags", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the specified Auto Scaling group. If the group has instances or scaling activities in progress, you must specify the option to force the deletion in order for it to succeed. If the group has policies, deleting the group deletes the policies, the underlying alarm actions, and any alarm that no longer has an associated action. To remove instances from the Auto Scaling group before deleting it, call the DetachInstances API with the list of instances and the option to decrement the desired capacity. This ensures that Amazon EC2 Auto Scaling does not launch replacement instances. To terminate all instances before deleting the Auto Scaling group, call the UpdateAutoScalingGroup API and set the minimum size and desired capacity of the Auto Scaling group to zero.
@discardableResult public func deleteAutoScalingGroup(_ input: DeleteAutoScalingGroupType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteAutoScalingGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the specified launch configuration. The launch configuration must not be attached to an Auto Scaling group. When this call completes, the launch configuration is no longer available for use.
@discardableResult public func deleteLaunchConfiguration(_ input: LaunchConfigurationNameType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteLaunchConfiguration", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the specified lifecycle hook. If there are any outstanding lifecycle actions, they are completed first (ABANDON for launching instances, CONTINUE for terminating instances).
public func deleteLifecycleHook(_ input: DeleteLifecycleHookType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteLifecycleHookAnswer> {
return self.client.execute(operation: "DeleteLifecycleHook", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the specified notification.
@discardableResult public func deleteNotificationConfiguration(_ input: DeleteNotificationConfigurationType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteNotificationConfiguration", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the specified scaling policy. Deleting either a step scaling policy or a simple scaling policy deletes the underlying alarm action, but does not delete the alarm, even if it no longer has an associated action. For more information, see Deleting a Scaling Policy in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func deletePolicy(_ input: DeletePolicyType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeletePolicy", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the specified scheduled action.
@discardableResult public func deleteScheduledAction(_ input: DeleteScheduledActionType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteScheduledAction", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the specified tags.
@discardableResult public func deleteTags(_ input: DeleteTagsType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteTags", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the current Amazon EC2 Auto Scaling resource quotas for your AWS account. For information about requesting an increase, see Amazon EC2 Auto Scaling Service Quotas in the Amazon EC2 Auto Scaling User Guide.
public func describeAccountLimits(logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeAccountLimitsAnswer> {
return self.client.execute(operation: "DescribeAccountLimits", path: "/", httpMethod: .POST, serviceConfig: self.config, logger: logger, on: eventLoop)
}
/// Describes the available adjustment types for Amazon EC2 Auto Scaling scaling policies. These settings apply to step scaling policies and simple scaling policies; they do not apply to target tracking scaling policies. The following adjustment types are supported: ChangeInCapacity ExactCapacity PercentChangeInCapacity
public func describeAdjustmentTypes(logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeAdjustmentTypesAnswer> {
return self.client.execute(operation: "DescribeAdjustmentTypes", path: "/", httpMethod: .POST, serviceConfig: self.config, logger: logger, on: eventLoop)
}
/// Describes one or more Auto Scaling groups.
public func describeAutoScalingGroups(_ input: AutoScalingGroupNamesType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AutoScalingGroupsType> {
return self.client.execute(operation: "DescribeAutoScalingGroups", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes one or more Auto Scaling instances.
public func describeAutoScalingInstances(_ input: DescribeAutoScalingInstancesType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AutoScalingInstancesType> {
return self.client.execute(operation: "DescribeAutoScalingInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the notification types that are supported by Amazon EC2 Auto Scaling.
public func describeAutoScalingNotificationTypes(logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeAutoScalingNotificationTypesAnswer> {
return self.client.execute(operation: "DescribeAutoScalingNotificationTypes", path: "/", httpMethod: .POST, serviceConfig: self.config, logger: logger, on: eventLoop)
}
/// Describes one or more instance refreshes. You can determine the status of a request by looking at the Status parameter. The following are the possible statuses: Pending - The request was created, but the operation has not started. InProgress - The operation is in progress. Successful - The operation completed successfully. Failed - The operation failed to complete. You can troubleshoot using the status reason and the scaling activities. Cancelling - An ongoing operation is being cancelled. Cancellation does not roll back any replacements that have already been completed, but it prevents new replacements from being started. Cancelled - The operation is cancelled. For more information, see Replacing Auto Scaling Instances Based on an Instance Refresh.
public func describeInstanceRefreshes(_ input: DescribeInstanceRefreshesType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeInstanceRefreshesAnswer> {
return self.client.execute(operation: "DescribeInstanceRefreshes", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes one or more launch configurations.
public func describeLaunchConfigurations(_ input: LaunchConfigurationNamesType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<LaunchConfigurationsType> {
return self.client.execute(operation: "DescribeLaunchConfigurations", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the available types of lifecycle hooks. The following hook types are supported: autoscaling:EC2_INSTANCE_LAUNCHING autoscaling:EC2_INSTANCE_TERMINATING
public func describeLifecycleHookTypes(logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeLifecycleHookTypesAnswer> {
return self.client.execute(operation: "DescribeLifecycleHookTypes", path: "/", httpMethod: .POST, serviceConfig: self.config, logger: logger, on: eventLoop)
}
/// Describes the lifecycle hooks for the specified Auto Scaling group.
public func describeLifecycleHooks(_ input: DescribeLifecycleHooksType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeLifecycleHooksAnswer> {
return self.client.execute(operation: "DescribeLifecycleHooks", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the target groups for the specified Auto Scaling group.
public func describeLoadBalancerTargetGroups(_ input: DescribeLoadBalancerTargetGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeLoadBalancerTargetGroupsResponse> {
return self.client.execute(operation: "DescribeLoadBalancerTargetGroups", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the load balancers for the specified Auto Scaling group. This operation describes only Classic Load Balancers. If you have Application Load Balancers or Network Load Balancers, use the DescribeLoadBalancerTargetGroups API instead.
public func describeLoadBalancers(_ input: DescribeLoadBalancersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeLoadBalancersResponse> {
return self.client.execute(operation: "DescribeLoadBalancers", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the available CloudWatch metrics for Amazon EC2 Auto Scaling. The GroupStandbyInstances metric is not returned by default. You must explicitly request this metric when calling the EnableMetricsCollection API.
public func describeMetricCollectionTypes(logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeMetricCollectionTypesAnswer> {
return self.client.execute(operation: "DescribeMetricCollectionTypes", path: "/", httpMethod: .POST, serviceConfig: self.config, logger: logger, on: eventLoop)
}
/// Describes the notification actions associated with the specified Auto Scaling group.
public func describeNotificationConfigurations(_ input: DescribeNotificationConfigurationsType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeNotificationConfigurationsAnswer> {
return self.client.execute(operation: "DescribeNotificationConfigurations", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the policies for the specified Auto Scaling group.
public func describePolicies(_ input: DescribePoliciesType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PoliciesType> {
return self.client.execute(operation: "DescribePolicies", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes one or more scaling activities for the specified Auto Scaling group.
public func describeScalingActivities(_ input: DescribeScalingActivitiesType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ActivitiesType> {
return self.client.execute(operation: "DescribeScalingActivities", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the scaling process types for use with the ResumeProcesses and SuspendProcesses APIs.
public func describeScalingProcessTypes(logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ProcessesType> {
return self.client.execute(operation: "DescribeScalingProcessTypes", path: "/", httpMethod: .POST, serviceConfig: self.config, logger: logger, on: eventLoop)
}
/// Describes the actions scheduled for your Auto Scaling group that haven't run or that have not reached their end time. To describe the actions that have already run, call the DescribeScalingActivities API.
public func describeScheduledActions(_ input: DescribeScheduledActionsType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ScheduledActionsType> {
return self.client.execute(operation: "DescribeScheduledActions", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the specified tags. You can use filters to limit the results. For example, you can query for the tags for a specific Auto Scaling group. You can specify multiple values for a filter. A tag must match at least one of the specified values for it to be included in the results. You can also specify multiple filters. The result includes information for a particular tag only if it matches all the filters. If there's no match, no special message is returned. For more information, see Tagging Auto Scaling Groups and Instances in the Amazon EC2 Auto Scaling User Guide.
public func describeTags(_ input: DescribeTagsType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<TagsType> {
return self.client.execute(operation: "DescribeTags", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the termination policies supported by Amazon EC2 Auto Scaling. For more information, see Controlling Which Auto Scaling Instances Terminate During Scale In in the Amazon EC2 Auto Scaling User Guide.
public func describeTerminationPolicyTypes(logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeTerminationPolicyTypesAnswer> {
return self.client.execute(operation: "DescribeTerminationPolicyTypes", path: "/", httpMethod: .POST, serviceConfig: self.config, logger: logger, on: eventLoop)
}
/// Removes one or more instances from the specified Auto Scaling group. After the instances are detached, you can manage them independent of the Auto Scaling group. If you do not specify the option to decrement the desired capacity, Amazon EC2 Auto Scaling launches instances to replace the ones that are detached. If there is a Classic Load Balancer attached to the Auto Scaling group, the instances are deregistered from the load balancer. If there are target groups attached to the Auto Scaling group, the instances are deregistered from the target groups. For more information, see Detach EC2 Instances from Your Auto Scaling Group in the Amazon EC2 Auto Scaling User Guide.
public func detachInstances(_ input: DetachInstancesQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DetachInstancesAnswer> {
return self.client.execute(operation: "DetachInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Detaches one or more target groups from the specified Auto Scaling group.
public func detachLoadBalancerTargetGroups(_ input: DetachLoadBalancerTargetGroupsType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DetachLoadBalancerTargetGroupsResultType> {
return self.client.execute(operation: "DetachLoadBalancerTargetGroups", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Detaches one or more Classic Load Balancers from the specified Auto Scaling group. This operation detaches only Classic Load Balancers. If you have Application Load Balancers or Network Load Balancers, use the DetachLoadBalancerTargetGroups API instead. When you detach a load balancer, it enters the Removing state while deregistering the instances in the group. When all instances are deregistered, then you can no longer describe the load balancer using the DescribeLoadBalancers API call. The instances remain running.
public func detachLoadBalancers(_ input: DetachLoadBalancersType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DetachLoadBalancersResultType> {
return self.client.execute(operation: "DetachLoadBalancers", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Disables group metrics for the specified Auto Scaling group.
@discardableResult public func disableMetricsCollection(_ input: DisableMetricsCollectionQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DisableMetricsCollection", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Enables group metrics for the specified Auto Scaling group. For more information, see Monitoring Your Auto Scaling Groups and Instances in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func enableMetricsCollection(_ input: EnableMetricsCollectionQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "EnableMetricsCollection", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Moves the specified instances into the standby state. If you choose to decrement the desired capacity of the Auto Scaling group, the instances can enter standby as long as the desired capacity of the Auto Scaling group after the instances are placed into standby is equal to or greater than the minimum capacity of the group. If you choose not to decrement the desired capacity of the Auto Scaling group, the Auto Scaling group launches new instances to replace the instances on standby. For more information, see Temporarily Removing Instances from Your Auto Scaling Group in the Amazon EC2 Auto Scaling User Guide.
public func enterStandby(_ input: EnterStandbyQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<EnterStandbyAnswer> {
return self.client.execute(operation: "EnterStandby", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Executes the specified policy. This can be useful for testing the design of your scaling policy.
@discardableResult public func executePolicy(_ input: ExecutePolicyType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "ExecutePolicy", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Moves the specified instances out of the standby state. After you put the instances back in service, the desired capacity is incremented. For more information, see Temporarily Removing Instances from Your Auto Scaling Group in the Amazon EC2 Auto Scaling User Guide.
public func exitStandby(_ input: ExitStandbyQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ExitStandbyAnswer> {
return self.client.execute(operation: "ExitStandby", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates or updates a lifecycle hook for the specified Auto Scaling group. A lifecycle hook tells Amazon EC2 Auto Scaling to perform an action on an instance when the instance launches (before it is put into service) or as the instance terminates (before it is fully terminated). This step is a part of the procedure for adding a lifecycle hook to an Auto Scaling group: (Optional) Create a Lambda function and a rule that allows CloudWatch Events to invoke your Lambda function when Amazon EC2 Auto Scaling launches or terminates instances. (Optional) Create a notification target and an IAM role. The target can be either an Amazon SQS queue or an Amazon SNS topic. The role allows Amazon EC2 Auto Scaling to publish lifecycle notifications to the target. Create the lifecycle hook. Specify whether the hook is used when the instances launch or terminate. If you need more time, record the lifecycle action heartbeat to keep the instance in a pending state using the RecordLifecycleActionHeartbeat API call. If you finish before the timeout period ends, complete the lifecycle action using the CompleteLifecycleAction API call. For more information, see Amazon EC2 Auto Scaling Lifecycle Hooks in the Amazon EC2 Auto Scaling User Guide. If you exceed your maximum limit of lifecycle hooks, which by default is 50 per Auto Scaling group, the call fails. You can view the lifecycle hooks for an Auto Scaling group using the DescribeLifecycleHooks API call. If you are no longer using a lifecycle hook, you can delete it by calling the DeleteLifecycleHook API.
public func putLifecycleHook(_ input: PutLifecycleHookType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PutLifecycleHookAnswer> {
return self.client.execute(operation: "PutLifecycleHook", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Configures an Auto Scaling group to send notifications when specified events take place. Subscribers to the specified topic can have messages delivered to an endpoint such as a web server or an email address. This configuration overwrites any existing configuration. For more information, see Getting Amazon SNS Notifications When Your Auto Scaling Group Scales in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func putNotificationConfiguration(_ input: PutNotificationConfigurationType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "PutNotificationConfiguration", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates or updates a scaling policy for an Auto Scaling group. For more information about using scaling policies to scale your Auto Scaling group, see Target Tracking Scaling Policies and Step and Simple Scaling Policies in the Amazon EC2 Auto Scaling User Guide.
public func putScalingPolicy(_ input: PutScalingPolicyType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PolicyARNType> {
return self.client.execute(operation: "PutScalingPolicy", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates or updates a scheduled scaling action for an Auto Scaling group. If you leave a parameter unspecified when updating a scheduled scaling action, the corresponding value remains unchanged. For more information, see Scheduled Scaling in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func putScheduledUpdateGroupAction(_ input: PutScheduledUpdateGroupActionType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "PutScheduledUpdateGroupAction", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Records a heartbeat for the lifecycle action associated with the specified token or instance. This extends the timeout by the length of time defined using the PutLifecycleHook API call. This step is a part of the procedure for adding a lifecycle hook to an Auto Scaling group: (Optional) Create a Lambda function and a rule that allows CloudWatch Events to invoke your Lambda function when Amazon EC2 Auto Scaling launches or terminates instances. (Optional) Create a notification target and an IAM role. The target can be either an Amazon SQS queue or an Amazon SNS topic. The role allows Amazon EC2 Auto Scaling to publish lifecycle notifications to the target. Create the lifecycle hook. Specify whether the hook is used when the instances launch or terminate. If you need more time, record the lifecycle action heartbeat to keep the instance in a pending state. If you finish before the timeout period ends, complete the lifecycle action. For more information, see Auto Scaling Lifecycle in the Amazon EC2 Auto Scaling User Guide.
public func recordLifecycleActionHeartbeat(_ input: RecordLifecycleActionHeartbeatType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<RecordLifecycleActionHeartbeatAnswer> {
return self.client.execute(operation: "RecordLifecycleActionHeartbeat", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Resumes the specified suspended automatic scaling processes, or all suspended process, for the specified Auto Scaling group. For more information, see Suspending and Resuming Scaling Processes in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func resumeProcesses(_ input: ScalingProcessQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "ResumeProcesses", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Sets the size of the specified Auto Scaling group. If a scale-in activity occurs as a result of a new DesiredCapacity value that is lower than the current size of the group, the Auto Scaling group uses its termination policy to determine which instances to terminate. For more information, see Manual Scaling in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func setDesiredCapacity(_ input: SetDesiredCapacityType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "SetDesiredCapacity", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Sets the health status of the specified instance. For more information, see Health Checks for Auto Scaling Instances in the Amazon EC2 Auto Scaling User Guide.
@discardableResult public func setInstanceHealth(_ input: SetInstanceHealthQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "SetInstanceHealth", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the instance protection settings of the specified instances. For more information about preventing instances that are part of an Auto Scaling group from terminating on scale in, see Instance Protection in the Amazon EC2 Auto Scaling User Guide.
public func setInstanceProtection(_ input: SetInstanceProtectionQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SetInstanceProtectionAnswer> {
return self.client.execute(operation: "SetInstanceProtection", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Starts a new instance refresh operation, which triggers a rolling replacement of all previously launched instances in the Auto Scaling group with a new group of instances. If successful, this call creates a new instance refresh request with a unique ID that you can use to track its progress. To query its status, call the DescribeInstanceRefreshes API. To describe the instance refreshes that have already run, call the DescribeInstanceRefreshes API. To cancel an instance refresh operation in progress, use the CancelInstanceRefresh API. For more information, see Replacing Auto Scaling Instances Based on an Instance Refresh.
public func startInstanceRefresh(_ input: StartInstanceRefreshType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartInstanceRefreshAnswer> {
return self.client.execute(operation: "StartInstanceRefresh", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Suspends the specified automatic scaling processes, or all processes, for the specified Auto Scaling group. If you suspend either the Launch or Terminate process types, it can prevent other process types from functioning properly. For more information, see Suspending and Resuming Scaling Processes in the Amazon EC2 Auto Scaling User Guide. To resume processes that have been suspended, call the ResumeProcesses API.
@discardableResult public func suspendProcesses(_ input: ScalingProcessQuery, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "SuspendProcesses", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Terminates the specified instance and optionally adjusts the desired group size. This call simply makes a termination request. The instance is not terminated immediately. When an instance is terminated, the instance status changes to terminated. You can't connect to or start an instance after you've terminated it. If you do not specify the option to decrement the desired capacity, Amazon EC2 Auto Scaling launches instances to replace the ones that are terminated. By default, Amazon EC2 Auto Scaling balances instances across all Availability Zones. If you decrement the desired capacity, your Auto Scaling group can become unbalanced between Availability Zones. Amazon EC2 Auto Scaling tries to rebalance the group, and rebalancing might terminate instances in other zones. For more information, see Rebalancing Activities in the Amazon EC2 Auto Scaling User Guide.
public func terminateInstanceInAutoScalingGroup(_ input: TerminateInstanceInAutoScalingGroupType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ActivityType> {
return self.client.execute(operation: "TerminateInstanceInAutoScalingGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates the configuration for the specified Auto Scaling group. To update an Auto Scaling group, specify the name of the group and the parameter that you want to change. Any parameters that you don't specify are not changed by this update request. The new settings take effect on any scaling activities after this call returns. If you associate a new launch configuration or template with an Auto Scaling group, all new instances will get the updated configuration. Existing instances continue to run with the configuration that they were originally launched with. When you update a group to specify a mixed instances policy instead of a launch configuration or template, existing instances may be replaced to match the new purchasing options that you specified in the policy. For example, if the group currently has 100% On-Demand capacity and the policy specifies 50% Spot capacity, this means that half of your instances will be gradually terminated and relaunched as Spot Instances. When replacing instances, Amazon EC2 Auto Scaling launches new instances before terminating the old ones, so that updating your group does not compromise the performance or availability of your application. Note the following about changing DesiredCapacity, MaxSize, or MinSize: If a scale-in activity occurs as a result of a new DesiredCapacity value that is lower than the current size of the group, the Auto Scaling group uses its termination policy to determine which instances to terminate. If you specify a new value for MinSize without specifying a value for DesiredCapacity, and the new MinSize is larger than the current size of the group, this sets the group's DesiredCapacity to the new MinSize value. If you specify a new value for MaxSize without specifying a value for DesiredCapacity, and the new MaxSize is smaller than the current size of the group, this sets the group's DesiredCapacity to the new MaxSize value. To see which parameters have been set, call the DescribeAutoScalingGroups API. To view the scaling policies for an Auto Scaling group, call the DescribePolicies API. If the group has scaling policies, you can update them by calling the PutScalingPolicy API.
@discardableResult public func updateAutoScalingGroup(_ input: UpdateAutoScalingGroupType, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "UpdateAutoScalingGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension AutoScaling {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: AutoScaling, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| apache-2.0 |
radex/swift-compiler-crashes | crashes-fuzzing/02690-swift-nominaltypedecl-computetype.swift | 11 | 233 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let:{if true{struct A{enum S{class a{class B<f where g:a{var d=c | mit |
BerekBR/gitCaronas | Caronas/TarifarioViewController.swift | 1 | 3081 | //
// TarifarioViewController.swift
// Caronas
//
// Created by Alexandre Wajcman on 03/10/16.
// Copyright © 2016 Alexandre Wajcman. All rights reserved.
//
import UIKit
class TarifarioViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
//MARK: - Outlets
@IBOutlet weak var tarifaPickerView: UIPickerView!
@IBOutlet weak var tarifaLabel: UILabel!
//MARK: - Properties
var arrayValor:[String] = []
var valor = ""
var pickerViewValue:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tarifaPickerView.dataSource = self
self.tarifaPickerView.delegate = self
//Construção do array com preços
for r in 1...10 {
for c in 0...9{
self.valor = "\(r).\(c)0"
self.arrayValor.append(valor)
}
}
//verificação que inicia o Pickerview com o último index selecionado
if FileManager.default.fileExists(atPath: tarifaArquivo){
let tarifaArray = (NSArray(contentsOfFile: tarifaArquivo) as! Array<String>)
tarifaFixa = (tarifaArray.last)!
self.tarifaLabel.text = "R$ " + tarifaFixa
}else {
self.tarifaLabel.text = "R$ 0.00"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Actions
@IBAction func definirTarifa(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
//MARK: - Métodos de PickerView DataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.arrayValor.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.arrayValor[row]
}
//MARK: - Métodos de PickerView Delegate
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
tarifaFixa = self.arrayValor[row]
self.pickerViewValue.append(tarifaFixa) //Rever implementaçao da tupla do pickerviewValue
// Persistencia do preço selecionado
(self.pickerViewValue as NSArray).write(toFile: tarifaArquivo, atomically: true)
self.tarifaLabel.text = "R$ " + tarifaFixa
print(self.pickerViewValue.last)
}
/*
// 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.
}
*/
}
| mit |
d-soto11/MaterialTB | MaterialTapBar/Helper/MaterialViewSegue.swift | 1 | 645 | //
// MaterialViewSegue.swift
// MaterialTapBar
//
// Created by Daniel Soto on 9/25/17.
// Copyright © 2017 Tres Astronautas. All rights reserved.
//
import UIKit
class MaterialViewSegue: UIStoryboardSegue {
override func perform() {
if let material = source as? MaterialTB, let vc = destination as? MaterialViewController, MaterialTB.tabBarLoaded, let index = Int(identifier!) {
material.addTapViewController(vc: vc, index: index-1)
} else {
print("Error setting view controller from segue. Please check that receiving view controller extends from MaterialViewController.")
}
}
}
| mit |
openhab/openhab.ios | openHABTestsSwift/OpenHABWatchTests.swift | 1 | 8507 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import XCTest
class OpenHABWatchTests: XCTestCase {
let jsonInput = """
{
"name": "watch",
"label": "Watch",
"link": "https://192.168.0.1:8080/rest/sitemaps/watch",
"homepage": {
"id": "watch",
"title": "Watch",
"link": "https://192.168.0.1:8080/rest/sitemaps/watch/watch",
"leaf": false,
"timeout": false,
"widgets": [
{
"widgetId": "00",
"type": "Switch",
"label": "Haustür",
"icon": "lock",
"mappings": [
],
"item": {
"link": "https://192.168.0.1:8080/rest/items/KeyMatic_Open",
"state": "OFF",
"stateDescription": {
"readOnly": false,
"options": [
]
},
"editable": false,
"type": "Switch",
"name": "KeyMatic_Open",
"label": "Haustuer",
"category": "lock",
"tags": [
],
"groupNames": [
]
},
"widgets": [
]
},
{
"widgetId": "01",
"type": "Switch",
"label": "Garagentor",
"icon": "garage",
"mappings": [
],
"item": {
"link": "https://192.168.0.1:8080/rest/items/Garagentor_Taster",
"state": "OFF",
"stateDescription": {
"readOnly": false,
"options": [
]
},
"editable": false,
"type": "Switch",
"name": "Garagentor_Taster",
"label": "Garagentor",
"category": "garage",
"tags": [
],
"groupNames": [
]
},
"widgets": [
]
},
{
"widgetId": "02",
"type": "Switch",
"label": "Garagentür [verriegelt]",
"icon": "lock",
"mappings": [
],
"item": {
"link": "https://192.168.0.1:8080/rest/items/KeyMatic_Garage_State",
"state": "OFF",
"transformedState": "verriegelt",
"stateDescription": {
"pattern": "",
"readOnly": false,
"options": [
]
},
"editable": false,
"type": "Switch",
"name": "KeyMatic_Garage_State",
"label": "Garagentuer entriegelt",
"category": "lock",
"tags": [
],
"groupNames": [
]
},
"widgets": [
]
},
{
"widgetId": "03",
"type": "Switch",
"label": "Küchenlicht",
"icon": "switch",
"mappings": [
],
"item": {
"link": "https://192.168.0.1:8080/rest/items/Licht_EG_Kueche",
"state": "OFF",
"stateDescription": {
"readOnly": false,
"options": [
]
},
"editable": false,
"type": "Switch",
"name": "Licht_EG_Kueche",
"label": "Kuechenlampe",
"tags": [
],
"groupNames": [
"gEG",
"Lichter",
"Simulation"
]
},
"widgets": [
]
},
{
"widgetId": "04",
"type": "Switch",
"label": "Bewässerung",
"icon": "switch",
"mappings": [
],
"item": {
"link": "https://192.168.0.1:8080/rest/items/HK_Bewaesserung",
"state": "OFF",
"editable": false,
"type": "Switch",
"name": "HK_Bewaesserung",
"label": "Bewaesserung",
"tags": [
"Lighting"
],
"groupNames": [
]
},
"widgets": [
]
},
{
"widgetId": "05",
"type": "Switch",
"label": "Pumpe",
"icon": "switch",
"mappings": [
],
"item": {
"link": "https://192.168.0.1:8080/rest/items/Pumpe_Garten",
"state": "OFF",
"stateDescription": {
"readOnly": false,
"options": [
]
},
"editable": false,
"type": "Switch",
"name": "Pumpe_Garten",
"label": "Pumpe",
"tags": [
],
"groupNames": [
"Garten"
]
},
"widgets": [
]
}
]
}
}
"""
let decoder = JSONDecoder()
override func setUp() {
super.setUp()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601Full)
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
// Pre-Decodable JSON parsing
func testSiteMapForWatchParsing() {
let data = Data(jsonInput.utf8)
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
guard let jsonDict: NSDictionary = json as? NSDictionary else {
XCTFail("Not able to parse")
return
}
let homepageDict = jsonDict.object(forKey: "homepage") as! NSDictionary
if homepageDict.isEmpty {
XCTFail("Not finding homepage")
return
}
let widgetsDict = homepageDict.object(forKey: "widgets") as! NSMutableArray
if widgetsDict.isEmpty {
XCTFail("widgets not found")
return
}
} catch {
XCTFail("Failed parsing")
}
}
// Parsing to [Item]
func testSiteMapForWatchParsingWithDecodable() {
var items: [Item] = []
let data = Data(jsonInput.utf8)
do {
let codingData = try decoder.decode(OpenHABSitemap.CodingData.self, from: data)
XCTAssert(codingData.label == "Watch", "OpenHABSitemap properly parsed")
XCTAssert(codingData.page.widgets?[0].type == "Switch", "widget properly parsed")
let widgets = try require(codingData.page.widgets)
items = widgets.compactMap { Item(with: $0.item) }
XCTAssert(items[0].name == "KeyMatic_Open", "Construction of items failed")
} catch {
XCTFail("Whoops, an error occured: \(error)")
}
}
// Decodable parsing to Frame
func testSiteMapForWatchParsingWithDecodabletoFrame() {
var frame: Frame
let data = Data(jsonInput.utf8)
do {
let codingData = try decoder.decode(OpenHABSitemap.CodingData.self, from: data)
frame = Frame(with: codingData)!
XCTAssert(frame.items[0].name == "KeyMatic_Open", "Parsing of Frame failed")
} catch {
XCTFail("Whoops, an error occured: \(error)")
}
}
// Decodable parsing to Sitemap
func testSiteMapForWatchParsingWithDecodabletoSitemap() {
let data = Data(jsonInput.utf8)
do {
let codingData = try decoder.decode(OpenHABSitemap.CodingData.self, from: data)
let sitemap = try require(Sitemap(with: codingData))
XCTAssert(sitemap.frames[0].items[0].name == "KeyMatic_Open", "Parsing of Frame failed")
} catch {
XCTFail("Whoops, an error occured: \(error)")
}
}
}
| epl-1.0 |
choefele/CCHDarwinNotificationCenter | CCHDarwinNotificationCenter Example/Today Widget/TodayViewController.swift | 1 | 2635 | //
// TodayViewController.swift
// Today Widget
//
// Created by Hoefele, Claus on 30.03.15.
// Copyright (c) 2015 Claus Höfele. All rights reserved.
//
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet private weak var colorSwatchView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// This turns Darwin notifications into standard NSNotifications
CCHDarwinNotificationCenter.startForwardingNotificationsWithIdentifier(NOTIFICATION_BLUE, fromEndpoints: .Default)
CCHDarwinNotificationCenter.startForwardingNotificationsWithIdentifier(NOTIFICATION_ORANGE, fromEndpoints: .Default)
CCHDarwinNotificationCenter.startForwardingNotificationsWithIdentifier(NOTIFICATION_RED, fromEndpoints: .Default)
// Observe standard NSNotifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: "colorDidChangeToBlue", name:NOTIFICATION_BLUE, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "colorDidChangeToOrange", name:NOTIFICATION_ORANGE, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "colorDidChangeToRed", name:NOTIFICATION_RED, object: nil)
}
deinit {
CCHDarwinNotificationCenter.stopForwardingNotificationsWithIdentifier(NOTIFICATION_BLUE, fromEndpoints: .Default)
CCHDarwinNotificationCenter.stopForwardingNotificationsWithIdentifier(NOTIFICATION_ORANGE, fromEndpoints: .Default)
CCHDarwinNotificationCenter.stopForwardingNotificationsWithIdentifier(NOTIFICATION_RED, fromEndpoints: .Default)
}
@IBAction func changeColorToBlue() {
colorSwatchView.backgroundColor = UIColor.blueColor()
CCHDarwinNotificationCenter.postNotificationWithIdentifier(NOTIFICATION_BLUE)
}
@IBAction func changeColorToOrange() {
colorSwatchView.backgroundColor = UIColor.orangeColor()
CCHDarwinNotificationCenter.postNotificationWithIdentifier(NOTIFICATION_ORANGE)
}
@IBAction func changeColorToRed() {
colorSwatchView.backgroundColor = UIColor.redColor()
CCHDarwinNotificationCenter.postNotificationWithIdentifier(NOTIFICATION_RED)
}
func colorDidChangeToBlue() {
colorSwatchView.backgroundColor = UIColor.blueColor()
}
func colorDidChangeToOrange() {
colorSwatchView.backgroundColor = UIColor.orangeColor()
}
func colorDidChangeToRed() {
colorSwatchView.backgroundColor = UIColor.redColor()
}
}
| mit |
StephenVinouze/ios-charts | ChartsDemo/Classes/Extensions/ChartUtils.swift | 1 | 6382 | //
// File.swift
// ChartsDemo
//
// Created by VINOUZE Stephen on 31/03/2016.
// Copyright © 2016 dcg. All rights reserved.
//
import Foundation
import Charts
public extension BarLineChartViewBase {
@objc
public enum ChartMode : Int {
case Display
case Export
}
@objc
public enum ChartType : Int {
case Pain
case Accumulation
}
func configureWithMode(mode: ChartMode, andType type: ChartType) {
self.descriptionText = ""
self.pinchZoomEnabled = false
self.scaleXEnabled = true
self.scaleYEnabled = false
self.drawGridBackgroundEnabled = false
self.doubleTapToZoomEnabled = false
self.drawBordersEnabled = false
self.backgroundColor = UIColor(colorLiteralRed: 0.2, green: 0.2, blue: 0.2, alpha: 1)
if let barChartView = self as? BarChartView {
barChartView.drawBarShadowEnabled = false
barChartView.drawValueAboveBarEnabled = false
}
configureLegend(self.legend, withMode: mode)
configureXAxis(self.xAxis, withMode: mode)
switch type {
case .Pain:
configureYAxis(self.leftAxis, withMode: mode, andType: type, maxValue: 10)
configureYAxis(self.rightAxis, withMode: mode, andType: type, maxValue: 21)
case .Accumulation:
configureYAxis(self.leftAxis, withMode: mode, andType: type, maxValue: 100)
}
}
func configureLegend(legend: ChartLegend, withMode mode: ChartMode) {
//legend.enabled = mode == .Export
legend.position = .AboveChartRight
legend.form = .Square
legend.xEntrySpace = 10
legend.font = configureFont()
legend.textColor = configureTextColor(mode)
}
func configureXAxis(xAxis: ChartXAxis, withMode mode: ChartMode) {
xAxis.labelPosition = .Bottom
xAxis.drawGridLinesEnabled = false
xAxis.drawAxisLineEnabled = false
xAxis.labelFont = configureFont()
xAxis.labelTextColor = configureTextColor(mode)
if mode == .Export {
xAxis.setLabelsToSkip(0)
}
if let dotXAxis = xAxis as? ChartDotXAxis {
dotXAxis.dotSize = 15
dotXAxis.dotOffset = 5
dotXAxis.dotStrokeSize = 2
dotXAxis.dotStrokeColor = self.backgroundColor!
}
}
func configureYAxis(yAxis: ChartYAxis, withMode mode: ChartMode, andType type: ChartType, maxValue: Double) {
let axisDependency = yAxis.axisDependency
yAxis.valueFormatter = NSNumberFormatter()
yAxis.axisMinimum = 0
yAxis.axisMaximum = maxValue
yAxis.drawGridLinesEnabled = axisDependency == .Left
yAxis.drawAxisLineEnabled = false
yAxis.labelFont = configureFont()
yAxis.labelTextColor = axisDependency == .Left ? configureTextColor(mode) : UIColor.redColor()
if type == .Pain && axisDependency == .Left {
yAxis.labelCount = Int(maxValue)
}
}
func configureFont() -> UIFont {
return UIFont(name: "HelveticaNeue-Light", size: 12)!
}
func configureTextColor(chartMode: ChartMode) -> UIColor {
switch chartMode {
case .Display:
return UIColor.whiteColor()
case .Export:
return UIColor.blackColor()
}
}
func barUnitValue() -> Float {
if let barChartView = self as? BarChartView {
if let barData = barChartView.barData {
return Float(barData.dataSetCount) + Float(barData.groupSpace)
}
}
return 1;
}
func generateBarChartData(xValues: [String], dotColorSets: [[UIColor]]?, wearinessEntries: [BarChartDataEntry], painEntries: [BarChartDataEntry], painScoreEntries: [BarChartDataEntry]) -> BarChartData {
let wearinessSet = BarChartDataSet(yVals: wearinessEntries, label: "Fatigue")
wearinessSet.setColor(UIColor(colorLiteralRed: 104/255, green: 241/255, blue: 175/255, alpha: 1))
wearinessSet.axisDependency = .Left
wearinessSet.highlightAlpha = 0
let painSet = BarChartDataSet(yVals: painEntries, label: "Douleur")
painSet.setColor(UIColor(colorLiteralRed: 164/255, green: 228/255, blue: 251/255, alpha: 1))
painSet.axisDependency = .Left
painSet.highlightAlpha = 0
let painScoreSet = BarChartDataSet(yVals: painScoreEntries, label: "Total score")
painScoreSet.setColor(UIColor(colorLiteralRed: 242/255, green: 247/255, blue: 158/255, alpha: 1))
painScoreSet.axisDependency = .Right
painScoreSet.highlightAlpha = 0
let data = DotBarChartData(xVals: xValues, dotColorSets: dotColorSets, dataSets: [wearinessSet, painSet, painScoreSet])
data.groupSpace = 2
data.setDrawValues(false)
return data
}
func generateLineChartData(xValues: [String], wearinessEntries: [ChartDataEntry], painEntries: [ChartDataEntry], painScoreEntries: [ChartDataEntry]) -> LineChartData {
let wearinessSet = LineChartDataSet(yVals: wearinessEntries, label: "Fatigue")
wearinessSet.setColor(UIColor(colorLiteralRed: 104/255, green: 241/255, blue: 175/255, alpha: 1))
wearinessSet.axisDependency = .Left
wearinessSet.drawCirclesEnabled = false
wearinessSet.setDrawHighlightIndicators(false)
let painSet = LineChartDataSet(yVals: painEntries, label: "Douleur")
painSet.setColor(UIColor(colorLiteralRed: 164/255, green: 228/255, blue: 251/255, alpha: 1))
painSet.axisDependency = .Left
painSet.drawCirclesEnabled = false
painSet.setDrawHighlightIndicators(false)
let painScoreSet = LineChartDataSet(yVals: painScoreEntries, label: "Total score")
painScoreSet.setColor(UIColor(colorLiteralRed: 242/255, green: 247/255, blue: 158/255, alpha: 1))
painScoreSet.axisDependency = .Right
painScoreSet.drawCirclesEnabled = false
painScoreSet.setDrawHighlightIndicators(false)
let data = LineChartData(xVals: xValues, dataSets: [wearinessSet, painSet, painScoreSet])
data.setDrawValues(false)
return data
}
}
| apache-2.0 |
wordpress-mobile/WordPress-iOS | WordPress/UITestsFoundation/Screens/Login/WelcomeScreen.swift | 1 | 1137 | import ScreenObject
import XCTest
// TODO: remove when unifiedAuth is permanent.
public class WelcomeScreen: ScreenObject {
private let logInButtonGetter: (XCUIApplication) -> XCUIElement = {
$0.buttons["Prologue Log In Button"]
}
private let signupButtonGetter: (XCUIApplication) -> XCUIElement = {
$0.buttons["Prologue Signup Button"]
}
var signupButton: XCUIElement { signupButtonGetter(app) }
var logInButton: XCUIElement { logInButtonGetter(app) }
public init(app: XCUIApplication = XCUIApplication()) throws {
try super.init(
expectedElementGetters: [logInButtonGetter, signupButtonGetter],
app: app,
waitTimeout: 7
)
}
public func selectSignup() throws -> WelcomeScreenSignupComponent {
signupButton.tap()
return try WelcomeScreenSignupComponent()
}
public func selectLogin() throws -> WelcomeScreenLoginComponent {
logInButton.tap()
return try WelcomeScreenLoginComponent()
}
static func isLoaded() -> Bool {
(try? WelcomeScreen().isLoaded) ?? false
}
}
| gpl-2.0 |
pabloroca/PR2StudioSwift | Source/Result.swift | 1 | 8274 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 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 value that represents either a success or a failure, including an
/// associated value in each case.
public enum Result<Success, Failure: Error> {
/// A success, storing a `Success` value.
case success(Success)
/// A failure, storing a `Failure` value.
case failure(Failure)
/// Initialiser for value.
public init(_ value: Success) {
self = .success(value)
}
/// Initialiser for error.
public init(_ error: Failure) {
self = .failure(error)
}
/// Returns a new result, mapping any success value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a success. The following example transforms
/// the integer success value of a result into a string:
///
/// func getNextInteger() -> Result<Int, Error> { /* ... */ }
///
/// let integerResult = getNextInteger()
/// // integerResult == .success(5)
/// let stringResult = integerResult.map({ String($0) })
/// // stringResult == .success("5")
///
/// - Parameter transform: A closure that takes the success value of this
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new success value if this instance represents a success.
public func map<NewSuccess>(
_ transform: (Success) -> NewSuccess
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return .success(transform(success))
case let .failure(failure):
return .failure(failure)
}
}
/// Returns a new result, mapping any failure value using the given
/// transformation.
///
/// Use this method when you need to transform the value of a `Result`
/// instance when it represents a failure. The following example transforms
/// the error value of a result by wrapping it in a custom `Error` type:
///
/// struct DatedError: Error {
/// var error: Error
/// var date: Date
///
/// init(_ error: Error) {
/// self.error = error
/// self.date = Date()
/// }
/// }
///
/// let result: Result<Int, Error> = // ...
/// // result == .failure(<error value>)
/// let resultWithDatedError = result.mapError({ e in DatedError(e) })
/// // result == .failure(DatedError(error: <error value>, date: <date>))
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new failure value if this instance represents a failure.
public func mapError<NewFailure>(
_ transform: (Failure) -> NewFailure
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return .failure(transform(failure))
}
}
/// Returns a new result, mapping any success value using the given
/// transformation and unwrapping the produced result.
///
/// - Parameter transform: A closure that takes the success value of the
/// instance.
/// - Returns: A `Result` instance with the result of evaluating `transform`
/// as the new failure value if this instance represents a failure.
public func flatMap<NewSuccess>(
_ transform: (Success) -> Result<NewSuccess, Failure>
) -> Result<NewSuccess, Failure> {
switch self {
case let .success(success):
return transform(success)
case let .failure(failure):
return .failure(failure)
}
}
/// Returns a new result, mapping any failure value using the given
/// transformation and unwrapping the produced result.
///
/// - Parameter transform: A closure that takes the failure value of the
/// instance.
/// - Returns: A `Result` instance, either from the closure or the previous
/// `.success`.
public func flatMapError<NewFailure>(
_ transform: (Failure) -> Result<Success, NewFailure>
) -> Result<Success, NewFailure> {
switch self {
case let .success(success):
return .success(success)
case let .failure(failure):
return transform(failure)
}
}
/// Returns the success value as a throwing expression.
///
/// Use this method to retrieve the value of this result if it represents a
/// success, or to catch the value if it represents a failure.
///
/// let integerResult: Result<Int, Error> = .success(5)
/// do {
/// let value = try integerResult.get()
/// print("The value is \(value).")
/// } catch error {
/// print("Error retrieving the value: \(error)")
/// }
/// // Prints "The value is 5."
///
/// - Returns: The success value, if the instance represents a success.
/// - Throws: The failure value, if the instance represents a failure.
public func get() throws -> Success {
switch self {
case let .success(success):
return success
case let .failure(failure):
throw failure
}
}
}
public struct AnyError: Error, CustomStringConvertible {
/// The underlying error.
public let underlyingError: Error
public init(_ error: Error) {
// If we already have any error, don't nest it.
if case let error as AnyError = error {
self = error
} else {
self.underlyingError = error
}
}
public var description: String {
return String(describing: underlyingError)
}
}
extension Result: Equatable where Success: Equatable, Failure: Equatable { }
extension Result: Hashable where Success: Hashable, Failure: Hashable { }
extension Result: CustomStringConvertible {
public var description: String {
switch self {
case .success(let value):
return "Result(\(value))"
case .failure(let error):
return "Result(\(error))"
}
}
}
extension Result: Codable where Success: Codable, Failure: Codable {
private enum CodingKeys: String, CodingKey {
case success, failure
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .success(let value):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .success)
try unkeyedContainer.encode(value)
case .failure(let error):
var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .failure)
try unkeyedContainer.encode(error)
}
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
guard let key = values.allKeys.first(where: values.contains) else {
throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key"))
}
switch key {
case .success:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let value = try unkeyedValues.decode(Success.self)
self = .success(value)
case .failure:
var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
let error = try unkeyedValues.decode(Failure.self)
self = .failure(error)
}
}
}
| mit |
mlgoogle/viossvc | viossvc/Scenes/ServantPersonalVC.swift | 1 | 16987 | //
// ServantPersonalVC.swift
// HappyTravel
//
// Created by 陈奕涛 on 16/8/4.
// Copyright © 2016年 陈奕涛. All rights reserved.
//
import Foundation
import UIKit
import MJRefresh
import SVProgressHUD
public class ServantPersonalVC : UIViewController,UITableViewDelegate,UITableViewDataSource,ServantPersonalCellDelegate,SendMsgViewDelegate ,GuideViewDelegate {
// MARK: - 属性
var personalInfo:UserInfoModel?
// 自定义导航条、左右按钮和title
var topView:UIView?
var leftBtn:UIButton?
var rightBtn:UIButton?
var topTitle:UILabel?
var tableView:UITableView?
let header:MJRefreshStateHeader = MJRefreshStateHeader()
let footer:MJRefreshAutoStateFooter = MJRefreshAutoStateFooter()
// 头视图
var headerView:ServantHeaderView?
// 是否关注状态
var follow = false
var fansCount = 0
var pageNum:Int = 0
var dataArray = [servantDynamicModel]()
var timer:NSTimer? // 刷新用
var offsetY:CGFloat = 0.0
// MARK: - 函数方法
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if offsetY < 0 {
UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true)
}
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
UIApplication.sharedApplication().setStatusBarStyle(.Default, animated: false)
}
override public func viewDidLoad() {
super.viewDidLoad()
let userDefaults = NSUserDefaults.standardUserDefaults()
if userDefaults.floatForKey("guideVersion") < ((NSBundle.mainBundle().infoDictionary! ["CFBundleShortVersionString"])?.floatValue) {
loadGuide()
} else {
initViews()
}
//接收通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateImageAndName), name: "updateImageAndName", object: nil)
}
//移除通知
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
//通知实现
func updateImageAndName(notification: NSNotification?) {
headerView?.didUpdateUI(CurrentUserHelper.shared.userInfo.head_url!, name: CurrentUserHelper.shared.userInfo.nickname!, star: CurrentUserHelper.shared.userInfo.praise_lv)
}
func loadGuide() {
let guidView:GuidView = GuidView.init(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight))
guidView.delegate = self
UIApplication.sharedApplication().keyWindow?.addSubview(guidView)
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setFloat(((NSBundle.mainBundle().infoDictionary! ["CFBundleShortVersionString"])?.floatValue)!, forKey: "guideVersion")
}
func initViews() {
personalInfo = CurrentUserHelper.shared.userInfo
addViews()
header.performSelector(#selector(MJRefreshHeader.beginRefreshing), withObject: nil, afterDelay: 0.5)
let userDefaults = NSUserDefaults.standardUserDefaults()
let key = "isShownFiestTime1"
let isshownfirsttime = userDefaults.valueForKey(key)
if isshownfirsttime == nil {
let imageView:UIImageView = UIImageView.init(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight))
imageView.image = UIImage.init(named: "助理端新手引导1")
imageView.alpha = 0.5
UIApplication.sharedApplication().keyWindow?.addSubview(imageView)
imageView.userInteractionEnabled = true
let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.imageTapAction(_:)))
imageView.addGestureRecognizer(tap)
userDefaults.setValue(true, forKey: key)
}
}
// 加载页面
func addViews() {
tableView = UITableView.init(frame: CGRectMake(0, -20, ScreenWidth, ScreenHeight + 20), style: .Grouped)
tableView?.backgroundColor = UIColor.init(decR: 242, decG: 242, decB: 242, a: 1)
tableView?.autoresizingMask = [.FlexibleWidth,.FlexibleHeight]
tableView?.delegate = self
tableView?.dataSource = self
tableView?.separatorStyle = .None
tableView?.estimatedRowHeight = 120
tableView?.rowHeight = UITableViewAutomaticDimension
tableView?.separatorStyle = .None
tableView?.showsVerticalScrollIndicator = false
tableView?.showsHorizontalScrollIndicator = false
// 只有一条文字的Cell展示
tableView?.registerClass(ServantOneLabelCell.self, forCellReuseIdentifier: "ServantOneLabelCell")
// 只有一张图片的Cell展示
tableView?.registerClass(ServantOnePicCell.self, forCellReuseIdentifier: "ServantOnePicCell")
// 复合Cell展示
tableView?.registerClass(ServantPicAndLabelCell.self, forCellReuseIdentifier: "ServantPicAndLabelCell")
view.addSubview(tableView!)
header.setRefreshingTarget(self, refreshingAction: #selector(ServantPersonalVC.headerRefresh))
footer.setRefreshingTarget(self, refreshingAction: #selector(ServantPersonalVC.footerRefresh))
tableView?.mj_header = header
tableView?.mj_footer = footer
// 设置顶部 topView
topView = UIView.init(frame: CGRectMake(0, 0, ScreenWidth, 64))
topView?.backgroundColor = UIColor.clearColor()
view.addSubview(topView!)
leftBtn = UIButton.init(frame: CGRectMake(15, 27, 30, 30))
leftBtn!.layer.masksToBounds = true
leftBtn!.layer.cornerRadius = 15.0
leftBtn!.setImage(UIImage.init(named: "message-1"), forState: .Normal)
topView?.addSubview(leftBtn!)
leftBtn!.addTarget(self, action: #selector(ServantPersonalVC.backAction), forControlEvents: .TouchUpInside)
rightBtn = UIButton.init(frame: CGRectMake(ScreenWidth - 45, 27, 30, 30))
rightBtn!.layer.masksToBounds = true
rightBtn!.layer.cornerRadius = 15.0
rightBtn!.setImage(UIImage.init(named: "sendDynamic-1"), forState: .Normal)
topView?.addSubview(rightBtn!)
rightBtn!.addTarget(self, action: #selector(ServantPersonalVC.reportAction), forControlEvents: .TouchUpInside)
topTitle = UILabel.init(frame: CGRectMake((leftBtn?.Right)! + 10 , (leftBtn?.Top)!, (rightBtn?.Left)! - leftBtn!.Right - 20, (leftBtn?.Height)!))
topView?.addSubview(topTitle!)
topTitle?.font = UIFont.systemFontOfSize(17)
topTitle?.textAlignment = .Center
topTitle?.textColor = UIColor.init(decR: 51, decG: 51, decB: 51, a: 1)
}
func backAction() {
let vc = MyInformationVC()
vc.title = "我的消息"
vc.hidesBottomBarWhenPushed = true
navigationController?.setNavigationBarHidden(false, animated: false)
navigationController?.pushViewController(vc, animated: true)
}
func reportAction() {
let sendMsgView:SendMsgViewController = SendMsgViewController()
sendMsgView.hidesBottomBarWhenPushed = true
sendMsgView.delegate = self
navigationController?.pushViewController(sendMsgView, animated: true)
}
// MARK: - UITableViewDelegate
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row < dataArray.count {
let model:servantDynamicModel = dataArray[indexPath.row]
let detailText:String = model.dynamic_text!
let urlStr = model.dynamic_url
let urlArray = urlStr!.componentsSeparatedByString(",")
if urlStr?.characters.count == 0 {
// 只有文字的Cell
let cell = tableView.dequeueReusableCellWithIdentifier("ServantOneLabelCell", forIndexPath: indexPath) as! ServantOneLabelCell
cell.delegate = self
cell.selectionStyle = .None
cell.updateLabelText(model)
return cell
} else if detailText.characters.count == 0 && urlArray.count == 1 {
// 只有一张图片的cell
let cell = tableView.dequeueReusableCellWithIdentifier("ServantOnePicCell", forIndexPath: indexPath) as! ServantOnePicCell
cell.delegate = self
cell.selectionStyle = .None
cell.updateImage(model)
return cell
} else {
// 复合cell
let cell = tableView.dequeueReusableCellWithIdentifier("ServantPicAndLabelCell", forIndexPath: indexPath) as! ServantPicAndLabelCell
cell.delegate = self
cell.selectionStyle = .None
cell.updateUI(model)
return cell
}
}
return UITableViewCell.init()
}
public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
headerView = ServantHeaderView.init(frame: CGRectMake(0, 0, ScreenWidth, 379))
headerView?.didUpdateUI(CurrentUserHelper.shared.userInfo.head_url!, name: CurrentUserHelper.shared.userInfo.nickname!, star: CurrentUserHelper.shared.userInfo.praise_lv)
headerView?.updateFansCount(self.fansCount)
return headerView
}
public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 316
}
public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.1
}
// 滑动的时候改变顶部 topView
public func scrollViewDidScroll(scrollView: UIScrollView) {
let color:UIColor = UIColor.whiteColor()
offsetY = scrollView.contentOffset.y
if offsetY < 0 {
UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true)
topView?.backgroundColor = color.colorWithAlphaComponent(0)
topTitle?.text = ""
leftBtn?.setImage(UIImage.init(named: "message-1"), forState:.Normal)
rightBtn?.setImage(UIImage.init(named: "sendDynamic-1"), forState: .Normal)
} else {
UIApplication.sharedApplication().setStatusBarStyle(.Default, animated: true)
let alpha:CGFloat = 1 - ((128 - offsetY) / 128)
topView?.backgroundColor = color.colorWithAlphaComponent(alpha)
let titleString = "首页"
topTitle?.text = titleString
leftBtn?.setImage(UIImage.init(named: "message-2"), forState:.Normal)
rightBtn?.setImage(UIImage.init(named: "sendDynamic-2"), forState: .Normal)
}
}
// MARK: 数据
// 刷新数据
func headerRefresh() {
footer.state = .Idle
pageNum = 0
let servantInfo:ServantInfoModel = ServantInfoModel()
servantInfo.page_num = pageNum
AppAPIHelper.userAPI().requestDynamicList(servantInfo, complete: { (response) in
if let models = response as? [servantDynamicModel] {
self.dataArray = models
self.endRefresh()
}
if self.dataArray.count < 10 {
self.noMoreData()
}
// 查询粉丝数
self.updateFollowCount()
}, error: { [weak self](error) in
self?.endRefresh()
})
timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(endRefresh), userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)
}
// 加载数据
func footerRefresh() {
pageNum += 1
let servantInfo:ServantInfoModel = ServantInfoModel()
servantInfo.page_num = pageNum
AppAPIHelper.userAPI().requestDynamicList(servantInfo, complete: { (response) in
let models = response as! [servantDynamicModel]
self.dataArray += models
self.endRefresh()
if models.count == 0 {
self.noMoreData()
}
}, error: { [weak self](error) in
self?.endRefresh()
})
timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(endRefresh), userInfo: nil, repeats: false)
NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSRunLoopCommonModes)
}
// 停止刷新
func endRefresh() {
if header.state == .Refreshing {
header.endRefreshing()
}
if footer.state == .Refreshing {
footer.endRefreshing()
}
if timer != nil {
timer?.invalidate()
timer = nil
}
tableView!.reloadData()
}
func noMoreData() {
endRefresh()
footer.state = .NoMoreData
if dataArray.count == 0 {
footer.setTitle("您还未发布任何动态,快去发布吧", forState: .NoMoreData)
} else {
footer.setTitle("暂无更多动态", forState: .NoMoreData)
}
}
// 查询粉丝数量
func updateFollowCount() {
let req = FollowCountRequestModel()
req.uid = CurrentUserHelper.shared.uid
req.type = 2
AppAPIHelper.userAPI().followCount(req, complete: { (response) in
if let model = response as? FollowCountModel {
self.headerView?.updateFansCount(model.follow_count)
}
}, error: nil)
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// 点赞
func servantIsLikedAction(sender: UIButton, model: servantDynamicModel) {
let req = ServantThumbUpModel()
req.dynamic_id = model.dynamic_id
AppAPIHelper.userAPI().servantThumbup(req, complete: { (response) in
let result = response as! ServantThumbUpResultModel
let likecount = result.dynamic_like_count
if result.result == 0 {
sender.selected = true
sender.setTitle(String(likecount), forState: .Selected)
model.is_liked = 1
}else if result.result == 1 {
sender.selected = false
sender.setTitle(String(likecount), forState: .Normal)
model.is_liked = 0
}
model.dynamic_like_count = likecount
}, error: nil)
}
// 图片点击放大
func servantImageDidClicked(model: servantDynamicModel, index: Int) {
// 解析图片链接
let urlString:String = model.dynamic_url!
let imageUrls:NSArray = urlString.componentsSeparatedByString(",")
// 显示图片
PhotoBroswerVC.show(self, type: PhotoBroswerVCTypePush , index: UInt(index)) {() -> [AnyObject]! in
let photoArray:NSMutableArray = NSMutableArray()
let count:Int = imageUrls.count
for i in 0..<count {
let model: PhotoModel = PhotoModel.init()
model.mid = UInt(i) + 1
model.image_HD_U = imageUrls.objectAtIndex(i) as! String
photoArray.addObject(model)
}
return photoArray as [AnyObject]
}
}
// 刷新界面
func sendMsgViewDidSendMessage() {
header.performSelector(#selector(MJRefreshHeader.beginRefreshing), withObject: nil, afterDelay: 0.5)
}
// 新手引导图片点击
func imageTapAction(tap:UITapGestureRecognizer) {
let imageView:UIImageView = tap.view as! UIImageView
imageView.removeFromSuperview()
let userDefaults = NSUserDefaults.standardUserDefaults()
let key = "isShownFiestTime1"
userDefaults.setValue(true, forKey: key)
}
// 启动页消失
func guideDidDismissed() {
initViews()
}
}
| apache-2.0 |
HuangJinyong/iOSDEV | 使用UIScrollView创建可滚动的内容/使用UIScrollView创建可滚动的内容Tests/__UIScrollView________Tests.swift | 1 | 1047 | //
// __UIScrollView________Tests.swift
// 使用UIScrollView创建可滚动的内容Tests
//
// Created by Jinyong on 2016/10/16.
// Copyright © 2016年 Jinyong. All rights reserved.
//
import XCTest
@testable import __UIScrollView________
class __UIScrollView________Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
samodom/TestSwagger | TestSwagger/Spying/Spyable.swift | 1 | 481 | //
// Spyable.swift
// TestSwagger
//
// Created by Sam Odom on 12/11/16.
// Copyright © 2016 Swagger Soft. All rights reserved.
//
import FoundationSwagger
/// A protocol for classes with instance methods and/or properties upon which one would like to spy.
public protocol ObjectSpyable: class, AssociatingObject {}
/// A protocol for classes with class methods and/or properties upon which one would like to spy.
public protocol ClassSpyable: class, AssociatingClass {}
| mit |
kobe41999/transea-mumble | Source/Classes/NCCU/UserVC/NUserVC.swift | 1 | 3925 | //
// UserVC.swift
// Mumble
//
// Created by 賴昱榮 on 2017/4/24.
//
//
import Foundation
import UIKit
class UserVC: UIViewController {
@IBOutlet var imgHead: UIImageView!
@IBOutlet var labelName: UILabel!
@IBOutlet var switchAvailable: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let currentUser = PFUser.current()
let userID: String = currentUser!.username!
print("userid=\(userID)")
if (currentUser != nil) {
let array: [Any] = userID.components(separatedBy: "@")
labelName.text = array[0] as! String
}
}
@IBAction func testBid(_ sender: Any) {
let serverURL: String = "http://162.243.49.105:8888/bid"
let currentUser = PFUser.current()
let userID: String = currentUser!.username!
print("userid=\(userID)")
if !(currentUser != nil) {
return
}
var resultsDictionary: [AnyHashable: Any]
// 返回的 JSON 数据
let starter: String = "starter"
let bid = Int(20)
let userData: [AnyHashable: Any] = [
"userid" : userID,
"starter" : starter,
"bid" : bid
]
let mainJson: [AnyHashable: Any] = [
"data" : userData,
"type" : "bid"
]
var error: Error?
let jsonData: Data? = try? JSONSerialization.data(withJSONObject: mainJson, options: JSONSerialization.WritingOptions.prettyPrinted)
let post = String(data: jsonData!, encoding: String.Encoding.utf8)
print("\(post)")
//NSString *queryString = [NSString stringWithFormat:@"http://example.com/username.php?name=%@", [self.txtName text]];
var theRequest = NSMutableURLRequest(url: URL(string: serverURL)!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 60.0)
theRequest.httpMethod = "POST"
theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
// should check for and handle errors here but we aren't
theRequest.httpBody = jsonData
NSURLConnection.sendAsynchronousRequest(theRequest as URLRequest, queue: OperationQueue.main, completionHandler: {(_ response: URLResponse, _ data: Data, _ error: Error?) -> Void in
if error != nil {
//do something with error
print("\(error?.localizedDescription)")
}
else {
var responseText = String(describing:(data, encoding: String.Encoding.ascii))
print("Response: \(responseText)")
let newLineStr: String = "\n"
responseText = responseText.replacingOccurrences(of: "<br />", with: newLineStr)
}
} as! (URLResponse?, Data?, Error?) -> Void)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSwitch(_ sender: Any) {
let currentUser = PFUser.current()
if switchAvailable.isOn {
print("ON")
currentUser?["AVAILABLE"] = Int(true)
}
else {
print("OFF")
currentUser?["AVAILABLE"] = Int(false)
}
currentUser?.saveInBackground(block: {(_ succeeded: Bool, _ error: Error?) -> Void in
})
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
deinit {
}
}
import ParseFacebookUtilsV4
| bsd-3-clause |
apple/swift-nio | Tests/NIOConcurrencyHelpersTests/NIOConcurrencyHelpersTests.swift | 1 | 36446 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#else
import Glibc
#endif
import Dispatch
import XCTest
import NIOCore
@testable import NIOConcurrencyHelpers
class NIOConcurrencyHelpersTests: XCTestCase {
private func sumOfIntegers(until n: UInt64) -> UInt64 {
return n*(n+1)/2
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testLargeContendedAtomicSum() {
let noAsyncs: UInt64 = 50
let noCounts: UInt64 = 2_000
let q = DispatchQueue(label: "q", attributes: .concurrent)
let g = DispatchGroup()
let ai = NIOConcurrencyHelpers.Atomic<UInt64>(value: 0)
let everybodyHere = DispatchSemaphore(value: 0)
let go = DispatchSemaphore(value: 0)
for thread in 1...noAsyncs {
q.async(group: g) {
everybodyHere.signal()
go.wait()
for _ in 0..<noCounts {
ai.add(thread)
}
}
}
for _ in 0..<noAsyncs {
everybodyHere.wait()
}
for _ in 0..<noAsyncs {
go.signal()
}
g.wait()
XCTAssertEqual(sumOfIntegers(until: noAsyncs) * noCounts, ai.load())
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testCompareAndExchangeBool() {
let ab = Atomic<Bool>(value: true)
XCTAssertFalse(ab.compareAndExchange(expected: false, desired: false))
XCTAssertTrue(ab.compareAndExchange(expected: true, desired: true))
XCTAssertFalse(ab.compareAndExchange(expected: false, desired: false))
XCTAssertTrue(ab.compareAndExchange(expected: true, desired: false))
XCTAssertTrue(ab.compareAndExchange(expected: false, desired: false))
XCTAssertTrue(ab.compareAndExchange(expected: false, desired: true))
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testAllOperationsBool() {
let ab = Atomic<Bool>(value: false)
XCTAssertEqual(false, ab.load())
ab.store(false)
XCTAssertEqual(false, ab.load())
ab.store(true)
XCTAssertEqual(true, ab.load())
ab.store(true)
XCTAssertEqual(true, ab.load())
XCTAssertEqual(true, ab.exchange(with: true))
XCTAssertEqual(true, ab.exchange(with: false))
XCTAssertEqual(false, ab.exchange(with: false))
XCTAssertTrue(ab.compareAndExchange(expected: false, desired: true))
XCTAssertFalse(ab.compareAndExchange(expected: false, desired: true))
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testCompareAndExchangeUInts() {
func testFor<T: AtomicPrimitive & FixedWidthInteger & UnsignedInteger>(_ value: T.Type) {
let zero: T = 0
let max = ~zero
let ab = Atomic<T>(value: max)
XCTAssertFalse(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: max, desired: max))
XCTAssertFalse(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: max, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: zero, desired: max))
var counter = max
for _ in 0..<255 {
XCTAssertTrue(ab.compareAndExchange(expected: counter, desired: counter-1))
counter = counter - 1
}
}
testFor(UInt8.self)
testFor(UInt16.self)
testFor(UInt32.self)
testFor(UInt64.self)
testFor(UInt.self)
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testCompareAndExchangeInts() {
func testFor<T: AtomicPrimitive & FixedWidthInteger & SignedInteger>(_ value: T.Type) {
let zero: T = 0
let upperBound: T = 127
let ab = Atomic<T>(value: upperBound)
XCTAssertFalse(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: upperBound, desired: upperBound))
XCTAssertFalse(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: upperBound, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: zero, desired: upperBound))
var counter = upperBound
for _ in 0..<255 {
XCTAssertTrue(ab.compareAndExchange(expected: counter, desired: counter-1))
XCTAssertFalse(ab.compareAndExchange(expected: counter, desired: counter))
counter = counter - 1
}
}
testFor(Int8.self)
testFor(Int16.self)
testFor(Int32.self)
testFor(Int64.self)
testFor(Int.self)
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testAddSub() {
func testFor<T: AtomicPrimitive & FixedWidthInteger>(_ value: T.Type) {
let zero: T = 0
let ab = Atomic<T>(value: zero)
XCTAssertEqual(0, ab.add(1))
XCTAssertEqual(1, ab.add(41))
XCTAssertEqual(42, ab.add(23))
XCTAssertEqual(65, ab.load())
XCTAssertEqual(65, ab.sub(23))
XCTAssertEqual(42, ab.sub(41))
XCTAssertEqual(1, ab.sub(1))
XCTAssertEqual(0, ab.load())
}
testFor(Int8.self)
testFor(Int16.self)
testFor(Int32.self)
testFor(Int64.self)
testFor(Int.self)
testFor(UInt8.self)
testFor(UInt16.self)
testFor(UInt32.self)
testFor(UInt64.self)
testFor(UInt.self)
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testExchange() {
func testFor<T: AtomicPrimitive & FixedWidthInteger>(_ value: T.Type) {
let zero: T = 0
let ab = Atomic<T>(value: zero)
XCTAssertEqual(0, ab.exchange(with: 1))
XCTAssertEqual(1, ab.exchange(with: 42))
XCTAssertEqual(42, ab.exchange(with: 65))
XCTAssertEqual(65, ab.load())
XCTAssertEqual(65, ab.exchange(with: 42))
XCTAssertEqual(42, ab.exchange(with: 1))
XCTAssertEqual(1, ab.exchange(with: 0))
XCTAssertEqual(0, ab.load())
}
testFor(Int8.self)
testFor(Int16.self)
testFor(Int32.self)
testFor(Int64.self)
testFor(Int.self)
testFor(UInt8.self)
testFor(UInt16.self)
testFor(UInt32.self)
testFor(UInt64.self)
testFor(UInt.self)
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testLoadStore() {
func testFor<T: AtomicPrimitive & FixedWidthInteger>(_ value: T.Type) {
let zero: T = 0
let ab = Atomic<T>(value: zero)
XCTAssertEqual(0, ab.load())
ab.store(42)
XCTAssertEqual(42, ab.load())
ab.store(0)
XCTAssertEqual(0, ab.load())
}
testFor(Int8.self)
testFor(Int16.self)
testFor(Int32.self)
testFor(Int64.self)
testFor(Int.self)
testFor(UInt8.self)
testFor(UInt16.self)
testFor(UInt32.self)
testFor(UInt64.self)
testFor(UInt.self)
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testLargeContendedNIOAtomicSum() {
let noAsyncs: UInt64 = 50
let noCounts: UInt64 = 2_000
let q = DispatchQueue(label: "q", attributes: .concurrent)
let g = DispatchGroup()
let ai = NIOConcurrencyHelpers.NIOAtomic<UInt64>.makeAtomic(value: 0)
let everybodyHere = DispatchSemaphore(value: 0)
let go = DispatchSemaphore(value: 0)
for thread in 1...noAsyncs {
q.async(group: g) {
everybodyHere.signal()
go.wait()
for _ in 0..<noCounts {
ai.add(thread)
}
}
}
for _ in 0..<noAsyncs {
everybodyHere.wait()
}
for _ in 0..<noAsyncs {
go.signal()
}
g.wait()
XCTAssertEqual(sumOfIntegers(until: noAsyncs) * noCounts, ai.load())
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testCompareAndExchangeBoolNIOAtomic() {
let ab = NIOAtomic<Bool>.makeAtomic(value: true)
XCTAssertFalse(ab.compareAndExchange(expected: false, desired: false))
XCTAssertTrue(ab.compareAndExchange(expected: true, desired: true))
XCTAssertFalse(ab.compareAndExchange(expected: false, desired: false))
XCTAssertTrue(ab.compareAndExchange(expected: true, desired: false))
XCTAssertTrue(ab.compareAndExchange(expected: false, desired: false))
XCTAssertTrue(ab.compareAndExchange(expected: false, desired: true))
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testAllOperationsBoolNIOAtomic() {
let ab = NIOAtomic<Bool>.makeAtomic(value: false)
XCTAssertEqual(false, ab.load())
ab.store(false)
XCTAssertEqual(false, ab.load())
ab.store(true)
XCTAssertEqual(true, ab.load())
ab.store(true)
XCTAssertEqual(true, ab.load())
XCTAssertEqual(true, ab.exchange(with: true))
XCTAssertEqual(true, ab.exchange(with: false))
XCTAssertEqual(false, ab.exchange(with: false))
XCTAssertTrue(ab.compareAndExchange(expected: false, desired: true))
XCTAssertFalse(ab.compareAndExchange(expected: false, desired: true))
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testCompareAndExchangeUIntsNIOAtomic() {
func testFor<T: NIOAtomicPrimitive & FixedWidthInteger & UnsignedInteger>(_ value: T.Type) {
let zero: T = 0
let max = ~zero
let ab = NIOAtomic<T>.makeAtomic(value: max)
XCTAssertFalse(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: max, desired: max))
XCTAssertFalse(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: max, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: zero, desired: max))
var counter = max
for _ in 0..<255 {
XCTAssertTrue(ab.compareAndExchange(expected: counter, desired: counter-1))
counter = counter - 1
}
}
testFor(UInt8.self)
testFor(UInt16.self)
testFor(UInt32.self)
testFor(UInt64.self)
testFor(UInt.self)
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testCompareAndExchangeIntsNIOAtomic() {
func testFor<T: NIOAtomicPrimitive & FixedWidthInteger & SignedInteger>(_ value: T.Type) {
let zero: T = 0
let upperBound: T = 127
let ab = NIOAtomic<T>.makeAtomic(value: upperBound)
XCTAssertFalse(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: upperBound, desired: upperBound))
XCTAssertFalse(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: upperBound, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: zero, desired: zero))
XCTAssertTrue(ab.compareAndExchange(expected: zero, desired: upperBound))
var counter = upperBound
for _ in 0..<255 {
XCTAssertTrue(ab.compareAndExchange(expected: counter, desired: counter-1))
XCTAssertFalse(ab.compareAndExchange(expected: counter, desired: counter))
counter = counter - 1
}
}
testFor(Int8.self)
testFor(Int16.self)
testFor(Int32.self)
testFor(Int64.self)
testFor(Int.self)
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testAddSubNIOAtomic() {
func testFor<T: NIOAtomicPrimitive & FixedWidthInteger>(_ value: T.Type) {
let zero: T = 0
let ab = NIOAtomic<T>.makeAtomic(value: zero)
XCTAssertEqual(0, ab.add(1))
XCTAssertEqual(1, ab.add(41))
XCTAssertEqual(42, ab.add(23))
XCTAssertEqual(65, ab.load())
XCTAssertEqual(65, ab.sub(23))
XCTAssertEqual(42, ab.sub(41))
XCTAssertEqual(1, ab.sub(1))
XCTAssertEqual(0, ab.load())
let atomic = NIOAtomic<T>.makeAtomic(value: zero)
atomic.store(100)
atomic.add(1)
XCTAssertEqual(101, atomic.load())
atomic.sub(1)
XCTAssertEqual(100, atomic.load())
}
testFor(Int8.self)
testFor(Int16.self)
testFor(Int32.self)
testFor(Int64.self)
testFor(Int.self)
testFor(UInt8.self)
testFor(UInt16.self)
testFor(UInt32.self)
testFor(UInt64.self)
testFor(UInt.self)
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testExchangeNIOAtomic() {
func testFor<T: NIOAtomicPrimitive & FixedWidthInteger>(_ value: T.Type) {
let zero: T = 0
let ab = NIOAtomic<T>.makeAtomic(value: zero)
XCTAssertEqual(0, ab.exchange(with: 1))
XCTAssertEqual(1, ab.exchange(with: 42))
XCTAssertEqual(42, ab.exchange(with: 65))
XCTAssertEqual(65, ab.load())
XCTAssertEqual(65, ab.exchange(with: 42))
XCTAssertEqual(42, ab.exchange(with: 1))
XCTAssertEqual(1, ab.exchange(with: 0))
XCTAssertEqual(0, ab.load())
}
testFor(Int8.self)
testFor(Int16.self)
testFor(Int32.self)
testFor(Int64.self)
testFor(Int.self)
testFor(UInt8.self)
testFor(UInt16.self)
testFor(UInt32.self)
testFor(UInt64.self)
testFor(UInt.self)
}
@available(*, deprecated, message: "deprecated because it tests deprecated functionality")
func testLoadStoreNIOAtomic() {
func testFor<T: NIOAtomicPrimitive & FixedWidthInteger>(_ value: T.Type) {
let zero: T = 0
let ab = NIOAtomic<T>.makeAtomic(value: zero)
XCTAssertEqual(0, ab.load())
ab.store(42)
XCTAssertEqual(42, ab.load())
ab.store(0)
XCTAssertEqual(0, ab.load())
}
testFor(Int8.self)
testFor(Int16.self)
testFor(Int32.self)
testFor(Int64.self)
testFor(Int.self)
testFor(UInt8.self)
testFor(UInt16.self)
testFor(UInt32.self)
testFor(UInt64.self)
testFor(UInt.self)
}
func testLockMutualExclusion() {
let l = NIOLock()
var x = 1
let q = DispatchQueue(label: "q")
let g = DispatchGroup()
let sem1 = DispatchSemaphore(value: 0)
let sem2 = DispatchSemaphore(value: 0)
l.lock()
q.async(group: g) {
sem1.signal()
l.lock()
x = 2
l.unlock()
sem2.signal()
}
sem1.wait()
XCTAssertEqual(DispatchTimeoutResult.timedOut,
g.wait(timeout: .now() + 0.1))
XCTAssertEqual(1, x)
l.unlock()
sem2.wait()
l.lock()
XCTAssertEqual(2, x)
l.unlock()
}
func testWithLockMutualExclusion() {
let l = NIOLock()
var x = 1
let q = DispatchQueue(label: "q")
let g = DispatchGroup()
let sem1 = DispatchSemaphore(value: 0)
let sem2 = DispatchSemaphore(value: 0)
l.withLock {
q.async(group: g) {
sem1.signal()
l.withLock {
x = 2
}
sem2.signal()
}
sem1.wait()
XCTAssertEqual(DispatchTimeoutResult.timedOut,
g.wait(timeout: .now() + 0.1))
XCTAssertEqual(1, x)
}
sem2.wait()
l.withLock {
XCTAssertEqual(2, x)
}
}
func testConditionLockMutualExclusion() {
let l = ConditionLock(value: 0)
var x = 1
let q = DispatchQueue(label: "q")
let g = DispatchGroup()
let sem1 = DispatchSemaphore(value: 0)
let sem2 = DispatchSemaphore(value: 0)
l.lock()
q.async(group: g) {
sem1.signal()
l.lock()
x = 2
l.unlock()
sem2.signal()
}
sem1.wait()
XCTAssertEqual(DispatchTimeoutResult.timedOut,
g.wait(timeout: .now() + 0.1))
XCTAssertEqual(1, x)
l.unlock()
sem2.wait()
l.lock()
XCTAssertEqual(2, x)
l.unlock()
}
func testConditionLock() {
let l = ConditionLock(value: 0)
let q = DispatchQueue(label: "q")
let sem = DispatchSemaphore(value: 0)
XCTAssertEqual(0, l.value)
l.lock()
l.unlock(withValue: 1)
XCTAssertEqual(1, l.value)
q.async {
l.lock(whenValue: 2)
l.unlock(withValue: 3)
sem.signal()
}
usleep(100_000)
l.lock()
l.unlock(withValue: 2)
sem.wait()
l.lock(whenValue: 3)
l.unlock()
XCTAssertEqual(false, l.lock(whenValue: 4, timeoutSeconds: 0.1))
XCTAssertEqual(true, l.lock(whenValue: 3, timeoutSeconds: 0.01))
l.unlock()
q.async {
usleep(100_000)
l.lock()
l.unlock(withValue: 4)
sem.signal()
}
XCTAssertEqual(true, l.lock(whenValue: 4, timeoutSeconds: 10))
l.unlock()
}
func testConditionLockWithDifferentConditions() {
for _ in 0..<200 {
let l = ConditionLock(value: 0)
let q1 = DispatchQueue(label: "q1")
let q2 = DispatchQueue(label: "q2")
let readySem = DispatchSemaphore(value: 0)
let doneSem = DispatchSemaphore(value: 0)
q1.async {
readySem.signal()
l.lock(whenValue: 1)
l.unlock()
XCTAssertEqual(1, l.value)
doneSem.signal()
}
q2.async {
readySem.signal()
l.lock(whenValue: 2)
l.unlock()
XCTAssertEqual(2, l.value)
doneSem.signal()
}
readySem.wait()
readySem.wait()
l.lock()
l.unlock(withValue: 1)
doneSem.wait() /* job on 'q1' is done */
XCTAssertEqual(1, l.value)
l.lock()
l.unlock(withValue: 2)
doneSem.wait() /* job on 'q2' is done */
}
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testAtomicBoxDoesNotTriviallyLeak() throws {
class SomeClass {}
weak var weakSomeInstance1: SomeClass? = nil
weak var weakSomeInstance2: SomeClass? = nil
({
let someInstance = SomeClass()
weakSomeInstance1 = someInstance
let someAtomic = AtomicBox(value: someInstance)
let loadedFromAtomic = someAtomic.load()
weakSomeInstance2 = loadedFromAtomic
XCTAssertNotNil(weakSomeInstance1)
XCTAssertNotNil(weakSomeInstance2)
XCTAssert(someInstance === loadedFromAtomic)
})()
XCTAssertNil(weakSomeInstance1)
XCTAssertNil(weakSomeInstance2)
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testAtomicBoxCompareAndExchangeWorksIfEqual() throws {
class SomeClass {}
weak var weakSomeInstance1: SomeClass? = nil
weak var weakSomeInstance2: SomeClass? = nil
weak var weakSomeInstance3: SomeClass? = nil
({
let someInstance1 = SomeClass()
let someInstance2 = SomeClass()
weakSomeInstance1 = someInstance1
let atomic = AtomicBox(value: someInstance1)
var loadedFromAtomic = atomic.load()
XCTAssert(someInstance1 === loadedFromAtomic)
weakSomeInstance2 = loadedFromAtomic
XCTAssertTrue(atomic.compareAndExchange(expected: loadedFromAtomic, desired: someInstance2))
loadedFromAtomic = atomic.load()
weakSomeInstance3 = loadedFromAtomic
XCTAssert(someInstance1 !== loadedFromAtomic)
XCTAssert(someInstance2 === loadedFromAtomic)
XCTAssertNotNil(weakSomeInstance1)
XCTAssertNotNil(weakSomeInstance2)
XCTAssertNotNil(weakSomeInstance3)
XCTAssert(weakSomeInstance1 === weakSomeInstance2 && weakSomeInstance2 !== weakSomeInstance3)
})()
XCTAssertNil(weakSomeInstance1)
XCTAssertNil(weakSomeInstance2)
XCTAssertNil(weakSomeInstance3)
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testAtomicBoxCompareAndExchangeWorksIfNotEqual() throws {
class SomeClass {}
weak var weakSomeInstance1: SomeClass? = nil
weak var weakSomeInstance2: SomeClass? = nil
weak var weakSomeInstance3: SomeClass? = nil
({
let someInstance1 = SomeClass()
let someInstance2 = SomeClass()
weakSomeInstance1 = someInstance1
let atomic = AtomicBox(value: someInstance1)
var loadedFromAtomic = atomic.load()
XCTAssert(someInstance1 === loadedFromAtomic)
weakSomeInstance2 = loadedFromAtomic
XCTAssertFalse(atomic.compareAndExchange(expected: someInstance2, desired: someInstance2))
XCTAssertFalse(atomic.compareAndExchange(expected: SomeClass(), desired: someInstance2))
XCTAssertTrue(atomic.load() === someInstance1)
loadedFromAtomic = atomic.load()
weakSomeInstance3 = someInstance2
XCTAssert(someInstance1 === loadedFromAtomic)
XCTAssert(someInstance2 !== loadedFromAtomic)
XCTAssertNotNil(weakSomeInstance1)
XCTAssertNotNil(weakSomeInstance2)
XCTAssertNotNil(weakSomeInstance3)
})()
XCTAssertNil(weakSomeInstance1)
XCTAssertNil(weakSomeInstance2)
XCTAssertNil(weakSomeInstance3)
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testAtomicBoxStoreWorks() throws {
class SomeClass {}
weak var weakSomeInstance1: SomeClass? = nil
weak var weakSomeInstance2: SomeClass? = nil
weak var weakSomeInstance3: SomeClass? = nil
({
let someInstance1 = SomeClass()
let someInstance2 = SomeClass()
weakSomeInstance1 = someInstance1
let atomic = AtomicBox(value: someInstance1)
var loadedFromAtomic = atomic.load()
XCTAssert(someInstance1 === loadedFromAtomic)
weakSomeInstance2 = loadedFromAtomic
atomic.store(someInstance2)
loadedFromAtomic = atomic.load()
weakSomeInstance3 = loadedFromAtomic
XCTAssert(someInstance1 !== loadedFromAtomic)
XCTAssert(someInstance2 === loadedFromAtomic)
XCTAssertNotNil(weakSomeInstance1)
XCTAssertNotNil(weakSomeInstance2)
XCTAssertNotNil(weakSomeInstance3)
})()
XCTAssertNil(weakSomeInstance1)
XCTAssertNil(weakSomeInstance2)
XCTAssertNil(weakSomeInstance3)
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testAtomicBoxCompareAndExchangeOntoItselfWorks() {
let q = DispatchQueue(label: "q")
let g = DispatchGroup()
let sem1 = DispatchSemaphore(value: 0)
let sem2 = DispatchSemaphore(value: 0)
class SomeClass {}
weak var weakInstance: SomeClass?
({
let instance = SomeClass()
weakInstance = instance
let atomic = AtomicBox(value: instance)
q.async(group: g) {
sem1.signal()
sem2.wait()
for _ in 0..<1000 {
XCTAssertTrue(atomic.compareAndExchange(expected: instance, desired: instance))
}
}
sem2.signal()
sem1.wait()
for _ in 0..<1000 {
XCTAssertTrue(atomic.compareAndExchange(expected: instance, desired: instance))
}
g.wait()
let v = atomic.load()
XCTAssert(v === instance)
})()
XCTAssertNil(weakInstance)
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testAtomicLoadMassLoadAndStore() {
let writer = DispatchQueue(label: "\(#file):writer")
let reader = DispatchQueue(label: "\(#file):reader")
let g = DispatchGroup()
let writerArrived = DispatchSemaphore(value: 0)
let readerArrived = DispatchSemaphore(value: 0)
let go = DispatchSemaphore(value: 0)
let iterations = 100_000
class Foo {
var x: Int
init(_ x: Int) {
self.x = x
}
deinit {
self.x = -1
}
}
let box: AtomicBox<Foo> = .init(value: Foo(iterations))
writer.async(group: g) {
writerArrived.signal()
go.wait()
for i in 0..<iterations {
box.store(Foo(i))
}
}
reader.async(group: g) {
readerArrived.signal()
go.wait()
for _ in 0..<iterations {
if box.load().x < 0 {
XCTFail("bad")
}
}
}
writerArrived.wait()
readerArrived.wait()
go.signal()
go.signal()
g.wait()
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testAtomicBoxCompareAndExchangeOntoItself() {
class Foo {}
weak var weakF: Foo? = nil
weak var weakG: Foo? = nil
@inline(never)
func doIt() {
let f = Foo()
let g = Foo()
weakF = f
weakG = g
let box = AtomicBox<Foo>(value: f)
XCTAssertFalse(box.compareAndExchange(expected: g, desired: g))
XCTAssertTrue(box.compareAndExchange(expected: f, desired: f))
XCTAssertFalse(box.compareAndExchange(expected: g, desired: g))
XCTAssertTrue(box.compareAndExchange(expected: f, desired: g))
}
doIt()
assert(weakF == nil, within: .seconds(1))
assert(weakG == nil, within: .seconds(1))
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testLoadAndExchangeHammering() {
let allDeallocations = NIOAtomic<Int>.makeAtomic(value: 0)
let iterations = 10_000
@inline(never)
func doIt() {
let box = AtomicBox(value: IntHolderWithDeallocationTracking(0, allDeallocations: allDeallocations))
spawnAndJoinRacingThreads(count: 6) { i in
switch i {
case 0: // writer
for i in 1 ... iterations {
let nextObject = box.exchange(with: .init(i, allDeallocations: allDeallocations))
XCTAssertEqual(nextObject.value, i - 1)
}
default: // readers
while true {
if box.load().value < 0 || box.load().value > iterations {
XCTFail("bad")
}
if box.load().value == iterations {
break
}
}
}
}
}
doIt()
assert(allDeallocations.load() == iterations + 1, within: .seconds(1))
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testLoadAndStoreHammering() {
let allDeallocations = NIOAtomic<Int>.makeAtomic(value: 0)
let iterations = 10_000
@inline(never)
func doIt() {
let box = AtomicBox(value: IntHolderWithDeallocationTracking(0, allDeallocations: allDeallocations))
spawnAndJoinRacingThreads(count: 6) { i in
switch i {
case 0: // writer
for i in 1 ... iterations {
box.store(IntHolderWithDeallocationTracking(i, allDeallocations: allDeallocations))
}
default: // readers
while true {
if box.load().value < 0 || box.load().value > iterations {
XCTFail("loaded the wrong value")
}
if box.load().value == iterations {
break
}
}
}
}
}
doIt()
assert(allDeallocations.load() == iterations + 1, within: .seconds(1))
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testLoadAndCASHammering() {
let allDeallocations = NIOAtomic<Int>.makeAtomic(value: 0)
let iterations = 1_000
@inline(never)
func doIt() {
let box = AtomicBox(value: IntHolderWithDeallocationTracking(0, allDeallocations: allDeallocations))
spawnAndJoinRacingThreads(count: 6) { i in
switch i {
case 0: // writer
for i in 1 ... iterations {
let old = box.load()
XCTAssertEqual(i - 1, old.value)
if !box.compareAndExchange(expected: old,
desired: .init(i, allDeallocations: allDeallocations)) {
XCTFail("compare and exchange didn't work but it should have")
}
}
default: // readers
while true {
if box.load().value < 0 || box.load().value > iterations {
XCTFail("loaded wrong value")
}
if box.load().value == iterations {
break
}
}
}
}
}
doIt()
assert(allDeallocations.load() == iterations + 1, within: .seconds(1))
}
@available(*, deprecated, message: "AtomicBox is deprecated, this is a test for the deprecated functionality")
func testMultipleLoadsRacingWhilstStoresAreGoingOn() {
// regression test for https://github.com/apple/swift-nio/pull/1287#discussion_r353932225
let allDeallocations = NIOAtomic<Int>.makeAtomic(value: 0)
let iterations = 10_000
@inline(never)
func doIt() {
let box = AtomicBox(value: IntHolderWithDeallocationTracking(0, allDeallocations: allDeallocations))
spawnAndJoinRacingThreads(count: 3) { i in
switch i {
case 0:
var last = Int.min
while last < iterations {
let loaded = box.load()
XCTAssertGreaterThanOrEqual(loaded.value, last)
last = loaded.value
}
case 1:
for n in 1...iterations {
box.store(.init(n, allDeallocations: allDeallocations))
}
case 2:
var last = Int.min
while last < iterations {
let loaded = box.load()
XCTAssertGreaterThanOrEqual(loaded.value, last)
last = loaded.value
}
default:
preconditionFailure("thread \(i)?!")
}
}
}
doIt()
XCTAssertEqual(iterations + 1, allDeallocations.load())
}
func testNIOLockedValueBox() {
struct State {
var count: Int = 0
}
let lv = NIOLockedValueBox<State>(State())
spawnAndJoinRacingThreads(count: 50) { _ in
for _ in 0..<1000 {
lv.withLockedValue { state in
state.count += 1
}
}
}
XCTAssertEqual(50_000, lv.withLockedValue { $0.count })
}
}
func spawnAndJoinRacingThreads(count: Int, _ body: @escaping (Int) -> Void) {
let go = DispatchSemaphore(value: 0) // will be incremented when the threads are supposed to run (and race).
let arrived = Array(repeating: DispatchSemaphore(value: 0), count: count) // waiting for all threads to arrive
let group = DispatchGroup()
for i in 0..<count {
DispatchQueue(label: "\(#file):\(#line):\(i)").async(group: group) {
arrived[i].signal()
go.wait()
body(i)
}
}
for sem in arrived {
sem.wait()
}
// all the threads are ready to go
for _ in 0..<count {
go.signal()
}
group.wait()
}
func assert(_ condition: @autoclosure () -> Bool, within time: TimeAmount, testInterval: TimeAmount? = nil, _ message: String = "condition not satisfied in time", file: StaticString = #filePath, line: UInt = #line) {
let testInterval = testInterval ?? TimeAmount.nanoseconds(time.nanoseconds / 5)
let endTime = NIODeadline.now() + time
repeat {
if condition() { return }
usleep(UInt32(testInterval.nanoseconds / 1000))
} while (NIODeadline.now() < endTime)
if !condition() {
XCTFail(message, file: (file), line: line)
}
}
@available(*, deprecated, message: "deprecated because it is used to test deprecated functionality")
fileprivate class IntHolderWithDeallocationTracking {
private(set) var value: Int
let allDeallocations: NIOAtomic<Int>
init(_ x: Int, allDeallocations: NIOAtomic<Int>) {
self.value = x
self.allDeallocations = allDeallocations
}
deinit {
self.value = -1
self.allDeallocations.add(1)
}
}
| apache-2.0 |
openHPI/xikolo-ios | iOS/XikoloTabBarController.swift | 1 | 8512 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
import UIKit
class XikoloTabBarController: UITabBarController {
enum Tabs: CaseIterable {
case dashboard
case channels
case courses
case news
case more
case account
static var availableTabs: [Tabs] {
return Self.allCases.filter(\.isAvailable)
}
var isAvailable: Bool {
switch self {
case .channels:
return Brand.default.features.enableChannels
case .news:
return !self.additionalLearningResourcesAvailable
case .more:
return self.additionalLearningResourcesAvailable
default:
return true
}
}
private var additionalLearningResourcesAvailable: Bool {
return !Brand.default.additionalLearningMaterial.isEmpty
}
var index: Int {
return Self.availableTabs.firstIndex(of: self).require()
}
var viewController: UIViewController? {
switch self {
case .dashboard:
return R.storyboard.tabDashboard.instantiateInitialViewController()
case .channels:
return R.storyboard.tabChannels.instantiateInitialViewController()
case .courses:
return R.storyboard.tabCourses.instantiateInitialViewController()
case .news:
return R.storyboard.tabNews.instantiateInitialViewController()
case .more:
return R.storyboard.tabMore.instantiateInitialViewController()
case .account:
return R.storyboard.tabAccount.instantiateInitialViewController()
}
}
}
struct Configuration {
let backgroundColor: UIColor
let textColor: UIColor
let message: String?
}
static func make() -> XikoloTabBarController {
let tabBarController = XikoloTabBarController()
tabBarController.viewControllers = Tabs.availableTabs.compactMap(\.viewController)
return tabBarController
}
private static let messageViewHeight: CGFloat = 16
private static let messageLabelFontSize: CGFloat = 12
private static let dateFormatter = DateFormatter.localizedFormatter(dateStyle: .long, timeStyle: .none)
private var messageView = UIView()
private var messageLabel = UILabel()
private var _status: APIStatus = .standard
var status: APIStatus {
get {
return self._status
}
set {
guard self.status != newValue else { return }
// allow only some status changes
switch (self.status, newValue) {
case (.standard, _):
break
case (.deprecated, .maintenance):
break
case (.deprecated, .expired):
break
case (.maintenance, .standard):
break
case (.maintenance, .expired):
break
default:
return
}
logger.info("Update app state from %@ to %@", String(describing: self.status), String(describing: newValue))
let animated = self.status != .standard
UIView.animate(withDuration: defaultAnimationDuration(animated)) {
self._status = newValue
self.updateMessageViewAppearance()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tabBar.isTranslucent = false
if #available(iOS 15, *) {
let appearance = UITabBarAppearance()
appearance.configureWithOpaqueBackground()
self.tabBar.standardAppearance = appearance
self.tabBar.scrollEdgeAppearance = appearance
}
self.messageLabel.textAlignment = .center
self.messageLabel.font = UIFont.systemFont(ofSize: XikoloTabBarController.messageLabelFontSize)
self.messageView.addSubview(self.messageLabel)
self.messageLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.messageLabel.topAnchor.constraint(equalTo: self.messageView.topAnchor),
self.messageLabel.leadingAnchor.constraint(equalTo: self.messageView.leadingAnchor),
self.messageLabel.trailingAnchor.constraint(equalTo: self.messageView.trailingAnchor),
self.messageLabel.heightAnchor.constraint(equalToConstant: XikoloTabBarController.messageViewHeight),
])
self.messageView.frame = CGRect(x: 0, y: self.tabBar.frame.height, width: self.view.frame.width, height: 0)
self.tabBar.addSubview(self.messageView)
self.messageView.autoresizingMask = [.flexibleWidth]
NotificationCenter.default.addObserver(self,
selector: #selector(handleAPIStatusChange(_:)),
name: APIStatus.didChangeNotification,
object: nil)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Make sure we can correctly determine the height of tab bar items
self.tabBar.layoutSubviews()
self.updateMessageViewAppearance()
}
@objc private func handleAPIStatusChange(_ notification: Notification) {
let newStatus = notification.userInfo?[APIStatusNotificationKey.status] as? APIStatus
self.status = newStatus ?? .standard
}
private func updateMessageViewAppearance() {
let config = self.configuration(for: self.status)
self.messageView.backgroundColor = config.backgroundColor
self.messageLabel.textColor = config.textColor
self.messageLabel.text = config.message
var newMessageViewFrame = self.messageView.frame
newMessageViewFrame.origin.y = self.status == .standard ? 0 : -1 * XikoloTabBarController.messageViewHeight
newMessageViewFrame.size.height = self.status == .standard ? 0 : XikoloTabBarController.messageViewHeight
self.messageView.frame = newMessageViewFrame
}
private func configuration(for status: APIStatus) -> Configuration {
switch status {
case .standard:
return Configuration(backgroundColor: .white, textColor: .clear, message: nil)
case .maintenance:
let format = NSLocalizedString("app-state.maintenance.server maintenance on %@",
comment: "App state message for server maintenance")
let message = String.localizedStringWithFormat(format, UIApplication.appName)
return Configuration(backgroundColor: Brand.default.colors.window, textColor: .white, message: message)
case .deprecated(expiresOn: let expirationDate):
let formattedExpirationDate = XikoloTabBarController.dateFormatter.string(from: expirationDate)
let format = NSLocalizedString("app-state.api-deprecated.please update the %@ app before %@",
comment: "App state message for deprecated API version")
let message = String.localizedStringWithFormat(format, UIApplication.appName, formattedExpirationDate)
return Configuration(backgroundColor: .orange, textColor: .white, message: message)
case .expired:
let format = NSLocalizedString("app-state.api-expired.app version of %@ expired - please update",
comment: "App state message for expired API version")
let message = String.localizedStringWithFormat(format, UIApplication.appName)
return Configuration(backgroundColor: .red, textColor: .white, message: message)
}
}
private func heightOfTabBarItems() -> CGFloat? {
var heightCounter: [CGFloat: Int] = [:]
for subview in self.tabBar.subviews.filter({ $0 != self.messageView }) {
let subviewHeight = subview.frame.height
if let count = heightCounter[subviewHeight] {
heightCounter[subviewHeight] = count + 1
} else {
heightCounter[subviewHeight] = 1
}
}
let itemsCounts = self.tabBar.items?.count ?? 0
return heightCounter.first { $1 == itemsCounts }?.key
}
}
| gpl-3.0 |
jellybeansoup/ios-melissa | Shared/Extensions/NSURL.swift | 2 | 515 | import Foundation
extension URL {
static var contactOther: URL {
return URL(string: "my-other:/contact")!
}
static var messageOther: URL {
return self.messageOther(with: nil)
}
static func messageOther(with body: String?) -> URL {
var components = URLComponents(string: "my-other:/message")!
if let body = body {
components.queryItems = [URLQueryItem(name: "body", value: body)]
}
return components.url!
}
}
| bsd-2-clause |
stephentyrone/swift | stdlib/public/core/UnicodeScalarProperties.swift | 1 | 59369 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Exposes advanced properties of Unicode.Scalar defined by the Unicode
// Standard.
//===----------------------------------------------------------------------===//
import SwiftShims
extension Unicode.Scalar {
/// A value that provides access to properties of a Unicode scalar that are
/// defined by the Unicode standard.
public struct Properties {
@usableFromInline
internal var _scalar: Unicode.Scalar
internal init(_ scalar: Unicode.Scalar) {
self._scalar = scalar
}
// Provide the value as UChar32 to make calling the ICU APIs cleaner
internal var icuValue: __swift_stdlib_UChar32 {
return __swift_stdlib_UChar32(bitPattern: self._scalar._value)
}
}
/// Properties of this scalar defined by the Unicode standard.
///
/// Use this property to access the Unicode properties of a Unicode scalar
/// value. The following code tests whether a string contains any math
/// symbols:
///
/// let question = "Which is larger, 3 * 3 * 3 or 10 + 10 + 10?"
/// let hasMathSymbols = question.unicodeScalars.contains(where: {
/// $0.properties.isMath
/// })
/// // hasMathSymbols == true
public var properties: Properties {
return Properties(self)
}
}
/// Boolean properties that are defined by the Unicode Standard (i.e., not
/// ICU-specific).
extension Unicode.Scalar.Properties {
internal func _hasBinaryProperty(
_ property: __swift_stdlib_UProperty
) -> Bool {
return __swift_stdlib_u_hasBinaryProperty(icuValue, property) != 0
}
/// A Boolean value indicating whether the scalar is alphabetic.
///
/// Alphabetic scalars are the primary units of alphabets and/or syllabaries.
///
/// This property corresponds to the "Alphabetic" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isAlphabetic: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_ALPHABETIC)
}
/// A Boolean value indicating whether the scalar is an ASCII character
/// commonly used for the representation of hexadecimal numbers.
///
/// The only scalars for which this property is `true` are:
///
/// * U+0030...U+0039: DIGIT ZERO...DIGIT NINE
/// * U+0041...U+0046: LATIN CAPITAL LETTER A...LATIN CAPITAL LETTER F
/// * U+0061...U+0066: LATIN SMALL LETTER A...LATIN SMALL LETTER F
///
/// This property corresponds to the "ASCII_Hex_Digit" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isASCIIHexDigit: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_ASCII_HEX_DIGIT)
}
/// A Boolean value indicating whether the scalar is a format control
/// character that has a specific function in the Unicode Bidrectional
/// Algorithm.
///
/// This property corresponds to the "Bidi_Control" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isBidiControl: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_BIDI_CONTROL)
}
/// A Boolean value indicating whether the scalar is mirrored in
/// bidirectional text.
///
/// This property corresponds to the "Bidi_Mirrored" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isBidiMirrored: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_BIDI_MIRRORED)
}
/// A Boolean value indicating whether the scalar is a punctuation
/// symbol explicitly called out as a dash in the Unicode Standard or a
/// compatibility equivalent.
///
/// This property corresponds to the "Dash" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isDash: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_DASH)
}
/// A Boolean value indicating whether the scalar is a default-ignorable
/// code point.
///
/// Default-ignorable code points are those that should be ignored by default
/// in rendering (unless explicitly supported). They have no visible glyph or
/// advance width in and of themselves, although they may affect the display,
/// positioning, or adornment of adjacent or surrounding characters.
///
/// This property corresponds to the "Default_Ignorable_Code_Point" property
/// in the [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isDefaultIgnorableCodePoint: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_DEFAULT_IGNORABLE_CODE_POINT)
}
/// A Boolean value indicating whether the scalar is deprecated.
///
/// Scalars are never removed from the Unicode Standard, but the usage of
/// deprecated scalars is strongly discouraged.
///
/// This property corresponds to the "Deprecated" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isDeprecated: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_DEPRECATED)
}
/// A Boolean value indicating whether the scalar is a diacritic.
///
/// Diacritics are scalars that linguistically modify the meaning of another
/// scalar to which they apply. Scalars for which this property is `true` are
/// frequently, but not always, combining marks or modifiers.
///
/// This property corresponds to the "Diacritic" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isDiacritic: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_DIACRITIC)
}
/// A Boolean value indicating whether the scalar's principal function is
/// to extend the value or shape of a preceding alphabetic scalar.
///
/// Typical extenders are length and iteration marks.
///
/// This property corresponds to the "Extender" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isExtender: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_EXTENDER)
}
/// A Boolean value indicating whether the scalar is excluded from
/// composition when performing Unicode normalization.
///
/// This property corresponds to the "Full_Composition_Exclusion" property in
/// the [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isFullCompositionExclusion: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_FULL_COMPOSITION_EXCLUSION)
}
/// A Boolean value indicating whether the scalar is a grapheme base.
///
/// A grapheme base can be thought of as a space-occupying glyph above or
/// below which other non-spacing modifying glyphs can be applied. For
/// example, when the character `é` is represented in its decomposed form,
/// the grapheme base is "e" (U+0065 LATIN SMALL LETTER E) and it is followed
/// by a single grapheme extender, U+0301 COMBINING ACUTE ACCENT.
///
/// The set of scalars for which `isGraphemeBase` is `true` is disjoint by
/// definition from the set for which `isGraphemeExtend` is `true`.
///
/// This property corresponds to the "Grapheme_Base" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isGraphemeBase: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_GRAPHEME_BASE)
}
/// A Boolean value indicating whether the scalar is a grapheme extender.
///
/// A grapheme extender can be thought of primarily as a non-spacing glyph
/// that is applied above or below another glyph. For example, when the
/// character `é` is represented in its decomposed form, the grapheme base is
/// "e" (U+0065 LATIN SMALL LETTER E) and it is followed by a single grapheme
/// extender, U+0301 COMBINING ACUTE ACCENT.
///
/// The set of scalars for which `isGraphemeExtend` is `true` is disjoint by
/// definition from the set for which `isGraphemeBase` is `true`.
///
/// This property corresponds to the "Grapheme_Extend" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isGraphemeExtend: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_GRAPHEME_EXTEND)
}
/// A Boolean value indicating whether the scalar is one that is commonly
/// used for the representation of hexadecimal numbers or a compatibility
/// equivalent.
///
/// This property is `true` for all scalars for which `isASCIIHexDigit` is
/// `true` as well as for their CJK halfwidth and fullwidth variants.
///
/// This property corresponds to the "Hex_Digit" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isHexDigit: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_HEX_DIGIT)
}
/// A Boolean value indicating whether the scalar is one which is
/// recommended to be allowed to appear in a non-starting position in a
/// programming language identifier.
///
/// Applications that store identifiers in NFKC normalized form should instead
/// use `isXIDContinue` to check whether a scalar is a valid identifier
/// character.
///
/// This property corresponds to the "ID_Continue" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIDContinue: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_ID_CONTINUE)
}
/// A Boolean value indicating whether the scalar is one which is
/// recommended to be allowed to appear in a starting position in a
/// programming language identifier.
///
/// Applications that store identifiers in NFKC normalized form should instead
/// use `isXIDStart` to check whether a scalar is a valid identifier
/// character.
///
/// This property corresponds to the "ID_Start" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIDStart: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_ID_START)
}
/// A Boolean value indicating whether the scalar is considered to be a
/// CJKV (Chinese, Japanese, Korean, and Vietnamese) or other siniform
/// (Chinese writing-related) ideograph.
///
/// This property roughly defines the class of "Chinese characters" and does
/// not include characters of other logographic scripts such as Cuneiform or
/// Egyptian Hieroglyphs.
///
/// This property corresponds to the "Ideographic" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIdeographic: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_IDEOGRAPHIC)
}
/// A Boolean value indicating whether the scalar is an ideographic
/// description character that determines how the two ideographic characters
/// or ideographic description sequences that follow it are to be combined to
/// form a single character.
///
/// Ideographic description characters are technically printable characters,
/// but advanced rendering engines may use them to approximate ideographs that
/// are otherwise unrepresentable.
///
/// This property corresponds to the "IDS_Binary_Operator" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIDSBinaryOperator: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_IDS_BINARY_OPERATOR)
}
/// A Boolean value indicating whether the scalar is an ideographic
/// description character that determines how the three ideographic characters
/// or ideographic description sequences that follow it are to be combined to
/// form a single character.
///
/// Ideographic description characters are technically printable characters,
/// but advanced rendering engines may use them to approximate ideographs that
/// are otherwise unrepresentable.
///
/// This property corresponds to the "IDS_Trinary_Operator" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isIDSTrinaryOperator: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_IDS_TRINARY_OPERATOR)
}
/// A Boolean value indicating whether the scalar is a format control
/// character that has a specific function in controlling cursive joining and
/// ligation.
///
/// There are two scalars for which this property is `true`:
///
/// * When U+200C ZERO WIDTH NON-JOINER is inserted between two characters, it
/// directs the rendering engine to render them separately/disconnected when
/// it might otherwise render them as a ligature. For example, a rendering
/// engine might display "fl" in English as a connected glyph; inserting the
/// zero width non-joiner would force them to be rendered as disconnected
/// glyphs.
///
/// * When U+200D ZERO WIDTH JOINER is inserted between two characters, it
/// directs the rendering engine to render them as a connected glyph when it
/// would otherwise render them independently. The zero width joiner is also
/// used to construct complex emoji from sequences of base emoji characters.
/// For example, the various "family" emoji are encoded as sequences of man,
/// woman, or child emoji that are interleaved with zero width joiners.
///
/// This property corresponds to the "Join_Control" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isJoinControl: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_JOIN_CONTROL)
}
/// A Boolean value indicating whether the scalar requires special handling
/// for operations involving ordering, such as sorting and searching.
///
/// This property applies to a small number of spacing vowel letters occurring
/// in some Southeast Asian scripts like Thai and Lao, which use a visual
/// order display model. Such letters are stored in text ahead of
/// syllable-initial consonants.
///
/// This property corresponds to the "Logical_Order_Exception" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isLogicalOrderException: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_LOGICAL_ORDER_EXCEPTION)
}
/// A Boolean value indicating whether the scalar's letterform is
/// considered lowercase.
///
/// This property corresponds to the "Lowercase" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isLowercase: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_LOWERCASE)
}
/// A Boolean value indicating whether the scalar is one that naturally
/// appears in mathematical contexts.
///
/// The set of scalars for which this property is `true` includes mathematical
/// operators and symbols as well as specific Greek and Hebrew letter
/// variants that are categorized as symbols. Notably, it does _not_ contain
/// the standard digits or Latin/Greek letter blocks; instead, it contains the
/// mathematical Latin, Greek, and Arabic letters and numbers defined in the
/// Supplemental Multilingual Plane.
///
/// This property corresponds to the "Math" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isMath: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_MATH)
}
/// A Boolean value indicating whether the scalar is permanently reserved
/// for internal use.
///
/// This property corresponds to the "Noncharacter_Code_Point" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isNoncharacterCodePoint: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_NONCHARACTER_CODE_POINT)
}
/// A Boolean value indicating whether the scalar is one that is used in
/// writing to surround quoted text.
///
/// This property corresponds to the "Quotation_Mark" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isQuotationMark: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_QUOTATION_MARK)
}
/// A Boolean value indicating whether the scalar is a radical component of
/// CJK characters, Tangut characters, or Yi syllables.
///
/// These scalars are often the components of ideographic description
/// sequences, as defined by the `isIDSBinaryOperator` and
/// `isIDSTrinaryOperator` properties.
///
/// This property corresponds to the "Radical" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isRadical: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_RADICAL)
}
/// A Boolean value indicating whether the scalar has a "soft dot" that
/// disappears when a diacritic is placed over the scalar.
///
/// For example, "i" is soft dotted because the dot disappears when adding an
/// accent mark, as in "í".
///
/// This property corresponds to the "Soft_Dotted" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isSoftDotted: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_SOFT_DOTTED)
}
/// A Boolean value indicating whether the scalar is a punctuation symbol
/// that typically marks the end of a textual unit.
///
/// This property corresponds to the "Terminal_Punctuation" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isTerminalPunctuation: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_TERMINAL_PUNCTUATION)
}
/// A Boolean value indicating whether the scalar is one of the unified
/// CJK ideographs in the Unicode Standard.
///
/// This property is false for CJK punctuation and symbols, as well as for
/// compatibility ideographs (which canonically decompose to unified
/// ideographs).
///
/// This property corresponds to the "Unified_Ideograph" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isUnifiedIdeograph: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_UNIFIED_IDEOGRAPH)
}
/// A Boolean value indicating whether the scalar's letterform is
/// considered uppercase.
///
/// This property corresponds to the "Uppercase" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isUppercase: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_UPPERCASE)
}
/// A Boolean value indicating whether the scalar is a whitespace
/// character.
///
/// This property is `true` for scalars that are spaces, separator characters,
/// and other control characters that should be treated as whitespace for the
/// purposes of parsing text elements.
///
/// This property corresponds to the "White_Space" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isWhitespace: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_WHITE_SPACE)
}
/// A Boolean value indicating whether the scalar is one which is
/// recommended to be allowed to appear in a non-starting position in a
/// programming language identifier, with adjustments made for NFKC normalized
/// form.
///
/// The set of scalars `[:XID_Continue:]` closes the set `[:ID_Continue:]`
/// under NFKC normalization by removing any scalars whose normalized form is
/// not of the form `[:ID_Continue:]*`.
///
/// This property corresponds to the "XID_Continue" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isXIDContinue: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_XID_CONTINUE)
}
/// A Boolean value indicating whether the scalar is one which is
/// recommended to be allowed to appear in a starting position in a
/// programming language identifier, with adjustments made for NFKC normalized
/// form.
///
/// The set of scalars `[:XID_Start:]` closes the set `[:ID_Start:]` under
/// NFKC normalization by removing any scalars whose normalized form is not of
/// the form `[:ID_Start:] [:ID_Continue:]*`.
///
/// This property corresponds to the "XID_Start" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isXIDStart: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_XID_START)
}
/// A Boolean value indicating whether the scalar is a punctuation mark
/// that generally marks the end of a sentence.
///
/// This property corresponds to the "Sentence_Terminal" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isSentenceTerminal: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_S_TERM)
}
/// A Boolean value indicating whether the scalar is a variation selector.
///
/// Variation selectors allow rendering engines that support them to choose
/// different glyphs to display for a particular code point.
///
/// This property corresponds to the "Variation_Selector" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isVariationSelector: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_VARIATION_SELECTOR)
}
/// A Boolean value indicating whether the scalar is recommended to have
/// syntactic usage in patterns represented in source code.
///
/// This property corresponds to the "Pattern_Syntax" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isPatternSyntax: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_PATTERN_SYNTAX)
}
/// A Boolean value indicating whether the scalar is recommended to be
/// treated as whitespace when parsing patterns represented in source code.
///
/// This property corresponds to the "Pattern_White_Space" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isPatternWhitespace: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_PATTERN_WHITE_SPACE)
}
/// A Boolean value indicating whether the scalar is considered to be
/// either lowercase, uppercase, or titlecase.
///
/// Though similar in name, this property is *not* equivalent to
/// `changesWhenCaseMapped`. The set of scalars for which `isCased` is `true`
/// is a superset of those for which `changesWhenCaseMapped` is `true`. For
/// example, the Latin small capitals that are used by the International
/// Phonetic Alphabet have a case, but do not change when they are mapped to
/// any of the other cases.
///
/// This property corresponds to the "Cased" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isCased: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_CASED)
}
/// A Boolean value indicating whether the scalar is ignored for casing
/// purposes.
///
/// This property corresponds to the "Case_Ignorable" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var isCaseIgnorable: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_CASE_IGNORABLE)
}
/// A Boolean value indicating whether the scalar's normalized form differs
/// from the `lowercaseMapping` of each constituent scalar.
///
/// This property corresponds to the "Changes_When_Lowercased" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenLowercased: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_LOWERCASED)
}
/// A Boolean value indicating whether the scalar's normalized form differs
/// from the `uppercaseMapping` of each constituent scalar.
///
/// This property corresponds to the "Changes_When_Uppercased" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenUppercased: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_UPPERCASED)
}
/// A Boolean value indicating whether the scalar's normalized form differs
/// from the `titlecaseMapping` of each constituent scalar.
///
/// This property corresponds to the "Changes_When_Titlecased" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenTitlecased: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_TITLECASED)
}
/// A Boolean value indicating whether the scalar's normalized form differs
/// from the case-fold mapping of each constituent scalar.
///
/// This property corresponds to the "Changes_When_Casefolded" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenCaseFolded: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_CASEFOLDED)
}
/// A Boolean value indicating whether the scalar may change when it
/// undergoes case mapping.
///
/// This property is `true` whenever one or more of `changesWhenLowercased`,
/// `changesWhenUppercased`, or `changesWhenTitlecased` are `true`.
///
/// This property corresponds to the "Changes_When_Casemapped" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenCaseMapped: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_CASEMAPPED)
}
/// A Boolean value indicating whether the scalar is one that is not
/// identical to its NFKC case-fold mapping.
///
/// This property corresponds to the "Changes_When_NFKC_Casefolded" property
/// in the [Unicode Standard](http://www.unicode.org/versions/latest/).
public var changesWhenNFKCCaseFolded: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED)
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// FIXME: These properties were introduced in ICU 57, but Ubuntu 16.04 comes
// with ICU 55 so the values won't be correct there. Exclude them on
// non-Darwin platforms for now; bundling ICU with the toolchain would resolve
// this and other inconsistencies (https://bugs.swift.org/browse/SR-6076).
/// A Boolean value indicating whether the scalar has an emoji
/// presentation, whether or not it is the default.
///
/// This property is true for scalars that are rendered as emoji by default
/// and also for scalars that have a non-default emoji rendering when followed
/// by U+FE0F VARIATION SELECTOR-16. This includes some scalars that are not
/// typically considered to be emoji:
///
/// let scalars: [Unicode.Scalar] = ["😎", "$", "0"]
/// for s in scalars {
/// print(s, "-->", s.properties.isEmoji)
/// }
/// // 😎 --> true
/// // $ --> false
/// // 0 --> true
///
/// The final result is true because the ASCII digits have non-default emoji
/// presentations; some platforms render these with an alternate appearance.
///
/// Because of this behavior, testing `isEmoji` alone on a single scalar is
/// insufficient to determine if a unit of text is rendered as an emoji; a
/// correct test requires inspecting multiple scalars in a `Character`. In
/// addition to checking whether the base scalar has `isEmoji == true`, you
/// must also check its default presentation (see `isEmojiPresentation`) and
/// determine whether it is followed by a variation selector that would modify
/// the presentation.
///
/// This property corresponds to the "Emoji" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
@available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *)
public var isEmoji: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI)
}
/// A Boolean value indicating whether the scalar is one that should be
/// rendered with an emoji presentation, rather than a text presentation, by
/// default.
///
/// Scalars that have default to emoji presentation can be followed by
/// U+FE0E VARIATION SELECTOR-15 to request the text presentation of the
/// scalar instead. Likewise, scalars that default to text presentation can
/// be followed by U+FE0F VARIATION SELECTOR-16 to request the emoji
/// presentation.
///
/// This property corresponds to the "Emoji_Presentation" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
@available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *)
public var isEmojiPresentation: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_PRESENTATION)
}
/// A Boolean value indicating whether the scalar is one that can modify
/// a base emoji that precedes it.
///
/// The Fitzpatrick skin types are examples of emoji modifiers; they change
/// the appearance of the preceding emoji base (that is, a scalar for which
/// `isEmojiModifierBase` is true) by rendering it with a different skin tone.
///
/// This property corresponds to the "Emoji_Modifier" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
@available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *)
public var isEmojiModifier: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_MODIFIER)
}
/// A Boolean value indicating whether the scalar is one whose appearance
/// can be changed by an emoji modifier that follows it.
///
/// This property corresponds to the "Emoji_Modifier_Base" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
@available(macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1, *)
public var isEmojiModifierBase: Bool {
return _hasBinaryProperty(__swift_stdlib_UCHAR_EMOJI_MODIFIER_BASE)
}
#endif
}
/// Case mapping properties.
extension Unicode.Scalar.Properties {
// The type of ICU case conversion functions.
internal typealias _U_StrToX = (
/* dest */ UnsafeMutablePointer<__swift_stdlib_UChar>,
/* destCapacity */ Int32,
/* src */ UnsafePointer<__swift_stdlib_UChar>,
/* srcLength */ Int32,
/* locale */ UnsafePointer<Int8>,
/* pErrorCode */ UnsafeMutablePointer<__swift_stdlib_UErrorCode>
) -> Int32
/// Applies the given ICU string mapping to the scalar.
///
/// This function attempts first to write the mapping into a stack-based
/// UTF-16 buffer capable of holding 16 code units, which should be enough for
/// all current case mappings. In the event more space is needed, it will be
/// allocated on the heap.
internal func _applyMapping(_ u_strTo: _U_StrToX) -> String {
// Allocate 16 code units on the stack.
var fixedArray = _FixedArray16<UInt16>(allZeros: ())
let count: Int = fixedArray.withUnsafeMutableBufferPointer { buf in
return _scalar.withUTF16CodeUnits { utf16 in
var err = __swift_stdlib_U_ZERO_ERROR
let correctSize = u_strTo(
buf.baseAddress._unsafelyUnwrappedUnchecked,
Int32(buf.count),
utf16.baseAddress._unsafelyUnwrappedUnchecked,
Int32(utf16.count),
"",
&err)
guard err.isSuccess else {
fatalError("Unexpected error case-converting Unicode scalar.")
}
return Int(correctSize)
}
}
if _fastPath(count <= 16) {
fixedArray.count = count
return fixedArray.withUnsafeBufferPointer {
String._uncheckedFromUTF16($0)
}
}
// Allocate `count` code units on the heap.
let array = Array<UInt16>(unsafeUninitializedCapacity: count) {
buf, initializedCount in
_scalar.withUTF16CodeUnits { utf16 in
var err = __swift_stdlib_U_ZERO_ERROR
let correctSize = u_strTo(
buf.baseAddress._unsafelyUnwrappedUnchecked,
Int32(buf.count),
utf16.baseAddress._unsafelyUnwrappedUnchecked,
Int32(utf16.count),
"",
&err)
guard err.isSuccess else {
fatalError("Unexpected error case-converting Unicode scalar.")
}
_internalInvariant(count == correctSize, "inconsistent ICU behavior")
initializedCount = count
}
}
return array.withUnsafeBufferPointer {
String._uncheckedFromUTF16($0)
}
}
/// The lowercase mapping of the scalar.
///
/// This property is a `String`, not a `Unicode.Scalar` or `Character`,
/// because some mappings may transform a scalar into multiple scalars or
/// graphemes. For example, the character "İ" (U+0130 LATIN CAPITAL LETTER I
/// WITH DOT ABOVE) becomes two scalars (U+0069 LATIN SMALL LETTER I, U+0307
/// COMBINING DOT ABOVE) when converted to lowercase.
///
/// This property corresponds to the "Lowercase_Mapping" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var lowercaseMapping: String {
return _applyMapping(__swift_stdlib_u_strToLower)
}
/// The titlecase mapping of the scalar.
///
/// This property is a `String`, not a `Unicode.Scalar` or `Character`,
/// because some mappings may transform a scalar into multiple scalars or
/// graphemes. For example, the ligature "fi" (U+FB01 LATIN SMALL LIGATURE FI)
/// becomes "Fi" (U+0046 LATIN CAPITAL LETTER F, U+0069 LATIN SMALL LETTER I)
/// when converted to titlecase.
///
/// This property corresponds to the "Titlecase_Mapping" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var titlecaseMapping: String {
return _applyMapping { ptr, cap, src, len, locale, err in
return __swift_stdlib_u_strToTitle(ptr, cap, src, len, nil, locale, err)
}
}
/// The uppercase mapping of the scalar.
///
/// This property is a `String`, not a `Unicode.Scalar` or `Character`,
/// because some mappings may transform a scalar into multiple scalars or
/// graphemes. For example, the German letter "ß" (U+00DF LATIN SMALL LETTER
/// SHARP S) becomes "SS" (U+0053 LATIN CAPITAL LETTER S, U+0053 LATIN CAPITAL
/// LETTER S) when converted to uppercase.
///
/// This property corresponds to the "Uppercase_Mapping" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var uppercaseMapping: String {
return _applyMapping(__swift_stdlib_u_strToUpper)
}
}
extension Unicode {
/// A version of the Unicode Standard represented by its major and minor
/// components.
public typealias Version = (major: Int, minor: Int)
}
extension Unicode.Scalar.Properties {
/// The earliest version of the Unicode Standard in which the scalar was
/// assigned.
///
/// This value is `nil` for code points that have not yet been assigned.
///
/// This property corresponds to the "Age" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var age: Unicode.Version? {
var versionInfo: __swift_stdlib_UVersionInfo = (0, 0, 0, 0)
withUnsafeMutablePointer(to: &versionInfo) { tuplePtr in
tuplePtr.withMemoryRebound(to: UInt8.self, capacity: 4) {
versionInfoPtr in
__swift_stdlib_u_charAge(icuValue, versionInfoPtr)
}
}
guard versionInfo.0 != 0 else { return nil }
return (major: Int(versionInfo.0), minor: Int(versionInfo.1))
}
}
extension Unicode {
/// The most general classification of a Unicode scalar.
///
/// The general category of a scalar is its "first-order, most usual
/// categorization". It does not attempt to cover multiple uses of some
/// scalars, such as the use of letters to represent Roman numerals.
public enum GeneralCategory {
/// An uppercase letter.
///
/// This value corresponds to the category `Uppercase_Letter` (abbreviated
/// `Lu`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case uppercaseLetter
/// A lowercase letter.
///
/// This value corresponds to the category `Lowercase_Letter` (abbreviated
/// `Ll`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case lowercaseLetter
/// A digraph character whose first part is uppercase.
///
/// This value corresponds to the category `Titlecase_Letter` (abbreviated
/// `Lt`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case titlecaseLetter
/// A modifier letter.
///
/// This value corresponds to the category `Modifier_Letter` (abbreviated
/// `Lm`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case modifierLetter
/// Other letters, including syllables and ideographs.
///
/// This value corresponds to the category `Other_Letter` (abbreviated
/// `Lo`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case otherLetter
/// A non-spacing combining mark with zero advance width (abbreviated Mn).
///
/// This value corresponds to the category `Nonspacing_Mark` (abbreviated
/// `Mn`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case nonspacingMark
/// A spacing combining mark with positive advance width.
///
/// This value corresponds to the category `Spacing_Mark` (abbreviated `Mc`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case spacingMark
/// An enclosing combining mark.
///
/// This value corresponds to the category `Enclosing_Mark` (abbreviated
/// `Me`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case enclosingMark
/// A decimal digit.
///
/// This value corresponds to the category `Decimal_Number` (abbreviated
/// `Nd`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case decimalNumber
/// A letter-like numeric character.
///
/// This value corresponds to the category `Letter_Number` (abbreviated
/// `Nl`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case letterNumber
/// A numeric character of another type.
///
/// This value corresponds to the category `Other_Number` (abbreviated `No`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case otherNumber
/// A connecting punctuation mark, like a tie.
///
/// This value corresponds to the category `Connector_Punctuation`
/// (abbreviated `Pc`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case connectorPunctuation
/// A dash or hyphen punctuation mark.
///
/// This value corresponds to the category `Dash_Punctuation` (abbreviated
/// `Pd`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case dashPunctuation
/// An opening punctuation mark of a pair.
///
/// This value corresponds to the category `Open_Punctuation` (abbreviated
/// `Ps`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case openPunctuation
/// A closing punctuation mark of a pair.
///
/// This value corresponds to the category `Close_Punctuation` (abbreviated
/// `Pe`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case closePunctuation
/// An initial quotation mark.
///
/// This value corresponds to the category `Initial_Punctuation`
/// (abbreviated `Pi`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case initialPunctuation
/// A final quotation mark.
///
/// This value corresponds to the category `Final_Punctuation` (abbreviated
/// `Pf`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case finalPunctuation
/// A punctuation mark of another type.
///
/// This value corresponds to the category `Other_Punctuation` (abbreviated
/// `Po`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case otherPunctuation
/// A symbol of mathematical use.
///
/// This value corresponds to the category `Math_Symbol` (abbreviated `Sm`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case mathSymbol
/// A currency sign.
///
/// This value corresponds to the category `Currency_Symbol` (abbreviated
/// `Sc`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case currencySymbol
/// A non-letterlike modifier symbol.
///
/// This value corresponds to the category `Modifier_Symbol` (abbreviated
/// `Sk`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case modifierSymbol
/// A symbol of another type.
///
/// This value corresponds to the category `Other_Symbol` (abbreviated
/// `So`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case otherSymbol
/// A space character of non-zero width.
///
/// This value corresponds to the category `Space_Separator` (abbreviated
/// `Zs`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case spaceSeparator
/// A line separator, which is specifically (and only) U+2028 LINE
/// SEPARATOR.
///
/// This value corresponds to the category `Line_Separator` (abbreviated
/// `Zl`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case lineSeparator
/// A paragraph separator, which is specifically (and only) U+2029 PARAGRAPH
/// SEPARATOR.
///
/// This value corresponds to the category `Paragraph_Separator`
/// (abbreviated `Zp`) in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case paragraphSeparator
/// A C0 or C1 control code.
///
/// This value corresponds to the category `Control` (abbreviated `Cc`) in
/// the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case control
/// A format control character.
///
/// This value corresponds to the category `Format` (abbreviated `Cf`) in
/// the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case format
/// A surrogate code point.
///
/// This value corresponds to the category `Surrogate` (abbreviated `Cs`) in
/// the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case surrogate
/// A private-use character.
///
/// This value corresponds to the category `Private_Use` (abbreviated `Co`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case privateUse
/// A reserved unassigned code point or a non-character.
///
/// This value corresponds to the category `Unassigned` (abbreviated `Cn`)
/// in the
/// [Unicode Standard](https://unicode.org/reports/tr44/#General_Category_Values).
case unassigned
internal init(rawValue: __swift_stdlib_UCharCategory) {
switch rawValue {
case __swift_stdlib_U_UNASSIGNED: self = .unassigned
case __swift_stdlib_U_UPPERCASE_LETTER: self = .uppercaseLetter
case __swift_stdlib_U_LOWERCASE_LETTER: self = .lowercaseLetter
case __swift_stdlib_U_TITLECASE_LETTER: self = .titlecaseLetter
case __swift_stdlib_U_MODIFIER_LETTER: self = .modifierLetter
case __swift_stdlib_U_OTHER_LETTER: self = .otherLetter
case __swift_stdlib_U_NON_SPACING_MARK: self = .nonspacingMark
case __swift_stdlib_U_ENCLOSING_MARK: self = .enclosingMark
case __swift_stdlib_U_COMBINING_SPACING_MARK: self = .spacingMark
case __swift_stdlib_U_DECIMAL_DIGIT_NUMBER: self = .decimalNumber
case __swift_stdlib_U_LETTER_NUMBER: self = .letterNumber
case __swift_stdlib_U_OTHER_NUMBER: self = .otherNumber
case __swift_stdlib_U_SPACE_SEPARATOR: self = .spaceSeparator
case __swift_stdlib_U_LINE_SEPARATOR: self = .lineSeparator
case __swift_stdlib_U_PARAGRAPH_SEPARATOR: self = .paragraphSeparator
case __swift_stdlib_U_CONTROL_CHAR: self = .control
case __swift_stdlib_U_FORMAT_CHAR: self = .format
case __swift_stdlib_U_PRIVATE_USE_CHAR: self = .privateUse
case __swift_stdlib_U_SURROGATE: self = .surrogate
case __swift_stdlib_U_DASH_PUNCTUATION: self = .dashPunctuation
case __swift_stdlib_U_START_PUNCTUATION: self = .openPunctuation
case __swift_stdlib_U_END_PUNCTUATION: self = .closePunctuation
case __swift_stdlib_U_CONNECTOR_PUNCTUATION: self = .connectorPunctuation
case __swift_stdlib_U_OTHER_PUNCTUATION: self = .otherPunctuation
case __swift_stdlib_U_MATH_SYMBOL: self = .mathSymbol
case __swift_stdlib_U_CURRENCY_SYMBOL: self = .currencySymbol
case __swift_stdlib_U_MODIFIER_SYMBOL: self = .modifierSymbol
case __swift_stdlib_U_OTHER_SYMBOL: self = .otherSymbol
case __swift_stdlib_U_INITIAL_PUNCTUATION: self = .initialPunctuation
case __swift_stdlib_U_FINAL_PUNCTUATION: self = .finalPunctuation
default: fatalError("Unknown general category \(rawValue)")
}
}
}
}
// Internal helpers
extension Unicode.GeneralCategory {
internal var _isSymbol: Bool {
switch self {
case .mathSymbol, .currencySymbol, .modifierSymbol, .otherSymbol:
return true
default: return false
}
}
internal var _isPunctuation: Bool {
switch self {
case .connectorPunctuation, .dashPunctuation, .openPunctuation,
.closePunctuation, .initialPunctuation, .finalPunctuation,
.otherPunctuation:
return true
default: return false
}
}
}
extension Unicode.Scalar.Properties {
/// The general category (most usual classification) of the scalar.
///
/// This property corresponds to the "General_Category" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var generalCategory: Unicode.GeneralCategory {
let rawValue = __swift_stdlib_UCharCategory(
__swift_stdlib_UCharCategory.RawValue(
__swift_stdlib_u_getIntPropertyValue(
icuValue, __swift_stdlib_UCHAR_GENERAL_CATEGORY)))
return Unicode.GeneralCategory(rawValue: rawValue)
}
}
extension Unicode.Scalar.Properties {
internal func _scalarName(
_ choice: __swift_stdlib_UCharNameChoice
) -> String? {
var err = __swift_stdlib_U_ZERO_ERROR
let count = Int(__swift_stdlib_u_charName(icuValue, choice, nil, 0, &err))
guard count > 0 else { return nil }
// ICU writes a trailing null, so we have to save room for it as well.
var array = Array<UInt8>(repeating: 0, count: count + 1)
return array.withUnsafeMutableBufferPointer { bufPtr in
var err = __swift_stdlib_U_ZERO_ERROR
let correctSize = __swift_stdlib_u_charName(
icuValue,
choice,
UnsafeMutableRawPointer(bufPtr.baseAddress._unsafelyUnwrappedUnchecked)
.assumingMemoryBound(to: Int8.self),
Int32(bufPtr.count),
&err)
guard err.isSuccess else {
fatalError("Unexpected error case-converting Unicode scalar.")
}
_internalInvariant(count == correctSize, "inconsistent ICU behavior")
return String._fromASCII(
UnsafeBufferPointer(rebasing: bufPtr[..<count]))
}
}
/// The published name of the scalar.
///
/// Some scalars, such as control characters, do not have a value for this
/// property in the Unicode Character Database. For such scalars, this
/// property is `nil`.
///
/// This property corresponds to the "Name" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var name: String? {
return _scalarName(__swift_stdlib_U_UNICODE_CHAR_NAME)
}
/// The normative formal alias of the scalar.
///
/// The name of a scalar is immutable and never changed in future versions of
/// the Unicode Standard. The `nameAlias` property is provided to issue
/// corrections if a name was issued erroneously. For example, the `name` of
/// U+FE18 is "PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRAKCET"
/// (note that "BRACKET" is misspelled). The `nameAlias` property then
/// contains the corrected name.
///
/// If a scalar has no alias, this property is `nil`.
///
/// This property corresponds to the "Name_Alias" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var nameAlias: String? {
return _scalarName(__swift_stdlib_U_CHAR_NAME_ALIAS)
}
}
extension Unicode {
/// The classification of a scalar used in the Canonical Ordering Algorithm
/// defined by the Unicode Standard.
///
/// Canonical combining classes are used by the ordering algorithm to
/// determine if two sequences of combining marks should be considered
/// canonically equivalent (that is, identical in interpretation). Two
/// sequences are canonically equivalent if they are equal when sorting the
/// scalars in ascending order by their combining class.
///
/// For example, consider the sequence `"\u{0041}\u{0301}\u{0316}"` (LATIN
/// CAPITAL LETTER A, COMBINING ACUTE ACCENT, COMBINING GRAVE ACCENT BELOW).
/// The combining classes of these scalars have the numeric values 0, 230, and
/// 220, respectively. Sorting these scalars by their combining classes yields
/// `"\u{0041}\u{0316}\u{0301}"`, so two strings that differ only by the
/// ordering of those scalars would compare as equal:
///
/// let aboveBeforeBelow = "\u{0041}\u{0301}\u{0316}"
/// let belowBeforeAbove = "\u{0041}\u{0316}\u{0301}"
/// print(aboveBeforeBelow == belowBeforeAbove)
/// // Prints "true"
///
/// Named and Unnamed Combining Classes
/// ===================================
///
/// Canonical combining classes are defined in the Unicode Standard as
/// integers in the range `0...254`. For convenience, the standard assigns
/// symbolic names to a subset of these combining classes.
///
/// The `CanonicalCombiningClass` type conforms to `RawRepresentable` with a
/// raw value of type `UInt8`. You can create instances of the type by using
/// the static members named after the symbolic names, or by using the
/// `init(rawValue:)` initializer.
///
/// let overlayClass = Unicode.CanonicalCombiningClass(rawValue: 1)
/// let overlayClassIsOverlay = overlayClass == .overlay
/// // overlayClassIsOverlay == true
public struct CanonicalCombiningClass:
Comparable, Hashable, RawRepresentable
{
/// Base glyphs that occupy their own space and do not combine with others.
public static let notReordered = CanonicalCombiningClass(rawValue: 0)
/// Marks that overlay a base letter or symbol.
public static let overlay = CanonicalCombiningClass(rawValue: 1)
/// Diacritic nukta marks in Brahmi-derived scripts.
public static let nukta = CanonicalCombiningClass(rawValue: 7)
/// Combining marks that are attached to hiragana and katakana to indicate
/// voicing changes.
public static let kanaVoicing = CanonicalCombiningClass(rawValue: 8)
/// Diacritic virama marks in Brahmi-derived scripts.
public static let virama = CanonicalCombiningClass(rawValue: 9)
/// Marks attached at the bottom left.
public static let attachedBelowLeft = CanonicalCombiningClass(rawValue: 200)
/// Marks attached directly below.
public static let attachedBelow = CanonicalCombiningClass(rawValue: 202)
/// Marks attached directly above.
public static let attachedAbove = CanonicalCombiningClass(rawValue: 214)
/// Marks attached at the top right.
public static let attachedAboveRight =
CanonicalCombiningClass(rawValue: 216)
/// Distinct marks at the bottom left.
public static let belowLeft = CanonicalCombiningClass(rawValue: 218)
/// Distinct marks directly below.
public static let below = CanonicalCombiningClass(rawValue: 220)
/// Distinct marks at the bottom right.
public static let belowRight = CanonicalCombiningClass(rawValue: 222)
/// Distinct marks to the left.
public static let left = CanonicalCombiningClass(rawValue: 224)
/// Distinct marks to the right.
public static let right = CanonicalCombiningClass(rawValue: 226)
/// Distinct marks at the top left.
public static let aboveLeft = CanonicalCombiningClass(rawValue: 228)
/// Distinct marks directly above.
public static let above = CanonicalCombiningClass(rawValue: 230)
/// Distinct marks at the top right.
public static let aboveRight = CanonicalCombiningClass(rawValue: 232)
/// Distinct marks subtending two bases.
public static let doubleBelow = CanonicalCombiningClass(rawValue: 233)
/// Distinct marks extending above two bases.
public static let doubleAbove = CanonicalCombiningClass(rawValue: 234)
/// Greek iota subscript only (U+0345 COMBINING GREEK YPOGEGRAMMENI).
public static let iotaSubscript = CanonicalCombiningClass(rawValue: 240)
/// The raw integer value of the canonical combining class.
public let rawValue: UInt8
/// Creates a new canonical combining class with the given raw integer
/// value.
///
/// - Parameter rawValue: The raw integer value of the canonical combining
/// class.
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
public static func == (
lhs: CanonicalCombiningClass,
rhs: CanonicalCombiningClass
) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func < (
lhs: CanonicalCombiningClass,
rhs: CanonicalCombiningClass
) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
}
}
extension Unicode.Scalar.Properties {
/// The canonical combining class of the scalar.
///
/// This property corresponds to the "Canonical_Combining_Class" property in
/// the [Unicode Standard](http://www.unicode.org/versions/latest/).
public var canonicalCombiningClass: Unicode.CanonicalCombiningClass {
let rawValue = UInt8(__swift_stdlib_u_getIntPropertyValue(
icuValue, __swift_stdlib_UCHAR_CANONICAL_COMBINING_CLASS))
return Unicode.CanonicalCombiningClass(rawValue: rawValue)
}
}
extension Unicode {
/// The numeric type of a scalar.
///
/// Scalars with a non-nil numeric type include numbers, fractions, numeric
/// superscripts and subscripts, and circled or otherwise decorated number
/// glyphs.
///
/// Some letterlike scalars used in numeric systems, such as Greek or Latin
/// letters, do not have a non-nil numeric type, in order to prevent programs
/// from incorrectly interpreting them as numbers in non-numeric contexts.
public enum NumericType {
/// A digit that is commonly understood to form base-10 numbers.
///
/// Specifically, scalars have this numeric type if they occupy a contiguous
/// range of code points representing numeric values `0...9`.
case decimal
/// A digit that does not meet the requirements of the `decimal` numeric
/// type.
///
/// Scalars with this numeric type are often those that represent a decimal
/// digit but would not typically be used to write a base-10 number, such
/// as "④" (U+2463 CIRCLED DIGIT FOUR).
///
/// As of Unicode 6.3, any new scalars that represent numbers but do not
/// meet the requirements of `decimal` will have numeric type `numeric`,
/// and programs can treat `digit` and `numeric` equivalently.
case digit
/// A digit that does not meet the requirements of the `decimal` numeric
/// type or a non-digit numeric value.
///
/// This numeric type includes fractions such as "⅕" (U+2155 VULGAR
/// FRACITON ONE FIFTH), numerical CJK ideographs like "兆" (U+5146 CJK
/// UNIFIED IDEOGRAPH-5146), and other scalars that are not decimal digits
/// used positionally in the writing of base-10 numbers.
///
/// As of Unicode 6.3, any new scalars that represent numbers but do not
/// meet the requirements of `decimal` will have numeric type `numeric`,
/// and programs can treat `digit` and `numeric` equivalently.
case numeric
internal init?(rawValue: __swift_stdlib_UNumericType) {
switch rawValue {
case __swift_stdlib_U_NT_NONE: return nil
case __swift_stdlib_U_NT_DECIMAL: self = .decimal
case __swift_stdlib_U_NT_DIGIT: self = .digit
case __swift_stdlib_U_NT_NUMERIC: self = .numeric
default: fatalError("Unknown numeric type \(rawValue)")
}
}
}
}
/// Numeric properties of scalars.
extension Unicode.Scalar.Properties {
/// The numeric type of the scalar.
///
/// For scalars that represent a number, `numericType` is the numeric type
/// of the scalar. For all other scalars, this property is `nil`.
///
/// let scalars: [Unicode.Scalar] = ["4", "④", "⅕", "X"]
/// for scalar in scalars {
/// print(scalar, "-->", scalar.properties.numericType)
/// }
/// // 4 --> Optional(Swift.Unicode.NumericType.decimal)
/// // ④ --> Optional(Swift.Unicode.NumericType.digit)
/// // ⅕ --> Optional(Swift.Unicode.NumericType.numeric)
/// // X --> nil
///
/// This property corresponds to the "Numeric_Type" property in the
/// [Unicode Standard](http://www.unicode.org/versions/latest/).
public var numericType: Unicode.NumericType? {
let rawValue = __swift_stdlib_UNumericType(
__swift_stdlib_UNumericType.RawValue(
__swift_stdlib_u_getIntPropertyValue(
icuValue, __swift_stdlib_UCHAR_NUMERIC_TYPE)))
return Unicode.NumericType(rawValue: rawValue)
}
/// The numeric value of the scalar.
///
/// For scalars that represent a numeric value, `numericValue` is the whole
/// or fractional value. For all other scalars, this property is `nil`.
///
/// let scalars: [Unicode.Scalar] = ["4", "④", "⅕", "X"]
/// for scalar in scalars {
/// print(scalar, "-->", scalar.properties.numericValue)
/// }
/// // 4 --> Optional(4.0)
/// // ④ --> Optional(4.0)
/// // ⅕ --> Optional(0.2)
/// // X --> nil
///
/// This property corresponds to the "Numeric_Value" property in the [Unicode
/// Standard](http://www.unicode.org/versions/latest/).
public var numericValue: Double? {
let icuNoNumericValue: Double = -123456789
let result = __swift_stdlib_u_getNumericValue(icuValue)
return result != icuNoNumericValue ? result : nil
}
}
| apache-2.0 |
wireapp/wire-ios-data-model | Tests/Source/Model/ConversationList/ZMConversationListDirectoryTests+Teams.swift | 1 | 4459 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
final class ZMConversationListDirectoryTests_Teams: ZMBaseManagedObjectTest {
var team: Team!
var otherTeam: Team!
var teamConversation1: ZMConversation!
var teamConversation2: ZMConversation!
var archivedTeamConversation: ZMConversation!
var clearedTeamConversation: ZMConversation!
var otherTeamConversation: ZMConversation!
var otherTeamArchivedConversation: ZMConversation!
var conversationWithoutTeam: ZMConversation!
override func setUp() {
super.setUp()
team = Team.insertNewObject(in: uiMOC)
team.remoteIdentifier = .create()
otherTeam = Team.insertNewObject(in: uiMOC)
otherTeam.remoteIdentifier = .create()
teamConversation1 = createGroupConversation(in: team)
teamConversation2 = createGroupConversation(in: team)
otherTeamConversation = createGroupConversation(in: otherTeam)
archivedTeamConversation = createGroupConversation(in: team, archived: true)
otherTeamArchivedConversation = createGroupConversation(in: otherTeam, archived: true)
clearedTeamConversation = createGroupConversation(in: team, archived: true)
clearedTeamConversation.clearedTimeStamp = clearedTeamConversation.lastServerTimeStamp
conversationWithoutTeam = createGroupConversation(in: nil)
}
override func tearDown() {
team = nil
otherTeam = nil
teamConversation1 = nil
teamConversation2 = nil
archivedTeamConversation = nil
clearedTeamConversation = nil
otherTeamConversation = nil
otherTeamArchivedConversation = nil
conversationWithoutTeam = nil
super.tearDown()
}
func testThatItReturnsConversationsInATeam() {
// given
let sut = uiMOC.conversationListDirectory()
// when
let conversations = sut.conversationsIncludingArchived
// then
XCTAssertEqual(conversations.setValue, [teamConversation1, teamConversation2, archivedTeamConversation, conversationWithoutTeam, otherTeamConversation, otherTeamArchivedConversation])
}
func testThatItReturnsArchivedConversationsInATeam() {
// given
let sut = uiMOC.conversationListDirectory()
// when
let conversations = sut.archivedConversations
// then
XCTAssertEqual(conversations.setValue, [archivedTeamConversation, otherTeamArchivedConversation])
}
func testThatItReturnsClearedConversationsInATeam() {
// given
let sut = uiMOC.conversationListDirectory()
// when
let conversations = sut.clearedConversations
// then
XCTAssertEqual(conversations.setValue, [clearedTeamConversation])
}
func testThatItDoesNotIncludeClearedConversationsInConversationsIncludingArchived() {
// given
let sut = uiMOC.conversationListDirectory()
// when
let conversations = sut.conversationsIncludingArchived
// then
XCTAssertFalse(conversations.setValue.contains(clearedTeamConversation))
}
// MARK: - Helper
func createGroupConversation(in team: Team?, archived: Bool = false) -> ZMConversation {
let conversation = ZMConversation.insertNewObject(in: uiMOC)
conversation.lastServerTimeStamp = Date()
conversation.lastReadServerTimeStamp = conversation.lastServerTimeStamp
conversation.remoteIdentifier = .create()
conversation.team = team
conversation.isArchived = archived
conversation.conversationType = .group
return conversation
}
}
fileprivate extension ZMConversationList {
var setValue: Set<ZMConversation> {
return Set(self as! [ZMConversation])
}
}
| gpl-3.0 |
goldenplan/Pattern-on-Swift | Visitor.playground/Contents.swift | 1 | 1396 | //: Playground - noun: a place where people can play
// Visitor pattern
import Cocoa
protocol Visitor{
func visitElementA(elementA: ElementA)
func visitElementB(elementB: ElementB)
}
class ConcreteVisitor1: Visitor{
func visitElementA(elementA: ElementA) {
elementA.operationA()
}
func visitElementB(elementB: ElementB) {
elementB.operationB()
}
}
class ConcreteVisitor2: Visitor{
func visitElementA(elementA: ElementA) {
elementA.operationA()
}
func visitElementB(elementB: ElementB) {
elementB.operationB()
}
}
protocol Element{
func accept(v: Visitor)
}
class ElementA: Element{
func accept(v: Visitor) {
v.visitElementA(elementA: self)
}
func operationA(){
print("operationA")
}
}
class ElementB: Element{
func accept(v: Visitor) {
v.visitElementB(elementB: self)
}
func operationB(){
print("operationB")
}
}
class ObjectStructure{
var elements = [Element]()
func add(element: Element){
elements.append(element)
}
func fooForAll(visitor: Visitor){
for element in elements{
element.accept(v: visitor)
}
}
}
let structure = ObjectStructure()
structure.add(element: ElementA())
structure.add(element: ElementB())
structure.fooForAll(visitor: ConcreteVisitor1())
| mit |
sha05301239/SHA_DYZB | SHA_DYZB/SHA_DYZB/Classes/Main/View/PageTitleView.swift | 1 | 6540 | //
// PageTitleView.swift
// SHA_DYZB
//
// Created by sha0530 on 17/2/7.
// Copyright © 2017年 鼎. All rights reserved.
//
import UIKit
//代理定义协议
protocol PageTitleViewDelegate : class{
func pageTitleView(_ titleView : PageTitleView, selectedIndex index : Int)
}
//定义常量
private let kScrollerLineH : CGFloat = 2
private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85)
private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0)
//MARK: - 定义类
class PageTitleView: UIView {
//定义属性
fileprivate var titles:[String]
fileprivate var currentIndex : Int = 0
weak var delegate : PageTitleViewDelegate?
//MARK: - 懒加载属性
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
//MARK: - 懒加载存放Label的数组
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
//MARK: - 懒加载底部滚动线条
fileprivate lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.orange
return scrollLine
}()
//MARK: - 自定义构造函数
init(frame: CGRect,titles: [String]) {
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//设置UI界面
extension PageTitleView{
func setupUI(){
//1.添加scrollView
addSubview(scrollView)
scrollView.frame = bounds
//2.添加title对应的Label
setipTitleLabels()
//3.设置label底部线条和滑块
setupbottomMenuAndScrollLine()
}
private func setipTitleLabels(){
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height - kScrollerLineH
let labelY : CGFloat = 0
for (index,title) in titles.enumerated(){
//1.创建label
let label = UILabel()
//2.设置label的属性
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
//3.设置label的frame
let labelX : CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
//4.将label添加到scrollerView上
scrollView.addSubview(label)
titleLabels.append(label)
//5.给label添加手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action:#selector(self.titleLabelClick(_:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupbottomMenuAndScrollLine(){
//添加底线
let bottonLine = UIView()
bottonLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottonLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottonLine)
//2.添加scrollerLine
//2.1获取第一个label
guard let firstLabel = titleLabels.first else{ return }
firstLabel.textColor = UIColor.orange
//2.2设置scrollerLine的属性
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollerLineH, width: firstLabel.frame.width, height: kScrollerLineH)
}
}
//mark - 监听label点击
extension PageTitleView{
@objc fileprivate func titleLabelClick(_ tapGes : UITapGestureRecognizer){
//1.获取当前label下表值
guard let currentLabel = tapGes.view as? UILabel else {return}
//2.获取之前的label
let oldLabel = titleLabels[currentIndex]
//3.切换文字颜色
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
//4.保存最新label
currentIndex = currentLabel.tag
//5.滚动条位置发生改变
let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width
UIView.animate(withDuration: 0.12) {
self.scrollLine.frame.origin.x = scrollLineX
}
//6.通知代理做事情
delegate?.pageTitleView(self, selectedIndex: currentIndex)
}
}
//MARK: - 对外公开方法,改变title选中状态
extension PageTitleView{
func setTitleWithProgress(progress : CGFloat,sourceIndex: Int,targetIndex: Int){
//1.取出sourceLabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
//2.处理滑块的逻辑
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
// 3.颜色的渐变(复杂)
// 3.1.取出变化的范围
let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2)
// 3.2.变化sourceLabel
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress)
// 3.2.变化targetLabel
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress)
//4.记录最新的index
currentIndex = targetIndex
}
}
| mit |
mnisn/zhangchu | zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommendTodayCell.swift | 1 | 4324 | //
// RecommendTodayCell.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/27.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class RecommendTodayCell: UITableViewCell {
var clickClosure:RecipClickClosure?
var listModle:RecipeRecommendWidgetList? {
didSet{
showData()
}
}
func showData()
{
if listModle?.widget_data?.count > 0
{
for i in 0 ..< 3
{
//图片
if i * 4 < listModle?.widget_data?.count
{
let imgData = listModle?.widget_data![i * 4]
if imgData?.type == "image"
{
let tmpView = contentView.viewWithTag(100 + i)
if tmpView?.isKindOfClass(UIImageView) == true
{
let imgView = tmpView as! UIImageView
imgView.kf_setImageWithURL(NSURL(string: (imgData?.content)!), placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
//标题
if i * 4 + 2 < listModle?.widget_data?.count
{
let textTitleData = listModle?.widget_data![i * 4 + 2]
if textTitleData!.type == "text"
{
let tmpView = contentView.viewWithTag(200 + i)
if tmpView?.isKindOfClass(UILabel) == true
{
let textTitleLabel = tmpView as! UILabel
textTitleLabel.text = textTitleData?.content
}
}
}
//内容
if i * 4 + 3 < listModle?.widget_data?.count
{
let textConData = listModle?.widget_data![i * 4 + 3]
if textConData!.type == "text"
{
let tmpView = contentView.viewWithTag(300 + i)
if tmpView?.isKindOfClass(UILabel) == true
{
let textConLabel = tmpView as! UILabel
textConLabel.text = textConData?.content
}
}
}
}
}
}
//点击进入详情
@IBAction func btnClick(sender: UIButton)
{
let index = sender.tag - 400
if index * 4 < listModle?.widget_data?.count
{
let imgData = listModle?.widget_data![index * 4]
if imgData?.type == "image"
{
if clickClosure != nil && imgData?.link != nil
{
clickClosure!((imgData?.link)!)
}
}
}
}
//点击播放视频
@IBAction func playBtnClick(sender: UIButton)
{
let index = sender.tag - 500
if index * 4 + 1 < listModle?.widget_data?.count
{
let videoData = listModle?.widget_data![index * 4 + 1]
if videoData?.type == "video"
{
if clickClosure != nil && videoData?.content != nil
{
clickClosure!((videoData?.content)!)
}
}
}
}
//创建cell
class func createTodayCell(tableView: UITableView, atIndexPath indexPath:NSIndexPath, listModel:RecipeRecommendWidgetList?) ->RecommendTodayCell
{
let cellID = "recommendTodayCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? RecommendTodayCell
if cell == nil
{
cell = NSBundle.mainBundle().loadNibNamed("RecommendTodayCell", owner: nil, options: nil).last as? RecommendTodayCell
}
cell?.listModle = listModel!
return cell!
}
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
}
}
| mit |
bignerdranch/Deferred | Tests/DeferredTests/FutureAsyncTests.swift | 1 | 1096 | //
// FutureAsyncTests.swift
// Deferred
//
// Created by Zachary Waldowski on 6/3/18.
// Copyright © 2018 Big Nerd Ranch. Licensed under MIT.
//
import XCTest
import Dispatch
import Deferred
class FutureAsyncTests: XCTestCase {
static let allTests: [(String, (FutureAsyncTests) -> () throws -> Void)] = [
("testThatPeekingBeforeStartingReturnsNil", testThatPeekingBeforeStartingReturnsNil)
]
private var queue: DispatchQueue!
override func setUp() {
super.setUp()
queue = DispatchQueue(label: "FutureAsyncTests")
queue.suspend()
}
override func tearDown() {
queue = nil
super.tearDown()
}
func testThatPeekingBeforeStartingReturnsNil() {
let future = Future<Int>.async(upon: queue) { 1 }
XCTAssertNil(future.peek())
queue.resume()
let expect = expectation(description: "future fulfils")
future.upon(queue) { (result) in
XCTAssertEqual(result, 1)
expect.fulfill()
}
wait(for: [ expect ], timeout: shortTimeout)
}
}
| mit |
sebk/BeaconMonitor | BeaconMonitor/BeaconSender.swift | 1 | 2157 | //
// BeaconSender.swift
// BeaconMonitor
//
// Created by Sebastian Kruschwitz on 16.09.15.
// Copyright © 2015 seb. All rights reserved.
//
import Foundation
import CoreLocation
import CoreBluetooth
public class BeaconSender: NSObject {
public static let sharedInstance = BeaconSender()
fileprivate var _region: CLBeaconRegion?
fileprivate var _peripheralManager: CBPeripheralManager!
fileprivate var _uuid = ""
fileprivate var _identifier = ""
public func startSending(uuid: String, majorID: CLBeaconMajorValue, minorID: CLBeaconMinorValue, identifier: String) {
_uuid = uuid
_identifier = identifier
stopSending() //stop sending when it's active
// create the region that will be used to send
_region = CLBeaconRegion(
proximityUUID: UUID(uuidString: uuid)!,
major: majorID,
minor: minorID,
identifier: identifier)
_peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
}
open func stopSending() {
_peripheralManager?.stopAdvertising()
}
}
//MARK: - CBPeripheralManagerDelegate
extension BeaconSender: CBPeripheralManagerDelegate {
public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
if peripheral.state == .poweredOn {
let data = ((_region?.peripheralData(withMeasuredPower: nil))! as NSDictionary) as! Dictionary<String, Any>
peripheral.startAdvertising(data)
print("Powered On -> start advertising")
}
else if peripheral.state == .poweredOff {
peripheral.stopAdvertising()
print("Powered Off -> stop advertising")
}
}
public func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
if let error = error {
print("Error starting advertising: \(error)")
}
else {
print("Did start advertising")
}
}
}
| mit |
nessBautista/iOSBackup | iOSNotebook/Pods/Outlaw/Sources/Outlaw/ValueWithContext.swift | 2 | 676 | //
// ValueWithContext.swift
// Outlaw
//
// Created by Brian Mullen on 11/15/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
public protocol ValueWithContext {
associatedtype Context
associatedtype ValueType = Self
static func value(from object: Any, using context: Context) throws -> ValueType
}
extension ValueWithContext {
public static func value(from object: Any, using context: Context) throws -> ValueType {
guard let objectValue = object as? ValueType else {
throw OutlawError.typeMismatch(expected: ValueType.self, actual: type(of: object))
}
return objectValue
}
}
| cc0-1.0 |
larryhou/swift | QRCode/QRCode/AztecImageView.swift | 1 | 1236 | //
// AztecImageView.swift
// QRCode
//
// Created by larryhou on 23/12/2015.
// Copyright © 2015 larryhou. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
class AztecImageView: GeneratorImageView {
@IBInspectable
var inputMessage: String = "larryhou" {
didSet { drawAztecImage() }
}
@IBInspectable
var inputCompactStyle: Bool = false {
didSet { drawAztecImage() }
}
@IBInspectable
var inputCorrectionLevel: Float = 50.0 // 23.0[5.0,95.0]
{
didSet { drawAztecImage() }
}
@IBInspectable
var inputLayers: Float = 1.0 // 0.0[1.0,32.0]
{
didSet { drawAztecImage() }
}
func drawAztecImage() {
let filter = CIFilter(name: "CIAztecCodeGenerator")
let data = inputMessage.data(using: .utf8)
filter?.setValue(data, forKey: "inputMessage")
// filter?.setValue(inputLayers, forKey: "inputLayers")
// filter?.setValue(inputCompactStyle, forKey: "inputCompactStyle")
filter?.setValue(inputCorrectionLevel, forKey: "inputCorrectionLevel")
self.image = stripOutputImage(of: filter)
}
override func prepareForInterfaceBuilder() {
drawAztecImage()
}
}
| mit |
collinsrj/QRCodeReader | QRCodeReader/AppDelegate.swift | 1 | 273 | //
// AppDelegate.swift
// QRCodeReader
//
// Created by Robert Collins on 30/11/2015.
// Copyright © 2015 Robert Collins. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| apache-2.0 |
King-Wizard/UITextField-Shake-Swift | UITextFieldShakeSwiftDemo/UITextFieldShakeSwiftDemoTests/UITextFieldShakeSwiftDemoTests.swift | 1 | 862 |
import XCTest
@testable import UITextFieldShakeSwiftDemo
class UITextFieldShakeSwiftDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
xedin/swift | test/decl/subscript/subscripting.swift | 2 | 14153 | // RUN: %target-typecheck-verify-swift
struct X { } // expected-note * {{did you mean 'X'?}}
// Simple examples
struct X1 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored
}
mutating
set {
stored = newValue
}
}
}
struct X2 {
var stored : Int
subscript (i : Int) -> Int {
get {
return stored + i
}
set(v) {
stored = v - i
}
}
}
struct X3 {
var stored : Int
subscript (_ : Int) -> Int {
get {
return stored
}
set(v) {
stored = v
}
}
}
struct X4 {
var stored : Int
subscript (i : Int, j : Int) -> Int {
get {
return stored + i + j
}
set(v) {
stored = v + i - j
}
}
}
struct X5 {
static var stored : Int = 1
static subscript (i : Int) -> Int {
get {
return stored + i
}
set {
stored = newValue - i
}
}
}
class X6 {
static var stored : Int = 1
class subscript (i : Int) -> Int {
get {
return stored + i
}
set {
stored = newValue - i
}
}
}
protocol XP1 {
subscript (i : Int) -> Int { get set }
static subscript (i : Int) -> Int { get set }
}
// Semantic errors
struct Y1 {
var x : X
subscript(i: Int) -> Int {
get {
return x // expected-error{{cannot convert return expression of type 'X' to return type 'Int'}}
}
set {
x = newValue // expected-error{{cannot assign value of type 'Int' to type 'X'}}
}
}
}
struct Y2 {
subscript(idx: Int) -> TypoType { // expected-error {{use of undeclared type 'TypoType'}}
get { repeat {} while true }
set {}
}
}
class Y3 {
subscript(idx: Int) -> TypoType { // expected-error {{use of undeclared type 'TypoType'}}
get { repeat {} while true }
set {}
}
}
class Y4 {
var x = X()
static subscript(idx: Int) -> X {
get { return x } // expected-error {{instance member 'x' cannot be used on type 'Y4'}}
set {}
}
}
class Y5 {
static var x = X()
subscript(idx: Int) -> X {
get { return x } // expected-error {{static member 'x' cannot be used on instance of type 'Y5'}}
set {}
}
}
protocol ProtocolGetSet0 {
subscript(i: Int) -> Int {} // expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolGetSet1 {
subscript(i: Int) -> Int { get }
}
protocol ProtocolGetSet2 {
subscript(i: Int) -> Int { set } // expected-error {{subscript with a setter must also have a getter}}
}
protocol ProtocolGetSet3 {
subscript(i: Int) -> Int { get set }
}
protocol ProtocolGetSet4 {
subscript(i: Int) -> Int { set get }
}
protocol ProtocolWillSetDidSet1 {
subscript(i: Int) -> Int { willSet } // expected-error {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolWillSetDidSet2 {
subscript(i: Int) -> Int { didSet } // expected-error {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolWillSetDidSet3 {
subscript(i: Int) -> Int { willSet didSet } // expected-error 2 {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}}
}
protocol ProtocolWillSetDidSet4 {
subscript(i: Int) -> Int { didSet willSet } // expected-error 2 {{expected get or set in a protocol property}} expected-error {{subscript declarations must have a getter}}
}
class DidSetInSubscript {
subscript(_: Int) -> Int {
didSet { // expected-error {{'didSet' is not allowed in subscripts}}
print("eek")
}
get {}
}
}
class WillSetInSubscript {
subscript(_: Int) -> Int {
willSet { // expected-error {{'willSet' is not allowed in subscripts}}
print("eek")
}
get {}
}
}
subscript(i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
func f() { // expected-note * {{did you mean 'f'?}}
subscript (i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}}
get {}
}
}
struct NoSubscript { }
struct OverloadedSubscript {
subscript(i: Int) -> Int {
get {
return i
}
set {}
}
subscript(i: Int, j: Int) -> Int {
get { return i }
set {}
}
}
struct RetOverloadedSubscript {
subscript(i: Int) -> Int { // expected-note {{found this candidate}}
get { return i }
set {}
}
subscript(i: Int) -> Float { // expected-note {{found this candidate}}
get { return Float(i) }
set {}
}
}
struct MissingGetterSubscript1 {
subscript (i : Int) -> Int {
} // expected-error {{subscript must have accessors specified}}
}
struct MissingGetterSubscript2 {
subscript (i : Int, j : Int) -> Int {
set {} // expected-error{{subscript with a setter must also have a getter}}
}
}
func test_subscript(_ x2: inout X2, i: Int, j: Int, value: inout Int, no: NoSubscript,
ovl: inout OverloadedSubscript, ret: inout RetOverloadedSubscript) {
no[i] = value // expected-error{{value of type 'NoSubscript' has no subscripts}}
value = x2[i]
x2[i] = value
value = ovl[i]
ovl[i] = value
value = ovl[i, j]
ovl[i, j] = value
value = ovl[(i, j, i)] // expected-error{{cannot convert value of type '(Int, Int, Int)' to expected argument type 'Int'}}
ret[i] // expected-error{{ambiguous use of 'subscript(_:)'}}
value = ret[i]
ret[i] = value
X5[i] = value
value = X5[i]
}
func test_proto_static<XP1Type: XP1>(
i: Int, value: inout Int,
existential: inout XP1,
generic: inout XP1Type
) {
existential[i] = value
value = existential[i]
type(of: existential)[i] = value
value = type(of: existential)[i]
generic[i] = value
value = generic[i]
XP1Type[i] = value
value = XP1Type[i]
}
func subscript_rvalue_materialize(_ i: inout Int) {
i = X1(stored: 0)[i]
}
func subscript_coerce(_ fn: ([UnicodeScalar], [UnicodeScalar]) -> Bool) {}
func test_subscript_coerce() {
subscript_coerce({ $0[$0.count-1] < $1[$1.count-1] })
}
struct no_index {
subscript () -> Int { return 42 }
func test() -> Int {
return self[]
}
}
struct tuple_index {
subscript (x : Int, y : Int) -> (Int, Int) { return (x, y) }
func test() -> (Int, Int) {
return self[123, 456]
}
}
struct MutableComputedGetter {
var value: Int
subscript(index: Int) -> Int {
value = 5 // expected-error{{cannot assign to property: 'self' is immutable}}
return 5
}
var getValue : Int {
value = 5 // expected-error {{cannot assign to property: 'self' is immutable}}
return 5
}
}
struct MutableSubscriptInGetter {
var value: Int
subscript(index: Int) -> Int {
get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}}
value = 5 // expected-error{{cannot assign to property: 'self' is immutable}}
return 5
}
}
}
protocol Protocol {}
protocol RefinedProtocol: Protocol {}
class SuperClass {}
class SubClass: SuperClass {}
class SubSubClass: SubClass {}
class ClassConformingToProtocol: Protocol {}
class ClassConformingToRefinedProtocol: RefinedProtocol {}
struct GenSubscriptFixitTest {
subscript<T>(_ arg: T) -> Bool { return true } // expected-note {{declared here}}
}
func testGenSubscriptFixit(_ s0: GenSubscriptFixitTest) {
_ = s0.subscript("hello")
// expected-error@-1 {{value of type 'GenSubscriptFixitTest' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{27-28=]}}
}
struct SubscriptTest1 {
subscript(keyword:String) -> Bool { return true }
// expected-note@-1 4 {{found this candidate}}
subscript(keyword:String) -> String? {return nil }
// expected-note@-1 4 {{found this candidate}}
subscript(arg: SubClass) -> Bool { return true } // expected-note {{declared here}}
subscript(arg: Protocol) -> Bool { return true } // expected-note 2 {{declared here}}
subscript(arg: (foo: Bool, bar: (Int, baz: SubClass)), arg2: String) -> Bool { return true }
// expected-note@-1 2 {{declared here}}
}
func testSubscript1(_ s1 : SubscriptTest1) {
let _ : Int = s1["hello"] // expected-error {{ambiguous subscript with base type 'SubscriptTest1' and index type 'String'}}
if s1["hello"] {}
_ = s1.subscript((true, (5, SubClass())), "hello")
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{52-53=]}}
_ = s1.subscript((true, (5, baz: SubSubClass())), "hello")
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{60-61=]}}
_ = s1.subscript((fo: true, (5, baz: SubClass())), "hello")
// expected-error@-1 {{cannot convert value of type '(fo: Bool, (Int, baz: SubClass))' to expected argument type '(foo: Bool, bar: (Int, baz: SubClass))'}}
_ = s1.subscript(SubSubClass())
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{33-34=]}}
_ = s1.subscript(ClassConformingToProtocol())
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{47-48=]}}
_ = s1.subscript(ClassConformingToRefinedProtocol())
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{54-55=]}}
_ = s1.subscript(true)
// expected-error@-1 {{cannot invoke 'subscript' with an argument list of type '(Bool)'}}
// expected-note@-2 {{overloads for 'subscript' exist with these partially matching parameter lists: (Protocol), (String), (SubClass)}}
_ = s1.subscript(SuperClass())
// expected-error@-1 {{cannot invoke 'subscript' with an argument list of type '(SuperClass)'}}
// expected-note@-2 {{overloads for 'subscript' exist with these partially matching parameter lists: (Protocol), (String), (SubClass)}}
_ = s1.subscript("hello")
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}}
_ = s1.subscript("hello"
// expected-error@-1 {{value of type 'SubscriptTest1' has no property or method named 'subscript'; did you mean to use the subscript operator?}}
// expected-note@-2 {{to match this opening '('}}
let _ = s1["hello"]
// expected-error@-1 {{ambiguous use of 'subscript(_:)'}}
// expected-error@-2 {{expected ')' in expression list}}
}
struct SubscriptTest2 {
subscript(a : String, b : Int) -> Int { return 0 }
// expected-note@-1 {{declared here}}
subscript(a : String, b : String) -> Int { return 0 }
}
func testSubscript1(_ s2 : SubscriptTest2) {
_ = s2["foo"] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an argument of type 'String'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}}
let a = s2["foo", 1.0] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an argument of type '(String, Double)'}}
// expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}}
_ = s2.subscript("hello", 6)
// expected-error@-1 {{value of type 'SubscriptTest2' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{30-31=]}}
let b = s2[1, "foo"] // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
// rdar://problem/27449208
let v: (Int?, [Int]?) = (nil [17]) // expected-error {{cannot subscript a nil literal value}}
}
// sr-114 & rdar://22007370
class Foo {
subscript(key: String) -> String { // expected-note {{'subscript(_:)' previously declared here}}
get { a } // expected-error {{use of unresolved identifier 'a'}}
set { b } // expected-error {{use of unresolved identifier 'b'}}
}
subscript(key: String) -> String { // expected-error {{invalid redeclaration of 'subscript(_:)'}}
get { _ = 0; a } // expected-error {{use of unresolved identifier 'a'}}
set { b } // expected-error {{use of unresolved identifier 'b'}}
}
}
// <rdar://problem/23952125> QoI: Subscript in protocol with missing {}, better diagnostic please
protocol r23952125 {
associatedtype ItemType
var count: Int { get }
subscript(index: Int) -> ItemType // expected-error {{subscript in protocol must have explicit { get } or { get set } specifier}} {{36-36= { get <#set#> \}}}
var c : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-14= { get <#set#> \}}}
}
// SR-2575
struct SR2575 {
subscript() -> Int { // expected-note {{declared here}}
return 1
}
}
SR2575().subscript()
// expected-error@-1 {{value of type 'SR2575' has no property or method named 'subscript'; did you mean to use the subscript operator?}} {{9-10=}} {{10-19=}} {{19-20=[}} {{20-21=]}}
// SR-7890
struct InOutSubscripts {
subscript(x1: inout Int) -> Int { return 0 }
// expected-error@-1 {{'inout' must not be used on subscript parameters}}
subscript(x2: inout Int, y2: inout Int) -> Int { return 0 }
// expected-error@-1 2{{'inout' must not be used on subscript parameters}}
subscript(x3: (inout Int) -> ()) -> Int { return 0 } // ok
subscript(x4: (inout Int, inout Int) -> ()) -> Int { return 0 } // ok
subscript(inout x5: Int) -> Int { return 0 }
// expected-error@-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}}
// expected-error@-2 {{'inout' must not be used on subscript parameters}}
}
| apache-2.0 |
guoc/spi | SPiKeyboard/TastyImitationKeyboard/KeyboardKeyBackground.swift | 2 | 10545 | //
// KeyboardKeyBackground.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/19/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
// This class does not actually draw its contents; rather, it generates bezier curves for others to use.
// (You can still move it around, resize it, and add subviews to it. It just won't display the curve assigned to it.)
class KeyboardKeyBackground: UIView, Connectable {
var fillPath: UIBezierPath?
var underPath: UIBezierPath?
var edgePaths: [UIBezierPath]?
// do not set this manually
var cornerRadius: CGFloat
var underOffset: CGFloat
var startingPoints: [CGPoint]
var segmentPoints: [(CGPoint, CGPoint)]
var arcCenters: [CGPoint]
var arcStartingAngles: [CGFloat]
var dirty: Bool
var attached: Direction? {
didSet {
self.dirty = true
self.setNeedsLayout()
}
}
var hideDirectionIsOpposite: Bool {
didSet {
self.dirty = true
self.setNeedsLayout()
}
}
init(cornerRadius: CGFloat, underOffset: CGFloat) {
attached = nil
hideDirectionIsOpposite = false
dirty = false
startingPoints = []
segmentPoints = []
arcCenters = []
arcStartingAngles = []
startingPoints.reserveCapacity(4)
segmentPoints.reserveCapacity(4)
arcCenters.reserveCapacity(4)
arcStartingAngles.reserveCapacity(4)
for _ in 0..<4 {
startingPoints.append(CGPoint.zero)
segmentPoints.append((CGPoint.zero, CGPoint.zero))
arcCenters.append(CGPoint.zero)
arcStartingAngles.append(0)
}
self.cornerRadius = cornerRadius
self.underOffset = underOffset
super.init(frame: CGRect.zero)
self.isUserInteractionEnabled = false
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
var oldBounds: CGRect?
override func layoutSubviews() {
if !self.dirty {
if self.bounds.width == 0 || self.bounds.height == 0 {
return
}
if oldBounds != nil && self.bounds.equalTo(oldBounds!) {
return
}
}
oldBounds = self.bounds
super.layoutSubviews()
self.generatePointsForDrawing(self.bounds)
self.dirty = false
}
let floatPi = CGFloat(M_PI)
let floatPiDiv2 = CGFloat(M_PI/2.0)
let floatPiDivNeg2 = -CGFloat(M_PI/2.0)
func generatePointsForDrawing(_ bounds: CGRect) {
let segmentWidth = bounds.width
let segmentHeight = bounds.height - CGFloat(underOffset)
// base, untranslated corner points
self.startingPoints[0] = CGPoint(x: 0, y: segmentHeight)
self.startingPoints[1] = CGPoint(x: 0, y: 0)
self.startingPoints[2] = CGPoint(x: segmentWidth, y: 0)
self.startingPoints[3] = CGPoint(x: segmentWidth, y: segmentHeight)
self.arcStartingAngles[0] = floatPiDiv2
self.arcStartingAngles[2] = floatPiDivNeg2
self.arcStartingAngles[1] = floatPi
self.arcStartingAngles[3] = 0
//// actual coordinates for each edge, including translation
//self.segmentPoints.removeAll(keepCapacity: true)
//
//// actual coordinates for arc centers for each corner
//self.arcCenters.removeAll(keepCapacity: true)
//
//self.arcStartingAngles.removeAll(keepCapacity: true)
for i in 0 ..< self.startingPoints.count {
let currentPoint = self.startingPoints[i]
let nextPoint = self.startingPoints[(i + 1) % self.startingPoints.count]
var floatXCorner: CGFloat = 0
var floatYCorner: CGFloat = 0
if (i == 1) {
floatXCorner = cornerRadius
}
else if (i == 3) {
floatXCorner = -cornerRadius
}
if (i == 0) {
floatYCorner = -cornerRadius
}
else if (i == 2) {
floatYCorner = cornerRadius
}
let p0 = CGPoint(
x: currentPoint.x + (floatXCorner),
y: currentPoint.y + underOffset + (floatYCorner))
let p1 = CGPoint(
x: nextPoint.x - (floatXCorner),
y: nextPoint.y + underOffset - (floatYCorner))
self.segmentPoints[i] = (p0, p1)
let c = CGPoint(
x: p0.x - (floatYCorner),
y: p0.y + (floatXCorner))
self.arcCenters[i] = c
}
// order of edge drawing: left edge, down edge, right edge, up edge
// We need to have separate paths for all the edges so we can toggle them as needed.
// Unfortunately, it doesn't seem possible to assemble the connected fill path
// by simply using CGPathAddPath, since it closes all the subpaths, so we have to
// duplicate the code a little bit.
let fillPath = UIBezierPath()
var edgePaths: [UIBezierPath] = []
var prevPoint: CGPoint?
for i in 0..<4 {
var edgePath: UIBezierPath?
let segmentPoint = self.segmentPoints[i]
if self.attached != nil && (self.hideDirectionIsOpposite ? self.attached!.rawValue != i : self.attached!.rawValue == i) {
// do nothing
// TODO: quick hack
if !self.hideDirectionIsOpposite {
continue
}
}
else {
edgePath = UIBezierPath()
// TODO: figure out if this is ncessary
if prevPoint == nil {
prevPoint = segmentPoint.0
fillPath.move(to: prevPoint!)
}
fillPath.addLine(to: segmentPoint.0)
fillPath.addLine(to: segmentPoint.1)
edgePath!.move(to: segmentPoint.0)
edgePath!.addLine(to: segmentPoint.1)
prevPoint = segmentPoint.1
}
let shouldDrawArcInOppositeMode = (self.attached != nil ? (self.attached!.rawValue == i) || (self.attached!.rawValue == ((i + 1) % 4)) : false)
if (self.attached != nil && (self.hideDirectionIsOpposite ? !shouldDrawArcInOppositeMode : self.attached!.rawValue == ((i + 1) % 4))) {
// do nothing
} else {
edgePath = (edgePath == nil ? UIBezierPath() : edgePath)
if prevPoint == nil {
prevPoint = segmentPoint.1
fillPath.move(to: prevPoint!)
}
let startAngle = self.arcStartingAngles[(i + 1) % 4]
let endAngle = startAngle + floatPiDiv2
let arcCenter = self.arcCenters[(i + 1) % 4]
fillPath.addLine(to: prevPoint!)
fillPath.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
edgePath!.move(to: prevPoint!)
edgePath!.addArc(withCenter: arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
prevPoint = self.segmentPoints[(i + 1) % 4].0
}
edgePath?.apply(CGAffineTransform(translationX: 0, y: -self.underOffset))
if edgePath != nil { edgePaths.append(edgePath!) }
}
fillPath.close()
fillPath.apply(CGAffineTransform(translationX: 0, y: -self.underOffset))
let underPath = { () -> UIBezierPath in
let underPath = UIBezierPath()
underPath.move(to: self.segmentPoints[2].1)
var startAngle = self.arcStartingAngles[3]
var endAngle = startAngle + CGFloat(M_PI/2.0)
underPath.addArc(withCenter: self.arcCenters[3], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true)
underPath.addLine(to: self.segmentPoints[3].1)
startAngle = self.arcStartingAngles[0]
endAngle = startAngle + CGFloat(M_PI/2.0)
underPath.addArc(withCenter: self.arcCenters[0], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true)
underPath.addLine(to: CGPoint(x: self.segmentPoints[0].0.x, y: self.segmentPoints[0].0.y - self.underOffset))
startAngle = self.arcStartingAngles[1]
endAngle = startAngle - CGFloat(M_PI/2.0)
underPath.addArc(withCenter: CGPoint(x: self.arcCenters[0].x, y: self.arcCenters[0].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false)
underPath.addLine(to: CGPoint(x: self.segmentPoints[2].1.x - self.cornerRadius, y: self.segmentPoints[2].1.y + self.cornerRadius - self.underOffset))
startAngle = self.arcStartingAngles[0]
endAngle = startAngle - CGFloat(M_PI/2.0)
underPath.addArc(withCenter: CGPoint(x: self.arcCenters[3].x, y: self.arcCenters[3].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false)
underPath.close()
return underPath
}()
self.fillPath = fillPath
self.edgePaths = edgePaths
self.underPath = underPath
}
func attachmentPoints(_ direction: Direction) -> (CGPoint, CGPoint) {
let returnValue = (
self.segmentPoints[direction.clockwise().rawValue].0,
self.segmentPoints[direction.counterclockwise().rawValue].1)
return returnValue
}
func attachmentDirection() -> Direction? {
return self.attached
}
func attach(_ direction: Direction?) {
self.attached = direction
}
}
| bsd-3-clause |
fabioalmeida/FAAutoLayout | Example/Tests/FAAutoLayoutTests_Center.swift | 1 | 6842 | //
// FAAutoLayoutTests_Center.swift
// FAAutoLayout
//
// Created by Fábio Almeida on 12/07/2017.
// Copyright (c) 2017 Fábio Almeida. All rights reserved.
//
import XCTest
import FAAutoLayout
class FAAutoLayoutTests_Center: FAAutoLayoutTests {
// MARK: - Center Container
func testCenterHorizontallyInContainer() {
let view1 = UIView()
self.view.addSubview(view1)
let width: CGFloat = 100
let height: CGFloat = 50
view1.constrainWidth(width)
view1.constrainHeight(height)
view1.constrainTopSpaceToContainer()
view1.centerHorizontallyInContainer()
self.view.layoutIfNeeded()
// view1 frame: (110 0; 100 50)
XCTAssertEqual(view1.frame.origin.x, self.view.frame.size.width/2 - width/2)
XCTAssertEqual(view1.frame.origin.y, 0)
}
func testCenterHorizontallyInContainerOffset() {
let view1 = UIView()
self.view.addSubview(view1)
let width: CGFloat = 100
let height: CGFloat = 50
let offset: CGFloat = 13
view1.constrainWidth(width)
view1.constrainHeight(height)
view1.constrainTopSpaceToContainer()
view1.centerHorizontallyInContainer(offset)
self.view.layoutIfNeeded()
// view1 frame: (123 0; 100 50)
XCTAssertEqual(view1.frame.origin.x, self.view.frame.size.width/2 - width/2 + offset)
XCTAssertEqual(view1.frame.origin.y, 0)
}
func testCenterVerticallyInContainer() {
let view1 = UIView()
self.view.addSubview(view1)
let width: CGFloat = 100
let height: CGFloat = 50
view1.constrainWidth(width)
view1.constrainHeight(height)
view1.constrainLeadingSpaceToContainer()
view1.centerVerticallyInContainer()
self.view.layoutIfNeeded()
// view1 frame: (0 275; 100 50)
XCTAssertEqual(view1.frame.origin.x, 0)
XCTAssertEqual(view1.frame.origin.y, self.view.frame.size.height/2 - height/2)
}
func testCenterVerticallyInContainerOffset() {
let view1 = UIView()
self.view.addSubview(view1)
let width: CGFloat = 100
let height: CGFloat = 50
let offset: CGFloat = 13
view1.constrainWidth(width)
view1.constrainHeight(height)
view1.constrainLeadingSpaceToContainer()
view1.centerVerticallyInContainer(offset)
self.view.layoutIfNeeded()
// view1 frame: (0 288; 100 50)
XCTAssertEqual(view1.frame.origin.x, 0)
XCTAssertEqual(view1.frame.origin.y, self.view.frame.size.height/2 - height/2 + offset)
}
func testCenterMiddleInContainer() {
let view1 = UIView()
self.view.addSubview(view1)
let width: CGFloat = 100
let height: CGFloat = 50
view1.constrainWidth(width)
view1.constrainHeight(height)
view1.centerVerticallyInContainer()
view1.centerHorizontallyInContainer()
self.view.layoutIfNeeded()
// view1 frame: (110 275; 100 50)
XCTAssertEqual(view1.frame.origin.x, self.view.frame.size.width/2 - width/2)
XCTAssertEqual(view1.frame.origin.y, self.view.frame.size.height/2 - height/2)
}
// MARK: - Center Container View
func testCenterHorizontallyInContainerView() {
let containerView = UIView()
let outerView = UIView()
let innerView = UIView()
outerView.addSubview(innerView)
containerView.addSubview(outerView)
self.view.addSubview(containerView)
// containerView frame: (0 0; 320 600)
containerView.fillContainer()
let outerPadding: CGFloat = 40.0
// outerView frame: (40 40; 240 520) - it is only relative to superview
outerView.fillContainer(outerPadding)
let width: CGFloat = 100
let height: CGFloat = 50
innerView.constrainWidth(width)
innerView.constrainHeight(height)
innerView.constrainTopSpaceToContainer()
innerView.centerHorizontally(withView: containerView)
self.view.layoutIfNeeded()
let relativeInnerViewFrame = innerView.superview?.convert(innerView.frame, to: containerView)
// relativeInnerViewFrame: (110 40; 100 50)
XCTAssertEqual(relativeInnerViewFrame?.origin.x, containerView.frame.size.width/2 - width/2)
XCTAssertEqual(relativeInnerViewFrame?.origin.y, outerPadding)
}
func testCenterVerticallyInContainerView() {
let containerView = UIView()
let outerView = UIView()
let innerView = UIView()
outerView.addSubview(innerView)
containerView.addSubview(outerView)
self.view.addSubview(containerView)
// containerView frame: (0 0; 320 600)
containerView.fillContainer()
let outerPadding: CGFloat = 40.0
// outerView frame: (40 40; 240 520) - it is only relative to superview
outerView.fillContainer(outerPadding)
let width: CGFloat = 100
let height: CGFloat = 50
innerView.constrainWidth(width)
innerView.constrainHeight(height)
innerView.constrainLeadingSpaceToContainer()
innerView.centerVertically(withView: containerView)
self.view.layoutIfNeeded()
let relativeInnerViewFrame = innerView.superview?.convert(innerView.frame, to: containerView)
// relativeInnerViewFrame: (40 275; 100 50)
XCTAssertEqual(relativeInnerViewFrame?.origin.x, outerPadding)
XCTAssertEqual(relativeInnerViewFrame?.origin.y, containerView.frame.size.height/2 - height/2)
}
func testCenterMiddleInContainerView() {
let containerView = UIView()
let outerView = UIView()
let innerView = UIView()
outerView.addSubview(innerView)
containerView.addSubview(outerView)
self.view.addSubview(containerView)
// containerView frame: (0 0; 320 600)
containerView.fillContainer()
let outerPadding: CGFloat = 40.0
// outerView frame: (40 40; 240 520) - it is only relative to superview
outerView.fillContainer(outerPadding)
let width: CGFloat = 100
let height: CGFloat = 50
innerView.constrainWidth(width)
innerView.constrainHeight(height)
innerView.centerHorizontally(withView: containerView)
innerView.centerVertically(withView: containerView)
self.view.layoutIfNeeded()
let relativeInnerViewFrame = innerView.superview?.convert(innerView.frame, to: containerView)
// relativeInnerViewFrame: (110 275; 100 50)
XCTAssertEqual(relativeInnerViewFrame?.origin.x, containerView.frame.size.width/2 - width/2)
XCTAssertEqual(relativeInnerViewFrame?.origin.y, containerView.frame.size.height/2 - height/2)
}
}
| mit |
tox777/tableviewjson | tableviewjson/ViewController.swift | 1 | 522 | //
// ViewController.swift
// tableviewjson
//
// Created by Jorge Torres A on 4/7/15.
// Copyright (c) 2015 torrestecnologia.com. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-2.0 |
haibtdt/NotifiOS-Cumulation | ExampleAppUITests/ExampleAppUITests.swift | 1 | 1245 | //
// ExampleAppUITests.swift
// ExampleAppUITests
//
// Created by Bui Hai on 9/21/15.
// Copyright © 2015 Bui Hai. All rights reserved.
//
import XCTest
class ExampleAppUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
paoloiulita/AbstractNumericStepper | AbstractNumericStepper/Classes/AbstractNumericStepper.swift | 1 | 4069 | //
// AbstractNumericStepper.swift
// Pods
//
// Created by Paolo Iulita on 03/05/16.
//
//
import Foundation
import UIKit
@objc public protocol AbstractNumericStepperDelegate: NSObjectProtocol {
func numericStepper(numericStepper: AbstractNumericStepper, valueChanged value: Double)
}
/// Contains methods for easily creating a numeric stepper
public class AbstractNumericStepper: UIView, UITextFieldDelegate {
// MARK: initializers
public override func awakeFromNib() {
textField.delegate = self
textField.keyboardType = .DecimalPad
let numberToolbar: UIToolbar = UIToolbar()
numberToolbar.barStyle = .Default
numberToolbar.items = [
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Done", style: .Plain, target: self, action: #selector(onDone))
]
numberToolbar.sizeToFit()
textField.inputAccessoryView = numberToolbar
}
// MARK: outlets
@IBOutlet weak var increment: UIButton!
@IBOutlet weak var decrement: UIButton!
@IBOutlet weak var textField: UITextField!
// MARK: actions
/**
change the model by adding a defined step value
- Parameter sender: The UIButton invoking
*/
@IBAction func onIncrement(sender: UIButton) {
value += step
}
/**
change the model by subtracting a defined step value
- Parameter sender: The UIButton invoking
*/
@IBAction func onDecrement(sender: UIButton) {
value -= step
}
// MARK: properties
/// The object implementing the method called when value changes
public var delegate: AbstractNumericStepperDelegate?
/// The actual value of the numeric stepper
public var value: Double = 0 {
didSet {
let isInt = floor(value) == value
if !canShowDecimalValues {
value = round(value)
} else if shouldRoundToHalfDecimal && !isInt {
var fValue: Double = floor(value)
if (value - fValue) > 0.5 {
fValue += 1
} else {
fValue += 0.5
}
value = fValue
}
value = Swift.min(value, max)
value = Swift.max(value, min)
decrement.enabled = value >= min
increment.enabled = value <= max
updateTextField()
if value != oldValue {
delegate?.numericStepper(self, valueChanged: value)
}
}
}
/// The minimum value allowed to be set
public var min: Double = 0 {
didSet {
value = Swift.max(value, min)
}
}
/// The maximum value allowed to be set
public var max: Double = 10 {
didSet {
value = Swift.min(value, max)
}
}
/// The quantity to be added or subtracted on each button press
public var step: Double = 1
/// Defines if the numeric stepper should or not show only integers
public var canShowDecimalValues: Bool = false {
didSet {
updateTextField()
}
}
/// The symbol that can be placed after the value
public var currencySymbol: String = "" {
didSet {
if currencySymbol != "" {
updateTextField()
}
}
}
/// Defines if the value should be rounded at the neares half decimal (0.5) point
public var shouldRoundToHalfDecimal: Bool = false
/// Defines if the UITextField shoul be interactive
public var canDirectInputValues: Bool = true {
didSet {
if canDirectInputValues {
textField.delegate = self
} else {
textField.delegate = nil
}
textField.userInteractionEnabled = canDirectInputValues
}
}
// MARK: private methods
private func updateTextField() {
var valueToString = ""
if !canShowDecimalValues {
valueToString = "\(Int(value))"
} else {
valueToString = String(value)
}
if currencySymbol != "" {
textField.text = "\(valueToString) \(currencySymbol)"
} else {
textField.text = valueToString
}
}
private func updateValue() {
if let tValue = textField.text {
value = Double(tValue) ?? min
}
}
@objc private func onDone() {
textField.resignFirstResponder()
}
// MARK: UITextFieldDelegate
public func textFieldDidEndEditing(textField: UITextField) {
updateValue()
}
public func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit |
davidstump/SwiftPhoenixClient | Tests/SwiftPhoenixClientTests/SocketSpec.swift | 1 | 33460 | //
// SocketSpec.swift
// SwiftPhoenixClient
//
// Created by Daniel Rees on 2/10/18.
//
import Quick
import Nimble
@testable import SwiftPhoenixClient
@available(iOS 13, *)
class SocketSpec: QuickSpec {
let encode = Defaults.encode
let decode = Defaults.decode
override func spec() {
describe("constructor") {
it("sets defaults", closure: {
let socket = Socket("wss://localhost:4000/socket")
expect(socket.channels).to(haveCount(0))
expect(socket.sendBuffer).to(haveCount(0))
expect(socket.ref).to(equal(0))
expect(socket.endPoint).to(equal("wss://localhost:4000/socket"))
expect(socket.stateChangeCallbacks.open).to(beEmpty())
expect(socket.stateChangeCallbacks.close).to(beEmpty())
expect(socket.stateChangeCallbacks.error).to(beEmpty())
expect(socket.stateChangeCallbacks.message).to(beEmpty())
expect(socket.timeout).to(equal(Defaults.timeoutInterval))
expect(socket.heartbeatInterval).to(equal(Defaults.heartbeatInterval))
expect(socket.logger).to(beNil())
expect(socket.reconnectAfter(1)).to(equal(0.010)) // 10ms
expect(socket.reconnectAfter(2)).to(equal(0.050)) // 50ms
expect(socket.reconnectAfter(3)).to(equal(0.100)) // 100ms
expect(socket.reconnectAfter(4)).to(equal(0.150)) // 150ms
expect(socket.reconnectAfter(5)).to(equal(0.200)) // 200ms
expect(socket.reconnectAfter(6)).to(equal(0.250)) // 250ms
expect(socket.reconnectAfter(7)).to(equal(0.500)) // 500ms
expect(socket.reconnectAfter(8)).to(equal(1.000)) // 1_000ms (1s)
expect(socket.reconnectAfter(9)).to(equal(2.000)) // 2_000ms (2s)
expect(socket.reconnectAfter(10)).to(equal(5.00)) // 5_000ms (5s)
expect(socket.reconnectAfter(11)).to(equal(5.00)) // 5_000ms (5s)
})
it("overrides some defaults", closure: {
let socket = Socket("wss://localhost:4000/socket", paramsClosure: { ["one": 2] })
socket.timeout = 40000
socket.heartbeatInterval = 60000
socket.logger = { _ in }
socket.reconnectAfter = { _ in return 10 }
expect(socket.timeout).to(equal(40000))
expect(socket.heartbeatInterval).to(equal(60000))
expect(socket.logger).toNot(beNil())
expect(socket.reconnectAfter(1)).to(equal(10))
expect(socket.reconnectAfter(2)).to(equal(10))
})
// it("sets queue for underlying transport", closure: {
// let socket = Socket(endPoint: "wss://localhost:4000/socket", transport: { (url) -> WebSocketClient in
// let webSocket = WebSocket(url: url)
// webSocket.callbackQueue = DispatchQueue(label: "test_queue")
// return webSocket
// })
// socket.timeout = 40000
// socket.heartbeatInterval = 60000
// socket.logger = { _ in }
// socket.reconnectAfter = { _ in return 10 }
// socket.connect()
// expect(socket.connection).to(beAKindOf(Transport.self))
// expect((socket.connection as! WebSocket).callbackQueue.label).to(equal("test_queue"))
// })
it("should construct a valid URL", closure: {
// test vsn
expect(Socket("http://localhost:4000/socket/websocket",
paramsClosure: { ["token": "abc123"] },
vsn: "1.0.0")
.endPointUrl
.absoluteString)
.to(equal("http://localhost:4000/socket/websocket?vsn=1.0.0&token=abc123"))
// test params
expect(Socket("http://localhost:4000/socket/websocket",
paramsClosure: { ["token": "abc123"] })
.endPointUrl
.absoluteString)
.to(equal("http://localhost:4000/socket/websocket?vsn=2.0.0&token=abc123"))
expect(Socket("ws://localhost:4000/socket/websocket",
paramsClosure: { ["token": "abc123", "user_id": 1] })
.endPointUrl
.absoluteString)
.to(satisfyAnyOf(
// absoluteString does not seem to return a string with the params in a deterministic order
equal("ws://localhost:4000/socket/websocket?vsn=2.0.0&token=abc123&user_id=1"),
equal("ws://localhost:4000/socket/websocket?vsn=2.0.0&user_id=1&token=abc123")
)
)
// test params with spaces
expect(Socket("ws://localhost:4000/socket/websocket",
paramsClosure: { ["token": "abc 123", "user_id": 1] })
.endPointUrl
.absoluteString)
.to(satisfyAnyOf(
// absoluteString does not seem to return a string with the params in a deterministic order
equal("ws://localhost:4000/socket/websocket?vsn=2.0.0&token=abc%20123&user_id=1"),
equal("ws://localhost:4000/socket/websocket?vsn=2.0.0&user_id=1&token=abc%20123")
)
)
})
it("should not introduce any retain cycles", closure: {
// Must remain as a weak var in order to deallocate the socket. This tests that the
// reconnect timer does not old on to the Socket causing a memory leak.
weak var socket = Socket("http://localhost:4000/socket/websocket")
expect(socket).to(beNil())
})
}
describe("params") {
it("changes dynamically with a closure") {
var authToken = "abc123"
let socket = Socket("ws://localhost:4000/socket/websocket", paramsClosure: { ["token": authToken] })
expect(socket.params?["token"] as? String).to(equal("abc123"))
authToken = "xyz987"
expect(socket.params?["token"] as? String).to(equal("xyz987"))
}
}
describe("websocketProtocol") {
it("returns wss when protocol is https", closure: {
let socket = Socket("https://example.com/")
expect(socket.websocketProtocol).to(equal("wss"))
})
it("returns wss when protocol is wss", closure: {
let socket = Socket("wss://example.com/")
expect(socket.websocketProtocol).to(equal("wss"))
})
it("returns ws when protocol is http", closure: {
let socket = Socket("http://example.com/")
expect(socket.websocketProtocol).to(equal("ws"))
})
it("returns ws when protocol is ws", closure: {
let socket = Socket("ws://example.com/")
expect(socket.websocketProtocol).to(equal("ws"))
})
it("returns empty if there is no scheme", closure: {
let socket = Socket("example.com/")
expect(socket.websocketProtocol).to(beEmpty())
})
}
// describe("endPointUrl") {
// it("does nothing with the url", closure: {
// let socket = Socket("http://example.com/websocket")
// expect(socket.endPointUrl.absoluteString).to(equal("http://example.com/websocket"))
// })
//
// it("appends /websocket correctly", closure: {
// let socketA = Socket("wss://example.org/chat/")
// expect(socketA.endPointUrl.absoluteString).to(equal("wss://example.org/chat/websocket"))
//
// let socketB = Socket("ws://example.org/chat")
// expect(socketB.endPointUrl.absoluteString).to(equal("ws://example.org/chat/websocket"))
// })
// }
describe("connect with Websocket") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket }
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport)
socket.skipHeartbeat = true
}
it("establishes websocket connection with endpoint", closure: {
socket.connect()
expect(socket.connection).toNot(beNil())
})
it("set callbacks for connection", closure: {
var open = 0
socket.onOpen { open += 1 }
var close = 0
socket.onClose { close += 1 }
var lastError: Error?
socket.onError(callback: { (error) in lastError = error })
var lastMessage: Message?
socket.onMessage(callback: { (message) in lastMessage = message })
mockWebSocket.readyState = .closed
socket.connect()
mockWebSocket.delegate?.onOpen()
expect(open).to(equal(1))
mockWebSocket.delegate?.onClose(code: 1000)
expect(close).to(equal(1))
mockWebSocket.delegate?.onError(error: TestError.stub)
expect(lastError).toNot(beNil())
let data: [Any] = ["2", "6", "topic", "event", ["response": ["go": true], "status": "ok"]]
let text = toWebSocketText(data: data)
mockWebSocket.delegate?.onMessage(message: text)
expect(lastMessage?.payload["go"] as? Bool).to(beTrue())
})
it("removes callbacks", closure: {
var open = 0
socket.onOpen { open += 1 }
var close = 0
socket.onClose { close += 1 }
var lastError: Error?
socket.onError(callback: { (error) in lastError = error })
var lastMessage: Message?
socket.onMessage(callback: { (message) in lastMessage = message })
mockWebSocket.readyState = .closed
socket.releaseCallbacks()
socket.connect()
mockWebSocket.delegate?.onOpen()
expect(open).to(equal(0))
mockWebSocket.delegate?.onClose(code: 1000)
expect(close).to(equal(0))
mockWebSocket.delegate?.onError(error: TestError.stub)
expect(lastError).to(beNil())
let data: [Any] = ["2", "6", "topic", "event", ["response": ["go": true], "status": "ok"]]
let text = toWebSocketText(data: data)
mockWebSocket.delegate?.onMessage(message: text)
expect(lastMessage).to(beNil())
})
it("does not connect if already connected", closure: {
mockWebSocket.readyState = .open
socket.connect()
socket.connect()
expect(mockWebSocket.connectCallsCount).to(equal(1))
})
}
describe("disconnect") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket }
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport)
}
it("removes existing connection", closure: {
socket.connect()
socket.disconnect()
expect(socket.connection).to(beNil())
expect(mockWebSocket.disconnectCodeReasonReceivedArguments?.code)
.to(equal(Socket.CloseCode.normal.rawValue))
})
it("flags the socket as closed cleanly", closure: {
expect(socket.closeStatus).to(equal(.unknown))
socket.disconnect()
expect(socket.closeStatus).to(equal(.clean))
})
it("calls callback", closure: {
var callCount = 0
socket.connect()
socket.disconnect(code: .goingAway) {
callCount += 1
}
expect(mockWebSocket.disconnectCodeReasonCalled).to(beTrue())
expect(mockWebSocket.disconnectCodeReasonReceivedArguments?.reason).to(beNil())
expect(mockWebSocket.disconnectCodeReasonReceivedArguments?.code)
.to(equal(Socket.CloseCode.goingAway.rawValue))
expect(callCount).to(equal(1))
})
it("calls onClose for all state callbacks", closure: {
var callCount = 0
socket.onClose {
callCount += 1
}
socket.disconnect()
expect(callCount).to(equal(1))
})
it("invalidates and invalidates the heartbeat timer", closure: {
var timerCalled = 0
let queue = DispatchQueue(label: "test.heartbeat")
let timer = HeartbeatTimer(timeInterval: 10, queue: queue)
timer.start { timerCalled += 1 }
socket.heartbeatTimer = timer
socket.disconnect()
expect(socket.heartbeatTimer?.isValid).to(beFalse())
timer.fire()
expect(timerCalled).to(equal(0))
})
it("does nothing if not connected", closure: {
socket.disconnect()
expect(mockWebSocket.disconnectCodeReasonCalled).to(beFalse())
})
}
describe("channel") {
var socket: Socket!
beforeEach {
socket = Socket("/socket")
}
it("returns channel with given topic and params", closure: {
let channel = socket.channel("topic", params: ["one": "two"])
socket.ref = 1006
// No deep equal, so hack it
expect(channel.socket?.ref).to(equal(socket.ref))
expect(channel.topic).to(equal("topic"))
expect(channel.params["one"] as? String).to(equal("two"))
})
it("adds channel to sockets channel list", closure: {
expect(socket.channels).to(beEmpty())
let channel = socket.channel("topic", params: ["one": "two"])
expect(socket.channels).to(haveCount(1))
expect(socket.channels[0].topic).to(equal(channel.topic))
})
}
describe("remove") {
var socket: Socket!
beforeEach {
socket = Socket("/socket")
}
it("removes given channel from channels", closure: {
let channel1 = socket.channel("topic-1")
let channel2 = socket.channel("topic-2")
channel1.joinPush.ref = "1"
channel2.joinPush.ref = "2"
socket.remove(channel1)
expect(socket.channels).to(haveCount(1))
expect(socket.channels[0].topic).to(equal(channel2.topic))
})
}
describe("push") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket }
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport)
}
it("sends data to connection when connected", closure: {
mockWebSocket.readyState = .open
socket.connect()
socket.push(topic: "topic", event: "event", payload: ["one": "two"], ref: "6", joinRef: "2")
expect(mockWebSocket.sendDataCalled).to(beTrue())
let json = self.decode(mockWebSocket.sendDataReceivedData!) as! [Any]
expect(json[0] as? String).to(equal("2"))
expect(json[1] as? String).to(equal("6"))
expect(json[2] as? String).to(equal("topic"))
expect(json[3] as? String).to(equal("event"))
expect(json[4] as? [String: String]).to(equal(["one": "two"]))
expect(String(data: mockWebSocket.sendDataReceivedData!, encoding: .utf8))
.to(equal("[\"2\",\"6\",\"topic\",\"event\",{\"one\":\"two\"}]"))
})
it("excludes ref information if not passed", closure: {
mockWebSocket.readyState = .open
socket.connect()
socket.push(topic: "topic", event: "event", payload: ["one": "two"])
let json = self.decode(mockWebSocket.sendDataReceivedData!) as! [Any?]
expect(json[0] as? String).to(beNil())
expect(json[1] as? String).to(beNil())
expect(json[2] as? String).to(equal("topic"))
expect(json[3] as? String).to(equal("event"))
expect(json[4] as? [String: String]).to(equal(["one": "two"]))
expect(String(data: mockWebSocket.sendDataReceivedData!, encoding: .utf8))
.to(equal("[null,null,\"topic\",\"event\",{\"one\":\"two\"}]"))
})
it("buffers data when not connected", closure: {
mockWebSocket.readyState = .closed
socket.connect()
expect(socket.sendBuffer).to(beEmpty())
socket.push(topic: "topic1", event: "event1", payload: ["one": "two"])
expect(mockWebSocket.sendDataCalled).to(beFalse())
expect(socket.sendBuffer).to(haveCount(1))
socket.push(topic: "topic2", event: "event2", payload: ["one": "two"])
expect(mockWebSocket.sendDataCalled).to(beFalse())
expect(socket.sendBuffer).to(haveCount(2))
socket.sendBuffer.forEach( { try? $0.callback() } )
expect(mockWebSocket.sendDataCalled).to(beTrue())
expect(mockWebSocket.sendDataCallsCount).to(equal(2))
})
}
describe("makeRef") {
var socket: Socket!
beforeEach {
socket = Socket("/socket")
}
it("returns next message ref", closure: {
expect(socket.ref).to(equal(0))
expect(socket.makeRef()).to(equal("1"))
expect(socket.ref).to(equal(1))
expect(socket.makeRef()).to(equal("2"))
expect(socket.ref).to(equal(2))
})
it("resets to 0 if it hits max int", closure: {
socket.ref = UInt64.max
expect(socket.makeRef()).to(equal("0"))
expect(socket.ref).to(equal(0))
})
}
describe("sendHeartbeat v1") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
socket = Socket("/socket")
socket.connection = mockWebSocket
}
it("closes socket when heartbeat is not ack'd within heartbeat window", closure: {
mockWebSocket.readyState = .open
socket.sendHeartbeat()
expect(mockWebSocket.disconnectCodeReasonCalled).to(beFalse())
expect(socket.pendingHeartbeatRef).toNot(beNil())
socket.sendHeartbeat()
expect(mockWebSocket.disconnectCodeReasonCalled).to(beTrue())
expect(socket.pendingHeartbeatRef).to(beNil())
})
it("pushes heartbeat data when connected", closure: {
mockWebSocket.readyState = .open
socket.sendHeartbeat()
expect(socket.pendingHeartbeatRef).to(equal(String(socket.ref)))
expect(mockWebSocket.sendDataCalled).to(beTrue())
let json = self.decode(mockWebSocket.sendDataReceivedData!) as? [Any?]
expect(json?[0] as? String).to(beNil())
expect(json?[1] as? String).to(equal(socket.pendingHeartbeatRef))
expect(json?[2] as? String).to(equal("phoenix"))
expect(json?[3] as? String).to(equal("heartbeat"))
expect(json?[4] as? [String: String]).to(beEmpty())
expect(String(data: mockWebSocket.sendDataReceivedData!, encoding: .utf8))
.to(equal("[null,\"1\",\"phoenix\",\"heartbeat\",{}]"))
})
it("does nothing when not connected", closure: {
mockWebSocket.readyState = .closed
socket.sendHeartbeat()
expect(mockWebSocket.disconnectCodeReasonCalled).to(beFalse())
expect(mockWebSocket.sendDataCalled).to(beFalse())
})
}
describe("flushSendBuffer") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
socket = Socket("/socket")
socket.connection = mockWebSocket
}
it("calls callbacks in buffer when connected", closure: {
var oneCalled = 0
socket.sendBuffer.append(("0", { oneCalled += 1 }))
var twoCalled = 0
socket.sendBuffer.append(("1", { twoCalled += 1 }))
let threeCalled = 0
mockWebSocket.readyState = .open
socket.flushSendBuffer()
expect(oneCalled).to(equal(1))
expect(twoCalled).to(equal(1))
expect(threeCalled).to(equal(0))
})
it("empties send buffer", closure: {
socket.sendBuffer.append((nil, { }))
mockWebSocket.readyState = .open
socket.flushSendBuffer()
expect(socket.sendBuffer).to(beEmpty())
})
}
describe("removeFromSendBuffer") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
socket = Socket("/socket")
socket.connection = mockWebSocket
}
it("removes a callback with a matching ref", closure: {
var oneCalled = 0
socket.sendBuffer.append(("0", { oneCalled += 1 }))
var twoCalled = 0
socket.sendBuffer.append(("1", { twoCalled += 1 }))
let threeCalled = 0
mockWebSocket.readyState = .open
socket.removeFromSendBuffer(ref: "0")
socket.flushSendBuffer()
expect(oneCalled).to(equal(0))
expect(twoCalled).to(equal(1))
expect(threeCalled).to(equal(0))
})
}
describe("onConnectionOpen") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
var mockTimeoutTimer: TimeoutTimerMock!
let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket }
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
mockTimeoutTimer = TimeoutTimerMock()
socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport)
socket.reconnectAfter = { _ in return 10 }
socket.reconnectTimer = mockTimeoutTimer
socket.skipHeartbeat = true
mockWebSocket.readyState = .open
socket.connect()
}
it("flushes the send buffer", closure: {
var oneCalled = 0
socket.sendBuffer.append(("0", { oneCalled += 1 }))
socket.onConnectionOpen()
expect(oneCalled).to(equal(1))
expect(socket.sendBuffer).to(beEmpty())
})
it("resets reconnectTimer", closure: {
socket.onConnectionOpen()
expect(mockTimeoutTimer.resetCalled).to(beTrue())
})
it("triggers onOpen callbacks", closure: {
var oneCalled = 0
socket.onOpen { oneCalled += 1 }
var twoCalled = 0
socket.onOpen { twoCalled += 1 }
var threeCalled = 0
socket.onClose { threeCalled += 1 }
socket.onConnectionOpen()
expect(oneCalled).to(equal(1))
expect(twoCalled).to(equal(1))
expect(threeCalled).to(equal(0))
})
}
describe("resetHeartbeat") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket }
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport)
}
it("clears any pending heartbeat", closure: {
socket.pendingHeartbeatRef = "1"
socket.resetHeartbeat()
expect(socket.pendingHeartbeatRef).to(beNil())
})
it("does not schedule heartbeat if skipHeartbeat == true", closure: {
socket.skipHeartbeat = true
socket.resetHeartbeat()
expect(socket.heartbeatTimer).to(beNil())
})
it("creates a timer and sends a heartbeat", closure: {
mockWebSocket.readyState = .open
socket.connect()
socket.heartbeatInterval = 1
expect(socket.heartbeatTimer).to(beNil())
socket.resetHeartbeat()
expect(socket.heartbeatTimer).toNot(beNil())
expect(socket.heartbeatTimer?.timeInterval).to(equal(1))
// Fire the timer
socket.heartbeatTimer?.fire()
expect(mockWebSocket.sendDataCalled).to(beTrue())
let json = self.decode(mockWebSocket.sendDataReceivedData!) as? [Any?]
expect(json?[0] as? String).to(beNil())
expect(json?[1] as? String).to(equal(String(socket.ref)))
expect(json?[2] as? String).to(equal("phoenix"))
expect(json?[3] as? String).to(equal(ChannelEvent.heartbeat))
expect(json?[4] as? [String: Any]).to(beEmpty())
})
it("should invalidate an old timer and create a new one", closure: {
mockWebSocket.readyState = .open
let queue = DispatchQueue(label: "test.heartbeat")
let timer = HeartbeatTimer(timeInterval: 1000, queue: queue)
var timerCalled = 0
timer.start { timerCalled += 1 }
socket.heartbeatTimer = timer
expect(timer.isValid).to(beTrue())
socket.resetHeartbeat()
expect(timer.isValid).to(beFalse())
expect(socket.heartbeatTimer).toNot(equal(timer))
})
}
describe("onConnectionClosed") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
var mockTimeoutTimer: TimeoutTimerMock!
let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket }
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
mockTimeoutTimer = TimeoutTimerMock()
socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport)
// socket.reconnectAfter = { _ in return 10 }
socket.reconnectTimer = mockTimeoutTimer
// socket.skipHeartbeat = true
}
it("schedules reconnectTimer timeout if normal close", closure: {
socket.onConnectionClosed(code: Socket.CloseCode.normal.rawValue)
expect(mockTimeoutTimer.scheduleTimeoutCalled).to(beTrue())
})
it("does not schedule reconnectTimer timeout if normal close after explicit disconnect", closure: {
socket.disconnect()
expect(mockTimeoutTimer.scheduleTimeoutCalled).to(beFalse())
})
it("schedules reconnectTimer timeout if not normal close", closure: {
socket.onConnectionClosed(code: 1001)
expect(mockTimeoutTimer.scheduleTimeoutCalled).to(beTrue())
})
it("schedules reconnectTimer timeout if connection cannot be made after a previous clean disconnect", closure: {
socket.disconnect()
socket.connect()
socket.onConnectionClosed(code: 1001)
expect(mockTimeoutTimer.scheduleTimeoutCalled).to(beTrue())
})
it("triggers channel error if joining", closure: {
let channel = socket.channel("topic")
var errorCalled = false
channel.on(ChannelEvent.error, callback: { _ in
errorCalled = true
})
channel.join()
expect(channel.state).to(equal(.joining))
socket.onConnectionClosed(code: 1001)
expect(errorCalled).to(beTrue())
})
it("triggers channel error if joined", closure: {
let channel = socket.channel("topic")
var errorCalled = false
channel.on(ChannelEvent.error, callback: { _ in
errorCalled = true
})
channel.join().trigger("ok", payload: [:])
expect(channel.state).to(equal(.joined))
socket.onConnectionClosed(code: 1001)
expect(errorCalled).to(beTrue())
})
it("does not trigger channel error after leave", closure: {
let channel = socket.channel("topic")
var errorCalled = false
channel.on(ChannelEvent.error, callback: { _ in
errorCalled = true
})
channel.join().trigger("ok", payload: [:])
channel.leave()
expect(channel.state).to(equal(.closed))
socket.onConnectionClosed(code: 1001)
expect(errorCalled).to(beFalse())
})
it("triggers onClose callbacks", closure: {
var oneCalled = 0
socket.onClose { oneCalled += 1 }
var twoCalled = 0
socket.onClose { twoCalled += 1 }
var threeCalled = 0
socket.onOpen { threeCalled += 1 }
socket.onConnectionClosed(code: 1000)
expect(oneCalled).to(equal(1))
expect(twoCalled).to(equal(1))
expect(threeCalled).to(equal(0))
})
}
describe("onConnectionError") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
var mockTimeoutTimer: TimeoutTimerMock!
let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket }
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
mockTimeoutTimer = TimeoutTimerMock()
socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport)
socket.reconnectAfter = { _ in return 10 }
socket.reconnectTimer = mockTimeoutTimer
socket.skipHeartbeat = true
mockWebSocket.readyState = .open
socket.connect()
}
it("triggers onClose callbacks", closure: {
var lastError: Error?
socket.onError(callback: { (error) in lastError = error })
socket.onConnectionError(TestError.stub)
expect(lastError).toNot(beNil())
})
it("triggers channel error if joining", closure: {
let channel = socket.channel("topic")
var errorCalled = false
channel.on(ChannelEvent.error, callback: { _ in
errorCalled = true
})
channel.join()
expect(channel.state).to(equal(.joining))
socket.onConnectionError(TestError.stub)
expect(errorCalled).to(beTrue())
})
it("triggers channel error if joined", closure: {
let channel = socket.channel("topic")
var errorCalled = false
channel.on(ChannelEvent.error, callback: { _ in
errorCalled = true
})
channel.join().trigger("ok", payload: [:])
expect(channel.state).to(equal(.joined))
socket.onConnectionError(TestError.stub)
expect(errorCalled).to(beTrue())
})
it("does not trigger channel error after leave", closure: {
let channel = socket.channel("topic")
var errorCalled = false
channel.on(ChannelEvent.error, callback: { _ in
errorCalled = true
})
channel.join().trigger("ok", payload: [:])
channel.leave()
expect(channel.state).to(equal(.closed))
socket.onConnectionError(TestError.stub)
expect(errorCalled).to(beFalse())
})
}
describe("onConnectionMessage") {
// Mocks
var mockWebSocket: PhoenixTransportMock!
var mockTimeoutTimer: TimeoutTimerMock!
let mockWebSocketTransport: ((URL) -> PhoenixTransportMock) = { _ in return mockWebSocket }
// UUT
var socket: Socket!
beforeEach {
mockWebSocket = PhoenixTransportMock()
mockTimeoutTimer = TimeoutTimerMock()
socket = Socket(endPoint: "/socket", transport: mockWebSocketTransport)
socket.reconnectAfter = { _ in return 10 }
socket.reconnectTimer = mockTimeoutTimer
socket.skipHeartbeat = true
mockWebSocket.readyState = .open
socket.connect()
}
it("parses raw message and triggers channel event", closure: {
let targetChannel = socket.channel("topic")
let otherChannel = socket.channel("off-topic")
var targetMessage: Message?
targetChannel.on("event", callback: { (msg) in targetMessage = msg })
var otherMessage: Message?
otherChannel.on("event", callback: { (msg) in otherMessage = msg })
let data: [Any?] = [nil, nil, "topic", "event", ["status": "ok", "response": ["one": "two"]]]
let rawMessage = toWebSocketText(data: data)
socket.onConnectionMessage(rawMessage)
expect(targetMessage?.topic).to(equal("topic"))
expect(targetMessage?.event).to(equal("event"))
expect(targetMessage?.payload["one"] as? String).to(equal("two"))
expect(otherMessage).to(beNil())
})
it("triggers onMessage callbacks", closure: {
var message: Message?
socket.onMessage(callback: { (msg) in message = msg })
let data: [Any?] = [nil, nil, "topic", "event", ["status": "ok", "response": ["one": "two"]]]
let rawMessage = toWebSocketText(data: data)
socket.onConnectionMessage(rawMessage)
expect(message?.topic).to(equal("topic"))
expect(message?.event).to(equal("event"))
expect(message?.payload["one"] as? String).to(equal("two"))
})
it("clears pending heartbeat", closure: {
socket.pendingHeartbeatRef = "5"
let rawMessage = "[null,\"5\",\"phoenix\",\"phx_reply\",{\"response\":{},\"status\":\"ok\"}]"
socket.onConnectionMessage(rawMessage)
expect(socket.pendingHeartbeatRef).to(beNil())
})
}
}
}
| mit |
michalkonturek/MKUnits | MKUnits/Classes/LengthUnit.swift | 1 | 3534 | //
// LengthUnit.swift
// MKUnits
//
// Copyright (c) 2016 Michal Konturek <michal.konturek@gmail.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
public final class LengthUnit: Unit {
/**
Returns kilometer `[km]` length unit.
- author: Michal Konturek
*/
public static var kilometer: LengthUnit {
return LengthUnit(
name: "kilometer",
symbol: "km",
ratio: NSDecimalNumber(mantissa: 1, exponent: 3, isNegative: false)
)
}
/**
Returns meter `[m]` length unit.
- important: This is a base unit.
- author: Michal Konturek
*/
public static var meter: LengthUnit {
return LengthUnit(
name: "meter",
symbol: "m",
ratio: NSDecimalNumber.one
)
}
/**
Returns centimeter `[cm]` length unit.
- author: Michal Konturek
*/
public static var centimeter: LengthUnit {
return LengthUnit(
name: "centimeter",
symbol: "cm",
ratio: NSDecimalNumber(mantissa: 1, exponent: -2, isNegative: false)
)
}
/**
Returns millimeter `[mm]` length unit.
- author: Michal Konturek
*/
public static var millimeter: LengthUnit {
return LengthUnit(
name: "millimeter",
symbol: "mm",
ratio: NSDecimalNumber(mantissa: 1, exponent: -3, isNegative: false)
)
}
}
extension ExpressibleByIntegerLiteral {
/**
Returns instance converted as kilometer quantity.
- author: Michal Konturek
*/
public func kilometer() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: LengthUnit.kilometer)
}
/**
Returns instance converted as meter quantity.
- author: Michal Konturek
*/
public func meter() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: LengthUnit.meter)
}
/**
Returns instance converted as centimeter quantity.
- author: Michal Konturek
*/
public func centimeter() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: LengthUnit.centimeter)
}
/**
Returns instance converted as millimeter quantity.
- author: Michal Konturek
*/
public func millimeter() -> Quantity {
return Quantity(amount: self as! NSNumber, unit: LengthUnit.millimeter)
}
}
| mit |
spweau/Test_DYZB | Test_DYZB/Test_DYZB/Classes/Home/View/RecommendGameView.swift | 1 | 623 | //
// RecommendGameView.swift
// Test_DYZB
//
// Created by Spweau on 2017/2/25.
// Copyright © 2017年 sp. All rights reserved.
//
import UIKit
class RecommendGameView: UIView {
override func awakeFromNib() {
super.awakeFromNib()
// 让控件不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
}
}
extension RecommendGameView {
class func recommendGameView() -> RecommendGameView {
return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)!.first as! RecommendGameView
}
}
| mit |
Legoless/iOS-Course | 2015-1/Lesson14/ThreadingPlay/ThreadingPlay/MyOperation.swift | 1 | 539 | //
// MyOperation.swift
// ThreadingPlay
//
// Created by Dal Rupnik on 26/11/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import UIKit
class MyOperation: NSOperation {
var progressView : UIProgressView?
var factor : Int = 5
override func main() {
for var i = 0; i <= factor; i++ {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.progressView!.progress = (Float(i) / Float(self.factor))
})
sleep(1)
}
}
}
| mit |
SparkAppStudio/SparkKit | SparkKit/BasicButton.swift | 1 | 1238 | //
// Copyright © 2017 Spark App Studio. All rights reserved.
//
import UIKit
@IBDesignable
class BasicButton: UIButton {
let rounded: CGFloat = 12
override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
func sharedInit() {
titleLabel?.textColor = UIColor.white
}
override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()!
let inset = rect.insetBy(dx: 1, dy: 1)
let rounded = UIBezierPath(roundedRect: inset, cornerRadius: self.rounded)
UIColor.blue.setFill()
ctx.addPath(rounded.cgPath)
ctx.fillPath()
UIColor.orange.setStroke()
ctx.addPath(rounded.cgPath)
ctx.strokePath()
}
override var intrinsicContentSize: CGSize {
if let string = titleLabel?.text as
NSString? {
let stringSize = string.size(withAttributes: [.font: titleLabel!.font])
return CGSize(width: rounded * 2 + ceil(stringSize.width), height: rounded * 2 + ceil(stringSize.height))
}
return super.intrinsicContentSize
}
}
| mit |
fs/FSHelper | FSHelpersTests/Tests/Extensions/FSE+NSObjectTests.swift | 1 | 1141 | //
// FSE+NSObjectTests.swift
// FSHelpers
//
// Created by Sergey Nikolaev on 04.05.16.
// Copyright © 2016 FlatStack. All rights reserved.
//
import XCTest
@testable import FSHelpers
class FSE_NSObjectTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testClassName_Class () {
let stringClass = NSString.self
let arrayClass = NSArray.self
XCTAssertEqual(stringClass.fs_className , NSStringFromClass(stringClass).components(separatedBy: ".").last!)
XCTAssertEqual(arrayClass.fs_className , NSStringFromClass(arrayClass).components(separatedBy: ".").last!)
}
func testClassName_Object () {
let stringObject = NSString()
let arrayObject = NSArray()
XCTAssertEqual(stringObject.fs_className , NSStringFromClass(type(of: stringObject)).components(separatedBy: ".").last!)
XCTAssertEqual(arrayObject.fs_className , NSStringFromClass(type(of: arrayObject)).components(separatedBy: ".").last!)
}
}
| mit |
RajmohanKathiresan/emotiphor_ios | Emotiphor/ViewController/CreatorViewController.swift | 1 | 5875 | //
// CreatorViewController.swift
// Emotiphor
//
// Created by Rajmohan Kathiresan on 13/09/16.
// Copyright © 2016 Rajmohan Kathiresan. All rights reserved.
//
import UIKit
import EmotCore
class CreatorViewController : UIViewController {
static let kStoryboardName = "Creator"
static let kControllerIdentifier = "CreatorViewController"
@IBOutlet weak var emoticonView: UIImageView!
@IBOutlet weak var historyCollectionView: UICollectionView!
@IBOutlet weak var backBarButton: UIBarButtonItem!
var history:[RMEmoji] = [RMEmoji]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Collage"
self.applyTheme()
self.backBarButton.target = self
self.backBarButton.action = #selector(self.backAction(_:))
let searchButton = UIBarButtonItem(image: UIImage(named:"search"), style: .plain, target: self, action: #selector(CreatorViewController.searchTapAction(_:)))
searchButton.tintColor = UIColor.white
self.navigationItem.rightBarButtonItem = searchButton
self.emoticonView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CreatorViewController.changeEmojiAction(gesture:))))
}
@objc fileprivate func backAction(_ sender:AnyObject?) {
_ = self.navigationController?.popViewController(animated: true)
}
fileprivate func applyTheme() {
self.historyCollectionView.backgroundColor = UIColor.white
let navigationBar = self.navigationController?.navigationBar
navigationBar?.backgroundColor = ApplicationTheme.color()
navigationBar?.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
self.emoticonView.tintColor = UIColor.lightGray
}
fileprivate func addToHistory(emoji:RMEmoji) {
history.insert(emoji, at: 0)
historyCollectionView.reloadData()
//Save tp Disk
// saveToDisk(emoji)
}
fileprivate func randomizeColor() {
let redValue:CGFloat = CGFloat(arc4random()%255)/255.0
let blueValue:CGFloat = CGFloat(arc4random()%255)/255.0
let greenValue:CGFloat = CGFloat(arc4random()%255)/255.0
let randomColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)
self.emoticonView.backgroundColor = randomColor
}
/// TODO: Need Refinements
fileprivate func getImageFromView() -> UIImage {
let scale = UIScreen.main.nativeScale
print(scale)
let actualSize = self.emoticonView.bounds.size
print("\(actualSize.width):\(actualSize.height)")
UIGraphicsBeginImageContextWithOptions(actualSize, false, scale)
self.emoticonView.drawHierarchy(in: self.emoticonView.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
fileprivate func saveToDisk(_ emoticon:RMEmoji) {
let image = getImageFromView()
let filemanager = FileManager.default
let path = filemanager.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first!
print(path)
let directoryName = "emotiphor"
let directoryPath = path.appendingPathComponent(directoryName)
print(directoryPath.path)
do {
try filemanager.createDirectory(atPath: directoryPath.path, withIntermediateDirectories:false, attributes: nil)
} catch {
print("Folder already exists")
}
let filename = emoticon.unicode + ".png"
let fileurl = directoryPath.appendingPathComponent("\(filename)")
print(fileurl.path)
do {
try UIImagePNGRepresentation(image)!.write(to: URL(fileURLWithPath: fileurl.path), options: NSData.WritingOptions.atomic)
} catch {
print("Issues writing to file")
}
}
func searchTapAction(_:UIBarButtonItem) {
self.searchEmoji()
}
func changeEmojiAction(gesture:UITapGestureRecognizer) {
if gesture.state == .ended {
self.searchEmoji()
}
}
private func searchEmoji() {
let searchVC = UIViewController.GetViewController(instoryboard: SearchEmojiViewController.kStoryboardName, withController: SearchEmojiViewController.kControllerIdentifier) as! SearchEmojiViewController
searchVC.delegate = self
self.present(searchVC, animated: true, completion: nil)
}
}
extension CreatorViewController : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return history.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmojiCell.kIdentifier, for: indexPath) as! EmojiCell
cell.setContent(withEmoji: history[(indexPath as NSIndexPath).row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 40.0,height: 40.0)
}
}
extension CreatorViewController : SearchEmojiDelegate {
func searchEmojiDidCancel(sender: AnyObject?) {
//TODO:
}
func searchEmojiDidSelectEmoji(emoji: RMEmoji, sender: AnyObject?) {
self.addToHistory(emoji: emoji)
self.emoticonView.image = UIImage(named: emoji.unicode)
}
}
| mpl-2.0 |
rsaenzi/MyBankManagementApp | MyBankManagementApp/MyBankManagementApp/ReportSelectClientVC.swift | 1 | 1399 | //
// ReportSelectClientVC.swift
// MyBankManagementApp
//
// Created by Rigoberto Sáenz Imbacuán on 1/31/16.
// Copyright © 2016 Rigoberto Saenz Imbacuan. All rights reserved.
//
import UIKit
class ReportSelectClientVC: UITableViewController {
// -------------------------
// UIViewController
// -------------------------
override func viewWillAppear(animated: Bool) { // Called when the view is about to made visible. Default does nothing
self.tableView.reloadData()
}
// -------------------------
// UITableViewController
// -------------------------
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
Bank.instance.setSelectedClientId(indexPath.row)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Bank.instance.clients.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
// Cell Color
cell.backgroundColor = View.clientsColor
// Cell Content
cell.textLabel?.text = Bank.instance.clients[indexPath.row].name
return cell
}
} | mit |
practicalswift/swift | test/ParseableInterface/ModuleCache/module-cache-errors-in-importing-file.swift | 2 | 1009 | // RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/modulecache)
//
// Setup builds a parseable interface for a module SomeModule (built from some-module.swift).
// This test checks we still build and load its corresponding .swiftmodule when the file that imports it contains an error prior to the import statement.
// Setup phase 1: Write the input file.
//
// RUN: echo 'public func SomeFunc() -> Int { return 42; }' >>%t/some-module.swift
// Setup phase 2: build the module.
//
// RUN: %target-swift-frontend -I %t -emit-parseable-module-interface-path %t/SomeModule.swiftinterface -module-name SomeModule %t/some-module.swift -emit-module -o /dev/null
// Actual test: compile and verify the import succeeds (i.e. we only report the error in this file)
//
// RUN: %target-swift-frontend -typecheck -verify -I %t -module-cache-path %t/modulecache -enable-parseable-module-interface %s
unresolved // expected-error {{use of unresolved identifier 'unresolved'}}
import SomeModule
print(SomeFunc())
| apache-2.0 |
billdonner/sheetcheats9 | sc9/InterAppCommunications.swift | 1 | 2067 | //
// InterAppCommunications
// stories
//
// Created by bill donner on 7/18/15.
// Copyright © 2015 shovelreadyapps. All rights reserved.
//
import Foundation
//typealias ExternalStory = Dictionary<String,String>
typealias ExternalTile = [String:String]
typealias ExTilePayload = [ExternalTile]
let SuiteNameForDataModel = "group.com.midnightrambler.stories"
enum IACommunications:Error {
case generalFailure
case restoreFailure
}
class InterAppCommunications {
class var shared: InterAppCommunications {
struct Singleton {
static let sharedAppConfiguration = InterAppCommunications()
}
return Singleton.sharedAppConfiguration
}
// the data sent to watch or "messages" extension
var version: String = "0.0.1"
var name: String // typically matches section name
var items: ExTilePayload // the small tile data
//
init() {
name = ""; items = []
}
class func make(_ name:String ,items:ExTilePayload){
InterAppCommunications.shared.name = name
InterAppCommunications.shared.items = items
}
//put in special NSUserDefaults which can be shared
class func restore () throws {
if let defaults: UserDefaults = UserDefaults(suiteName: SuiteNameForDataModel),
let name = (defaults.object(forKey: "name") as? String),
let items = (defaults.object(forKey: "items") as? ExTilePayload)
{
// version check goes here
InterAppCommunications.make(name,items:items)
return
}
else {throw IACommunications.restoreFailure}
}
class func save (_ name:String,items:ExTilePayload) {// aka send to other device/panel
InterAppCommunications.make(name,items:items)
let defaults: UserDefaults = UserDefaults(suiteName:SuiteNameForDataModel)!
defaults.set( InterAppCommunications.shared.version, forKey: "version")
defaults.set( name, forKey: "name")
defaults.set( items, forKey: "items")
}
}
| apache-2.0 |
460467069/smzdm | 什么值得买7.1.1版本/什么值得买(5月12日)/Classes/Utills/SwiftNetwork/ResponseModel.swift | 1 | 172 | //
// ResponseModel.swift
// 什么值得买
//
// Created by Wang_Ruzhou on 2018/5/29.
// Copyright © 2018年 Wang_ruzhou. All rights reserved.
//
import Foundation
| mit |
jopamer/swift | test/Generics/protocol_requirement_signatures.swift | 1 | 3319 | // RUN: %target-typecheck-verify-swift
// RUN: %target-typecheck-verify-swift -debug-generic-signatures > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
// CHECK-LABEL: .P1@
// CHECK-NEXT: Requirement signature: <Self>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0>
protocol P1 {}
// CHECK-LABEL: .P2@
// CHECK-NEXT: Requirement signature: <Self>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0>
protocol P2 {}
// CHECK-LABEL: .P3@
// CHECK-NEXT: Requirement signature: <Self>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0>
protocol P3 {}
// basic protocol
// CHECK-LABEL: .Q1@
// CHECK-NEXT: Requirement signature: <Self where Self.X : P1>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0.X : P1>
protocol Q1 {
associatedtype X: P1 // expected-note {{declared here}}
}
// inheritance
// CHECK-LABEL: .Q2@
// CHECK-NEXT: Requirement signature: <Self where Self : Q1>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q1>
protocol Q2: Q1 {}
// inheritance without any new requirements
// CHECK-LABEL: .Q3@
// CHECK-NEXT: Requirement signature: <Self where Self : Q1>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q1>
protocol Q3: Q1 {
associatedtype X
}
// inheritance adding a new conformance
// CHECK-LABEL: .Q4@
// CHECK-NEXT: Requirement signature: <Self where Self : Q1, Self.X : P2>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q1, τ_0_0.X : P2>
protocol Q4: Q1 {
associatedtype X: P2 // expected-warning{{redeclaration of associated type 'X'}}
// expected-note@-1 2{{'X' declared here}}
}
// multiple inheritance
// CHECK-LABEL: .Q5@
// CHECK-NEXT: Requirement signature: <Self where Self : Q2, Self : Q3, Self : Q4>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0 : Q3, τ_0_0 : Q4>
protocol Q5: Q2, Q3, Q4 {}
// multiple inheritance without any new requirements
// CHECK-LABEL: .Q6@
// CHECK-NEXT: Requirement signature: <Self where Self : Q2, Self : Q3, Self : Q4>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0 : Q3, τ_0_0 : Q4>
protocol Q6: Q2, // expected-note{{conformance constraint 'Self.X': 'P1' implied here}}
Q3, Q4 {
associatedtype X: P1 // expected-warning{{redundant conformance constraint 'Self.X': 'P1'}}
// expected-warning@-1{{redeclaration of associated type 'X' from protocol 'Q4' is}}
}
// multiple inheritance with a new conformance
// CHECK-LABEL: .Q7@
// CHECK-NEXT: Requirement signature: <Self where Self : Q2, Self : Q3, Self : Q4, Self.X : P3>
// CHECK-NEXT: Canonical requirement signature: <τ_0_0 where τ_0_0 : Q2, τ_0_0 : Q3, τ_0_0 : Q4, τ_0_0.X : P3>
protocol Q7: Q2, Q3, Q4 {
associatedtype X: P3 // expected-warning{{redeclaration of associated type 'X'}}
}
// SR-5945
class SomeBaseClass {}
// CHECK-DAG: .P4@
// CHECK-NEXT: Requirement signature: <Self where Self == Self.BType.AType, Self.BType : P5, Self.Native : SomeBaseClass>
protocol P4 {
associatedtype Native : SomeBaseClass
associatedtype BType : P5 where BType.AType == Self
}
// CHECK-DAG: .P5@
// CHECK-NEXT: <Self where Self == Self.AType.BType, Self.AType : P4>
protocol P5 {
associatedtype AType : P4 where AType.BType == Self
}
| apache-2.0 |
blkbrds/intern09_final_project_tung_bien | MyApp/View/Controls/CustomCells/SearchTableViewCell/SearchTableViewCell.swift | 1 | 805 | //
// SearchTableViewCell.swift
// MyApp
//
// Created by asiantech on 8/30/17.
// Copyright © 2017 Asian Tech Co., Ltd. All rights reserved.
//
import UIKit
class SearchTableViewCell: TableCell {
// MARK: - Properties
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
var viewModel: SearchCellViewModel? {
didSet {
updateView()
}
}
// MARK: - LifeCycle
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
// MARK: - Private
private func updateView() {
guard let viewModel = viewModel else { return }
nameLabel.text = viewModel.name
priceLabel.text = "\(viewModel.price.formattedWithSeparator()) \(App.String.UnitCurrency)"
}
}
| mit |
networkextension/SFSocket | SFSocket/tcp/ProxyConnector.swift | 1 | 7690 | //
// ProxyConnector.swift
// Surf
//
// Created by yarshure on 16/1/7.
// Copyright © 2016年 yarshure. All rights reserved.
//
import Foundation
import AxLogger
import NetworkExtension
import Security
public class ProxyConnector: NWTCPSocket,NWTCPConnectionAuthenticationDelegate {
var proxy:SFProxy
var tlsSupport:Bool = false
var targetHost:String = ""
var targetPort:UInt16 = 0
var tlsEvaluate:Bool = false
#if os(iOS)
let acceptableCipherSuites:Set<NSNumber> = [
NSNumber(value: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256),
NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
NSNumber(value: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA),
NSNumber(value: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256),
NSNumber(value: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA),
NSNumber(value: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384),
NSNumber(value: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384),
NSNumber(value: TLS_RSA_WITH_AES_256_GCM_SHA384),
NSNumber(value: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384),
NSNumber(value: TLS_DH_RSA_WITH_AES_256_GCM_SHA384)
// public var TLS_RSA_WITH_AES_256_GCM_SHA384: SSLCipherSuite { get }
// public var TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: SSLCipherSuite { get }
// public var TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: SSLCipherSuite { get }
// public var TLS_DH_RSA_WITH_AES_128_GCM_SHA256: SSLCipherSuite { get }
// public var TLS_DH_RSA_WITH_AES_256_GCM_SHA384: SSLCipherSuite { get }
]
#else
let acceptableCipherSuites:Set<NSNumber> = [
NSNumber(value: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256),
NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
NSNumber(value: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
NSNumber(value: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA),
NSNumber(value: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256),
NSNumber(value: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA)
]
#endif
var pFrontAddress:String = ""
var pFrontPort:UInt16 = 0
init(p:SFProxy) {
proxy = p
super.init()
//cIDFunc()
}
override public func start() {
guard let port = Int(proxy.serverPort) else {
return
}
if proxy.type == .SS {
if !proxy.serverIP.isEmpty{
//by pass dns resolv
try! self.connectTo(proxy.serverIP, port: port, enableTLS: false, tlsSettings: nil)
}else {
try! self.connectTo(proxy.serverAddress, port: port, enableTLS: false, tlsSettings: nil)
}
}else {
try! self.connectTo(proxy.serverAddress, port: port, enableTLS: proxy.tlsEnable, tlsSettings: nil)
}
}
override public func connectTo(_ host: String, port: Int, enableTLS: Bool, tlsSettings: [NSObject : AnyObject]?) throws {
if enableTLS {
let endpoint = NWHostEndpoint(hostname: host, port: "\(port)")
let tlsParameters = NWTLSParameters()
if let tlsSettings = tlsSettings as? [String: AnyObject] {
tlsParameters.setValuesForKeys(tlsSettings)
}else {
tlsParameters.sslCipherSuites = acceptableCipherSuites
}
let v = SSLProtocol.tlsProtocol12
tlsParameters.minimumSSLProtocolVersion = Int(v.rawValue)
guard let c = RawSocketFactory.TunnelProvider?.createTCPConnection(to: endpoint, enableTLS: enableTLS, tlsParameters: tlsParameters, delegate: nil) else {
// This should only happen when the extension is already stoped and `RawSocketFactory.TunnelProvider` is set to `nil`.
return
}
connection = c
connection!.addObserver(self, forKeyPath: "state", options: [.initial, .new], context: nil)
}else {
do {
try super.connectTo(host, port: port, enableTLS: false, tlsSettings: tlsSettings)
}catch let e as NSError{
throw e
}
}
}
@nonobjc public func shouldEvaluateTrustForConnection(connection: NWTCPConnection) -> Bool{
return true
}
@nonobjc public func evaluateTrustForConnection(connection: NWTCPConnection, peerCertificateChain: [AnyObject], completionHandler completion: @escaping (SecTrust) -> Void){
let myPolicy = SecPolicyCreateSSL(true, nil)//proxy.serverAddress
var possibleTrust: SecTrust?
let x = SecTrustCreateWithCertificates(peerCertificateChain.first!, myPolicy,
&possibleTrust)
guard let remoteAddress = connection.remoteAddress as? NWHostEndpoint else {
completion(possibleTrust!)
return
}
AxLogger.log("debug :\(remoteAddress.hostname)", level: .Debug)
if x != 0 {
AxLogger.log("debug :\(remoteAddress.hostname) \(x)", level: .Debug)
}
if let trust = possibleTrust {
//let's do test by ourself first
var trustResult : SecTrustResultType = .invalid
let r = SecTrustEvaluate(trust, &trustResult)
if r != 0{
AxLogger.log("debug :\(remoteAddress.hostname) error code:\(r)", level: .Debug)
}
if trustResult == .proceed {
AxLogger.log("debug :\(remoteAddress.hostname) Proceed", level: .Debug)
}else {
AxLogger.log("debug :\(remoteAddress.hostname) Proceed error", level: .Debug)
}
//print(trustResult) // the result is 5, is it
//kSecTrustResultRecoverableTrustFailure?
completion(trust)
}else {
AxLogger.log("debug :\(remoteAddress.hostname) error", level: .Debug)
}
}
// override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
// let x = connection.endpoint as! NWHostEndpoint
// if keyPath == "state" {
//
//
// var stateString = ""
// switch connection.state {
// case .Connected:
// stateString = "Connected"
// if proxy.tlsEnable == true && proxy.type != .SS {
// AxLogger.log("\(cIDString) host:\(x) tls handshake passed", level: .Debug)
// }
// queueCall {
// self.socketConnectd()
// }
//
// case .Disconnected:
// stateString = "Disconnected"
// cancel()
// case .Cancelled:
// stateString = "Cancelled"
// queueCall {
// let delegate = self.delegate
// self.delegate = nil
// delegate?.didDisconnect(self)
//
// }
// case .Connecting:
// stateString = "Connecting"
// case .Waiting:
// stateString = "Waiting"
// case .Invalid:
// stateString = "Invalid"
//
// }
// AxLogger.log("\(cIDString) host:\(x) " + stateString, level: .Debug)
// }
//
// }
}
| bsd-3-clause |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift | 1 | 16960 | //
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.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.
#if !os(watchOS)
#if os(macOS)
import AppKit
#else
import UIKit
#endif
extension KingfisherWrapper where Base: KFCrossPlatformImageView {
// MARK: Setting Image
/// Sets an image to the image view with a `Source`.
///
/// - Parameters:
/// - source: The `Source` object defines data information from network or a data provider.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
/// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
///
/// ```
/// // Set image from a network source.
/// let url = URL(string: "https://example.com/image.png")!
/// imageView.kf.setImage(with: .network(url))
///
/// // Or set image from a data provider.
/// let provider = LocalFileImageDataProvider(fileURL: fileURL)
/// imageView.kf.setImage(with: .provider(provider))
/// ```
///
/// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code
/// above is equivalent to:
///
/// ```
/// imageView.kf.setImage(with: url)
/// imageView.kf.setImage(with: provider)
/// ```
///
/// Internally, this method will use `KingfisherManager` to get the source.
/// Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with source: Source?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
mutatingSelf.placeholder = placeholder
mutatingSelf.taskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil
if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet {
// Always set placeholder while there is no image/placeholder yet.
mutatingSelf.placeholder = placeholder
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.taskIdentifier = issuedIdentifier
if base.shouldPreloadAllAnimation() {
options.preloadAllAnimationData = true
}
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
if let provider = ImageProgressiveProvider(options, refresh: { image in
self.base.image = image
}) {
options.onDataReceived = (options.onDataReceived ?? []) + [provider]
}
options.onDataReceived?.forEach {
$0.onShouldApply = { issuedIdentifier == self.taskIdentifier }
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
maybeIndicator?.stopAnimatingView()
guard issuedIdentifier == self.taskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.imageTask = nil
mutatingSelf.taskIdentifier = nil
switch result {
case .success(let value):
guard self.needsTransition(options: options, cacheType: value.cacheType) else {
mutatingSelf.placeholder = nil
self.base.image = value.image
completionHandler?(result)
return
}
self.makeTransition(image: value.image, transition: options.transition) {
completionHandler?(result)
}
case .failure:
if let image = options.onFailureImage {
self.base.image = image
}
completionHandler?(result)
}
}
}
)
mutatingSelf.imageTask = task
return task
}
/// Sets an image to the image view with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters
/// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
///
/// ```
/// let url = URL(string: "https://example.com/image.png")!
/// imageView.kf.setImage(with: url)
/// ```
///
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with resource: Resource?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: resource.map { .network($0) },
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
/// Sets an image to the image view with a data provider.
///
/// - Parameters:
/// - provider: The `ImageDataProvider` object contains information about the data.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// Internally, this method will use `KingfisherManager` to get the image data, from either cache
/// or the data provider. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with provider: ImageDataProvider?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: provider.map { .provider($0) },
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
// MARK: Cancelling Downloading Task
/// Cancels the image download task of the image view if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelDownloadTask() {
imageTask?.cancel()
}
private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool {
switch options.transition {
case .none:
return false
#if !os(macOS)
default:
if options.forceTransition { return true }
if cacheType == .none { return true }
return false
#endif
}
}
private func makeTransition(image: KFCrossPlatformImage, transition: ImageTransition, done: @escaping () -> Void) {
#if !os(macOS)
// Force hiding the indicator without transition first.
UIView.transition(
with: self.base,
duration: 0.0,
options: [],
animations: { self.indicator?.stopAnimatingView() },
completion: { _ in
var mutatingSelf = self
mutatingSelf.placeholder = nil
UIView.transition(
with: self.base,
duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: { transition.animations?(self.base, image) },
completion: { finished in
transition.completion?(finished)
done()
}
)
}
)
#else
done()
#endif
}
}
// MARK: - Associated Object
private var taskIdentifierKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var placeholderKey: Void?
private var imageTaskKey: Void?
extension KingfisherWrapper where Base: KFCrossPlatformImageView {
// MARK: Properties
public private(set) var taskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &taskIdentifierKey, box)
}
}
/// Holds which indicator type is going to be used.
/// Default is `.none`, means no indicator will be shown while downloading.
public var indicatorType: IndicatorType {
get {
return getAssociatedObject(base, &indicatorTypeKey) ?? .none
}
set {
switch newValue {
case .none: indicator = nil
case .activity: indicator = ActivityIndicator()
case .image(let data): indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator): indicator = anIndicator
}
setRetainedAssociatedObject(base, &indicatorTypeKey, newValue)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
public private(set) var indicator: Indicator? {
get {
let box: Box<Indicator>? = getAssociatedObject(base, &indicatorKey)
return box?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if let newIndicator = newValue {
// Set default indicator layout
let view = newIndicator.view
base.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.centerXAnchor.constraint(
equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true
view.centerYAnchor.constraint(
equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true
newIndicator.view.isHidden = true
}
// Save in associated object
// Wrap newValue with Box to workaround an issue that Swift does not recognize
// and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init))
}
}
private var imageTask: DownloadTask? {
get { return getAssociatedObject(base, &imageTaskKey) }
set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
}
/// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while
/// it is downloading an image.
public private(set) var placeholder: Placeholder? {
get { return getAssociatedObject(base, &placeholderKey) }
set {
if let previousPlaceholder = placeholder {
previousPlaceholder.remove(from: base)
}
if let newPlaceholder = newValue {
newPlaceholder.add(to: base)
} else {
base.image = nil
}
setRetainedAssociatedObject(base, &placeholderKey, newValue)
}
}
}
@objc extension KFCrossPlatformImageView {
func shouldPreloadAllAnimation() -> Bool { return true }
}
extension KingfisherWrapper where Base: KFCrossPlatformImageView {
/// Gets the image URL bound to this image view.
@available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.")
public private(set) var webURL: URL? {
get { return nil }
set { }
}
}
#endif
| mit |
nodes-vapor/jwt-keychain | Sources/Keychain/LoginRequest.swift | 1 | 1286 | import Vapor
import Submissions
public protocol LoginRequest: AuthenticationRequest, ValidatableRequest {
typealias Model = User
static var hashedPasswordKey: KeyPath<Model, String> { get }
var password: String { get }
func logIn(on request: Request) -> EventLoopFuture<Model>
}
public extension LoginRequest {
static func logIn(
on request: Request,
errorOnWrongPassword: @escaping @autoclosure () -> Error,
currentDate: Date = Date()
) -> EventLoopFuture<AuthenticationResponse<Model>> {
validated(on: request).flatMap { loginRequest in
loginRequest
.logIn(on: request)
.flatMap { user in
request.password.async
.verify(loginRequest.password, created: user[keyPath: hashedPasswordKey])
.flatMapThrowing { passwordsMatch in
guard passwordsMatch else { throw errorOnWrongPassword() }
return try authenticationResponse(
for: user,
on: request,
currentDate: currentDate
)
}
}
}
}
}
| mit |
tdjackey/TipCalculator | TipCalculatorTests/TipCalculatorTests.swift | 1 | 921 | //
// TipCalculatorTests.swift
// TipCalculatorTests
//
// Created by Main Account on 12/18/14.
// Copyright (c) 2014 Razeware LLC. All rights reserved.
//
import UIKit
import XCTest
class TipCalculatorTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
YuanZhu-apple/ResearchKit | Testing/ORKTest/ORKTest/Charts/ChartTableViewCells.swift | 15 | 2049 | /*
Copyright (c) 2015, James Cox. 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(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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 OWNER 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 UIKit
import ResearchKit
class PieChartTableViewCell: UITableViewCell {
@IBOutlet weak var pieChartView: ORKPieChartView!
}
class GraphChartTableViewCell: UITableViewCell {
@IBOutlet weak var graphChartView: ORKGraphChartView!
}
class DiscreteGraphChartTableViewCell: GraphChartTableViewCell { }
class LineGraphChartTableViewCell: GraphChartTableViewCell { }
class BarGraphChartTableViewCell: GraphChartTableViewCell { }
| bsd-3-clause |
ssmali1505/Web-service-call-in-swift | WebServiceCalls/WebServiceCalls/APIHelper.swift | 1 | 8737 | //
// APIHelper.swift
// WebServiceCalls
//
// Created by SANDY on 02/01/15.
// Copyright (c) 2015 Evgeny Nazarov. All rights reserved.
//
import Foundation
@objc protocol APIHelperDelegate
{
/// This will return response from webservice if request successfully done to server
func apiHelperResponseSuccess(apihelper:APIHelper)
/// This is for Fail request or server give any error
optional func apiHelperResponseFail(connection: NSURLConnection?,error: NSError)
}
public class APIHelper: NSObject,NSURLConnectionDelegate
{
public enum MethodType : Int{
case GET = 1
case POST = 2
case JSON = 3
case IMAGE = 4
}
let timeinterval:Int = 239
private var objConnection:NSURLConnection?
private var objURL:NSString!
private var objParameter:NSMutableDictionary?
private var objUtility:APIUtilityHelper!
public var responseData:NSMutableData!
var delegate:APIHelperDelegate?
public var ApiIdentifier:NSString!=""
override init()
{
super.init();
objUtility=APIUtilityHelper()
}
// MARK: Method Web API
/// Call GET request webservice (urlMethodOrFile, parameters:,apiIdentifier,delegate)
func APIHelperAPI_GET(urlMethodOrFile:NSString, parameters:NSMutableDictionary?,apiIdentifier:NSString,delegate:APIHelperDelegate!)
{
self.objParameter=parameters
self.ApiIdentifier=apiIdentifier
self.delegate=delegate
var strParam :NSString? = objUtility!.JSONStringify(objParameter!)
if (strParam != "")
{
strParam = "?" + strParam!
}
var strURL:String = "\(urlMethodOrFile)" + strParam!
self.objURL=strURL
self.CallURL(nil, methodtype: MethodType.GET)
}
/// Call POST request webservice (urlMethodOrFile, parameters,apiIdentifier,delegate)
func APIHelperAPI_POST(urlMethodOrFile:NSString, parameters:NSMutableDictionary?,apiIdentifier:NSString,delegate:APIHelperDelegate!)
{
self.objParameter=parameters
self.ApiIdentifier=apiIdentifier
self.delegate=delegate
var strParam :NSString? = objUtility!.JSONStringify(objParameter!)
println("wenservice Post Input >>> \(strParam)")
var strURL:String = (urlMethodOrFile)
self.objURL=strURL
self.CallURL(strParam?.dataUsingEncoding(NSUTF8StringEncoding), methodtype: MethodType.POST);
}
/// Upload file and text data through webservice (urlMethodOrFile, parameters,parametersImage(dictionary of NSData),apiIdentifier,delegate)
func APIHelperAPI_FileUpload(urlMethodOrFile:NSString, parameters:NSMutableDictionary?,parametersImage:NSMutableDictionary?,apiIdentifier:NSString,delegate:APIHelperDelegate!)
{
self.objParameter=parameters
self.ApiIdentifier=apiIdentifier
self.delegate=delegate
var strParam :NSString? = objUtility!.JSONStringify(self.objParameter!)
var strURL:String = (urlMethodOrFile)
self.objURL=strURL
var body : NSMutableData?=NSMutableData()
var dicParam:NSDictionary = parameters!
var dicImageParam:NSDictionary = parametersImage!
var boundary:NSString? = "---------------------------14737809831466499882746641449"
// process text parameters
for (key, value) in dicParam {
body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!);
body?.appendData(("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!);
body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!);
}
//process images parameters
var i:Int=0
for (key, value) in dicImageParam {
body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!);
body?.appendData(("Content-Disposition: file; name=\"\(key)\"; filename=\"image.png\(i)\"\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!);
body?.appendData(("Content-Type: application/octet-stream\r\n\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!);
body?.appendData(value as NSData);
body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!);
}
body?.appendData(("\r\n--\(boundary)\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding)!);
self.CallURL(body!, methodtype: MethodType.IMAGE);
}
/// Call JSON webservice (urlMethodOrFile,json,apiIdentifier,delegate)
func APIHelperAPI_JSON(urlMethodOrFile:NSString, json:NSString?,apiIdentifier:NSString,delegate:APIHelperDelegate!)
{
self.ApiIdentifier=apiIdentifier
self.delegate=delegate
var strParam :NSString? = json
var strURL:String = urlMethodOrFile
self.objURL=strURL
self.CallURL(strParam?.dataUsingEncoding(NSUTF8StringEncoding),methodtype: MethodType.JSON)
}
private func CallURL(dataParam:NSData?,methodtype:MethodType)
{
//println(self.objURL)
if(!self.objUtility.isInternetAvailable())
{
println("INTERNET NOT AVAILABLE")
var error :NSError=NSError(domain: "INTERNET NOT AVAILABLE", code: 404, userInfo: nil)
delegate?.apiHelperResponseFail?(nil, error: error)
return;
}
var objurl = NSURL(string: self.objURL)
var request:NSMutableURLRequest = NSMutableURLRequest(URL:objurl!)
if(methodtype == MethodType.GET)
{//if simple GET method -- here we are not using strParam as it concenate with url already
request.timeoutInterval = NSTimeInterval(self.timeinterval)
request.HTTPMethod = "GET";
}
if(methodtype == MethodType.POST)
{//if simple POST method
// request.addValue("\(strParam?.length)", forHTTPHeaderField: "Content-length")
request.timeoutInterval = NSTimeInterval(self.timeinterval)
request.HTTPMethod = "POST";
request.HTTPBody=dataParam
}
if(methodtype == MethodType.JSON)
{//if JSON type webservice called
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// request.addValue("\(strParam?.length)", forHTTPHeaderField: "Content-length")
request.timeoutInterval = NSTimeInterval(self.timeinterval)
request.HTTPMethod = "POST";
request.HTTPBody=dataParam
}
if(methodtype == MethodType.IMAGE)
{//if webservice with Image Uploading
var boundary:NSString? = "---------------------------14737809831466499882746641449"
var contentType:NSString? = "multipart/form-data; boundary=\(boundary)"
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
request.timeoutInterval = NSTimeInterval(self.timeinterval)
request.HTTPMethod = "POST";
request.HTTPBody=dataParam
}
self.objConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)
self.responseData=NSMutableData()
}
// MARK: NSURLConnection
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse)
{
//println("response")
}
func connection(connection: NSURLConnection, didReceiveData data: NSData)
{
self.responseData.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection)
{
//println(NSDate().timeIntervalSince1970)
// println("json : \(NSString(data: self.responseData!, encoding: NSUTF8StringEncoding))")
delegate?.apiHelperResponseSuccess(self)
}
public func connection(connection: NSURLConnection, didFailWithError error: NSError)
{
println("error iHelperClass: \(error)");
delegate?.apiHelperResponseFail?(connection, error: error)
}
} | apache-2.0 |
vapor/vapor | Sources/Vapor/_Deprecations.swift | 1 | 200 |
// MARK: - Sessions
extension SessionData {
@available(*, deprecated, message: "use SessionData.init(initialData:)")
public init(_ data: [String: String]) { self.init(initialData: data) }
}
| mit |
forbidden404/FSOhanaAlert | FSOhanaAlert/FSOhanaCustomAlert.swift | 1 | 6417 | //
// FSOhanaCustomAlert.swift
// FSOhanaAlert
//
// Created by Francisco Soares on 26/10/17.
// Copyright © 2017 Francisco Soares. All rights reserved.
//
import UIKit
public class FSOhanaCustomAlert: UIView {
@IBOutlet weak var ohanaImageView: UIImageView!
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var leftButton: UIButton!
@IBOutlet weak var rightButton: UIButton!
@IBOutlet weak var buttonStackView: UIStackView!
@IBOutlet weak var okButton: UIButton!
var hasOkButton: Bool = false {
willSet {
okButton.isHidden = !newValue
okButton.isUserInteractionEnabled = newValue
okButton.tintColor = FSOhanaButtonType.standard.color()
okButton.titleLabel?.font = FSOhanaButtonType.standard.font()
}
}
var completion: ((Any?, Error?) -> Void)? {
didSet {
leftButton.isHidden = false
rightButton.isHidden = false
leftButton.isUserInteractionEnabled = true
rightButton.isUserInteractionEnabled = true
hasOkButton = false
}
}
let nibName = "FSOhanaCustomAlert"
var contentView: UIView!
// MARK: Set Up View
public override init(frame: CGRect) {
super.init(frame: frame)
setUpView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpView()
}
public override func layoutSubviews() {
self.layoutIfNeeded()
if completion == nil && !hasOkButton {
self.buttonStackView.removeFromSuperview()
self.contentView.frame = CGRect(x: self.contentView.frame.origin.x, y: self.contentView.frame.origin.y, width: self.contentView.frame.size.width, height: self.contentView.frame.size.height - (self.buttonStackView.bounds.size.height/2.0))
}
// If there is no Ok Button
if !hasOkButton {
self.okButton.removeFromSuperview()
}
// Shadow
self.contentView.backgroundColor = UIColor.clear
for subview in self.contentView.subviews {
subview.backgroundColor = UIColor.clear
}
let shadowPath = UIBezierPath(rect: self.contentView.bounds)
self.contentView.layer.shadowColor = UIColor.black.cgColor
self.contentView.layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
self.contentView.layer.shadowOpacity = 0.5
self.contentView.layer.shadowPath = shadowPath.cgPath
// Corner
let border = UIView()
border.frame = self.contentView.bounds
border.layer.masksToBounds = true
border.clipsToBounds = true
border.layer.cornerRadius = 10
border.layer.backgroundColor = UIColor.white.cgColor
self.contentView.addSubview(border)
self.contentView.sendSubview(toBack: border)
}
public override func didMoveToSuperview() {
self.contentView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.15, animations: {
self.contentView.alpha = 1.0
self.contentView.transform = CGAffineTransform.identity
}) { _ in
if self.completion == nil && !self.hasOkButton {
let when = DispatchTime.now() + 3
DispatchQueue.main.asyncAfter(deadline: when) {
UIView.animate(withDuration: 0.20, delay: 0, options: .curveEaseOut, animations: {
self.contentView.alpha = 0.0
self.contentView.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
}) { _ in
self.removeFromSuperview()
}
}
}
}
}
private func setUpView() {
let bundle = Bundle(for: self.classForCoder)
let nib = UINib(nibName: self.nibName, bundle: bundle)
self.contentView = nib.instantiate(withOwner: self, options: nil).first as! UIView
contentView.frame = aspectRatio()
addSubview(contentView)
contentView.center = self.center
contentView.autoresizingMask = []
contentView.translatesAutoresizingMaskIntoConstraints = true
contentView.alpha = 0.0
textLabel.text = ""
textLabel.autoresizingMask = [.flexibleHeight, .flexibleWidth]
leftButton.isHidden = true
leftButton.autoresizingMask = [.flexibleHeight, .flexibleWidth]
rightButton.isHidden = true
rightButton.autoresizingMask = [.flexibleHeight, .flexibleWidth]
hasOkButton = false
okButton.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
private func aspectRatio() -> CGRect {
var frame = self.contentView.frame
while frame.width > self.frame.width {
frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width / 1.2, height: frame.height / 1.2)
}
return frame
}
public func set(image: UIImage) {
self.ohanaImageView.image = image
}
public func set(text: String) {
self.textLabel.text = text
self.textLabel.adjustsFontSizeToFitWidth = true
}
public func set(completion: @escaping ((Any?, Error?) -> Void), with titles: [String] = ["Cancel", "Take"], and types: [FSOhanaButtonType] = [.cancel, .standard]) {
self.completion = completion
leftButton.tintColor = types[0].color()
rightButton.tintColor = types[1].color()
leftButton.titleLabel?.font = types[0].font()
rightButton.titleLabel?.font = types[1].font()
leftButton.setTitle(titles[0], for: .normal)
rightButton.setTitle(titles[1], for: .normal)
}
public func has(okButton: Bool) {
self.hasOkButton = okButton
}
@IBAction func leftButtonPressed(_ sender: UIButton) {
guard let completion = completion else {
return
}
completion(nil, FSError.LeftButton)
}
@IBAction func rightButtonPressed(_ sender: UIButton) {
guard let completion = completion else {
return
}
completion(self, FSError.RightButton)
}
@IBAction func okButtonPressed(_ sender: UIButton) {
self.removeFromSuperview()
}
}
| mit |
zhiquan911/chance_btc_wallet | chance_btc_wallet/Pods/Log/Source/Extensions/Themes.swift | 4 | 2525 | //
// Themes.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.
//
extension Themes {
public static let `default` = Theme(
trace: "#C8C8C8",
debug: "#0000FF",
info: "#00FF00",
warning: "#FFFB00",
error: "#FF0000"
)
public static let dusk = Theme(
trace: "#FFFFFF",
debug: "#526EDA",
info: "#93C96A",
warning: "#D28F5A",
error: "#E44347"
)
public static let midnight = Theme(
trace: "#FFFFFF",
debug: "#527EFF",
info: "#08FA95",
warning: "#EB905A",
error: "#FF4647"
)
public static let tomorrow = Theme(
trace: "#4D4D4C",
debug: "#4271AE",
info: "#718C00",
warning: "#EAB700",
error: "#C82829"
)
public static let tomorrowNight = Theme(
trace: "#C5C8C6",
debug: "#81A2BE",
info: "#B5BD68",
warning: "#F0C674",
error: "#CC6666"
)
public static let tomorrowNightEighties = Theme(
trace: "#CCCCCC",
debug: "#6699CC",
info: "#99CC99",
warning: "#FFCC66",
error: "#F2777A"
)
public static let tomorrowNightBright = Theme(
trace: "#EAEAEA",
debug: "#7AA6DA",
info: "#B9CA4A",
warning: "#E7C547",
error: "#D54E53"
)
}
| mit |
srosskopf/Geschmacksbildung | Geschmacksbildung/Geschmacksbildung/GlossaryTableController.swift | 1 | 4080 | //
// GlossaryTableController.swift
// Geschmacksbildung
//
// Created by Sebastian Roßkopf on 01.07.16.
// Copyright © 2016 sebastian rosskopf. All rights reserved.
//
import UIKit
protocol GlossaryTableControllerDelegate {
func termSelected(term: String)
}
class GlossaryTableController: UITableViewController {
var delegate: GlossaryTableControllerDelegate?
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 viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
if let text = cell?.textLabel?.text {
print("selected row: \(text)")
if let delegate = delegate {
if text.characters.count > 1 {
delegate.termSelected(text)
}
}
}
}
// MARK: - Table view data source
// override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return 0
// }
//
// override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// // #warning Incomplete implementation, return the number of rows
// return 0
// }
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
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.
}
*/
}
| mit |
kl/dehub | DeHubTests/LoginViewModelTest.swift | 2 | 3786 | //
// LoginDirectorTest.swift
// DeHubTests
//
// Created by Kalle Lindström on 05/06/16.
// Copyright © 2016 Dewire. All rights reserved.
//
// swiftlint:disable function_body_length
import XCTest
@testable import DeHub
@testable import Model
import RxSwift
import RxCocoa
import RxBlocking
import Quick
import Nimble
typealias LoginResult = () -> Observable<Void>
class LoginViewModelTests: QuickSpec {
override func spec() {
// MARK: Setup
var usernameInput: BehaviorSubject<String?>!
var passwordInput: BehaviorSubject<String?>!
var loginButtonInput: BehaviorSubject<Void>!
var resourceFactory: MockResourceFactory!
var viewModel: LoginViewModel!
var outputs: LoginViewModel.Outputs!
describe("the login view model") {
beforeEach {
usernameInput = BehaviorSubject(value: "")
passwordInput = BehaviorSubject(value: "")
loginButtonInput = BehaviorSubject(value: Void())
let state = State()
resourceFactory = MockResourceFactory()
let api = GistApi(resourceFactory: resourceFactory, state: state)
let services = Services(api: api, state: state)
viewModel = LoginViewModel(services: services)
outputs = viewModel.observe(inputs: LoginViewModel.Inputs(
username: ControlProperty<String?>(values: usernameInput, valueSink: AnyObserver { _ in }),
password: ControlProperty<String?>(values: passwordInput, valueSink: AnyObserver { _ in }),
loginPressed: ControlEvent<Void>(events: loginButtonInput)), bag: DisposeBag())
}
// MARK: Tests
it("disables the login button when username and password are not entered") {
usernameInput.onNext("")
passwordInput.onNext("")
try! expect(outputs.isLoginButtonEnabled.toBlocking().first()).to(beFalse())
}
it("enables the login button when username and password are entered") {
usernameInput.onNext("username")
passwordInput.onNext("password")
try! expect(outputs.isLoginButtonEnabled.toBlocking().first()).to(beTrue())
}
it("disables the login button after it is tapped") {
resourceFactory.setMockResponse(path: "gists", jsonFile: "gists")
usernameInput.onNext("username")
passwordInput.onNext("password")
loginButtonInput.onNext(())
try! expect(outputs.isLoginButtonEnabled.asObservable().take(2).toBlocking().last()).to(beFalse())
}
it("it enabled the login button again on a failed login") {
resourceFactory.setMockError(path: "gists", error: AnyError())
usernameInput.onNext("username")
passwordInput.onNext("password")
loginButtonInput.onNext(())
try! expect(outputs.isLoginButtonEnabled.asObservable().take(3).toBlocking().last()).to(beTrue())
}
it("signals that the login is successful") {
resourceFactory.setMockResponse(path: "gists", jsonFile: "gists")
usernameInput.onNext("username")
passwordInput.onNext("password")
loginButtonInput.onNext(Void())
try! expect(outputs.isLoggedIn.asObservable().take(2).toBlocking().last()).to(beTrue())
}
it("signals that the login failed") {
resourceFactory.setMockError(path: "gists", error: AnyError())
usernameInput.onNext("username")
passwordInput.onNext("password")
loginButtonInput.onNext(Void())
try! expect(outputs.isLoggedIn.asObservable().take(1).toBlocking().last()).to(beFalse())
}
}
}
}
| mit |
tache/SwifterSwift | Sources/Extensions/UIKit/UITableViewExtensions.swift | 1 | 5222 | //
// UITableViewExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/22/16.
// Copyright © 2016 SwifterSwift
//
#if os(iOS) || os(tvOS)
import UIKit
// MARK: - Properties
public extension UITableView {
/// SwifterSwift: Index path of last row in tableView.
public var indexPathForLastRow: IndexPath? {
return indexPathForLastRow(inSection: lastSection)
}
/// SwifterSwift: Index of last section in tableView.
public var lastSection: Int {
return numberOfSections > 0 ? numberOfSections - 1 : 0
}
}
// MARK: - Methods
public extension UITableView {
/// SwifterSwift: Number of all rows in all sections of tableView.
///
/// - Returns: The count of all rows in the tableView.
public func numberOfRows() -> Int {
var section = 0
var rowCount = 0
while section < numberOfSections {
rowCount += numberOfRows(inSection: section)
section += 1
}
return rowCount
}
/// SwifterSwift: IndexPath for last row in section.
///
/// - Parameter section: section to get last row in.
/// - Returns: optional last indexPath for last row in section (if applicable).
public func indexPathForLastRow(inSection section: Int) -> IndexPath? {
guard section >= 0 else {
return nil
}
guard numberOfRows(inSection: section) > 0 else {
return IndexPath(row: 0, section: section)
}
return IndexPath(row: numberOfRows(inSection: section) - 1, section: section)
}
/// Reload data with a completion handler.
///
/// - Parameter completion: completion handler to run after reloadData finishes.
public func reloadData(_ completion: @escaping () -> Void) {
UIView.animate(withDuration: 0, animations: {
self.reloadData()
}, completion: { _ in
completion()
})
}
/// SwifterSwift: Remove TableFooterView.
public func removeTableFooterView() {
tableFooterView = nil
}
/// SwifterSwift: Remove TableHeaderView.
public func removeTableHeaderView() {
tableHeaderView = nil
}
/// SwifterSwift: Scroll to bottom of TableView.
///
/// - Parameter animated: set true to animate scroll (default is true).
public func scrollToBottom(animated: Bool = true) {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height)
setContentOffset(bottomOffset, animated: animated)
}
/// SwifterSwift: Scroll to top of TableView.
///
/// - Parameter animated: set true to animate scroll (default is true).
public func scrollToTop(animated: Bool = true) {
setContentOffset(CGPoint.zero, animated: animated)
}
/// SwifterSwift: Dequeue reusable UITableViewCell using class name
///
/// - Parameter name: UITableViewCell type
/// - Returns: UITableViewCell object with associated class name (optional value)
public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type) -> T? {
return dequeueReusableCell(withIdentifier: String(describing: name)) as? T
}
/// SwiferSwift: Dequeue reusable UITableViewCell using class name for indexPath
///
/// - Parameters:
/// - name: UITableViewCell type.
/// - indexPath: location of cell in tableView.
/// - Returns: UITableViewCell object with associated class name.
public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T? {
return dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T
}
/// SwiferSwift: Dequeue reusable UITableViewHeaderFooterView using class name
///
/// - Parameter name: UITableViewHeaderFooterView type
/// - Returns: UITableViewHeaderFooterView object with associated class name (optional value)
public func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(withClass name: T.Type) -> T? {
return dequeueReusableHeaderFooterView(withIdentifier: String(describing: name)) as? T
}
/// SwifterSwift: Register UITableViewHeaderFooterView using class name
///
/// - Parameters:
/// - nib: Nib file used to create the header or footer view.
/// - name: UITableViewHeaderFooterView type.
public func register<T: UITableViewHeaderFooterView>(nib: UINib?, withHeaderFooterViewClass name: T.Type) {
register(nib, forHeaderFooterViewReuseIdentifier: String(describing: name))
}
/// SwifterSwift: Register UITableViewHeaderFooterView using class name
///
/// - Parameter name: UITableViewHeaderFooterView type
public func register<T: UITableViewHeaderFooterView>(headerFooterViewClassWith name: T.Type) {
register(T.self, forHeaderFooterViewReuseIdentifier: String(describing: name))
}
/// SwifterSwift: Register UITableViewCell using class name
///
/// - Parameter name: UITableViewCell type
public func register<T: UITableViewCell>(cellWithClass name: T.Type) {
register(T.self, forCellReuseIdentifier: String(describing: name))
}
/// SwifterSwift: Register UITableViewCell using class name
///
/// - Parameters:
/// - nib: Nib file used to create the tableView cell.
/// - name: UITableViewCell type.
public func register<T: UITableViewCell>(nib: UINib?, withCellClass name: T.Type) {
register(nib, forCellReuseIdentifier: String(describing: name))
}
}
#endif
| mit |
omaralbeik/SwifterSwift | Tests/UIKitTests/UIViewControllerExtensionsTests.swift | 1 | 8159 | //
// UIViewControllerExtensionsTests.swift
// SwifterSwift
//
// Created by Steven on 2/25/17.
// Copyright © 2017 SwifterSwift
//
import XCTest
@testable import SwifterSwift
#if canImport(UIKit) && !os(watchOS)
import UIKit
final class UIViewControllerExtensionsTests: XCTestCase {
class MockNotificationViewController: UIViewController {
var notificationFired = false
@objc func testSelector() {
notificationFired = true
}
}
let notificationIdentifier = Notification.Name("MockNotification")
func testAddNotificationObserver() {
let viewController = MockNotificationViewController()
let selector = #selector(MockNotificationViewController.testSelector)
viewController.addNotificationObserver(name: notificationIdentifier, selector: selector)
NotificationCenter.default.post(name: notificationIdentifier, object: nil)
XCTAssert(viewController.notificationFired)
}
func testIsVisible() {
let viewController = UIViewController()
XCTAssertFalse(viewController.isVisible)
}
func testRemoveNotificationObserver() {
let viewController = MockNotificationViewController()
let selector = #selector(MockNotificationViewController.testSelector)
viewController.addNotificationObserver(name: notificationIdentifier, selector: selector)
viewController.removeNotificationObserver(name: notificationIdentifier)
NotificationCenter.default.post(name: notificationIdentifier, object: nil)
XCTAssertFalse(viewController.notificationFired)
}
func testRemoveNotificationsObserver() {
let viewController = MockNotificationViewController()
let selector = #selector(MockNotificationViewController.testSelector)
viewController.addNotificationObserver(name: notificationIdentifier, selector: selector)
viewController.removeNotificationsObserver()
NotificationCenter.default.post(name: notificationIdentifier, object: nil)
XCTAssertFalse(viewController.notificationFired)
}
func testShowAlert() {
let viewController = UIViewController()
UIApplication.shared.keyWindow?.rootViewController = viewController
let title = "test title"
let message = "test message"
let actionButtons = ["OK", "Cancel"]
let preferredButtonIndex = 1
let alertController = viewController.showAlert(
title: title,
message: message,
buttonTitles: actionButtons,
highlightedButtonIndex: preferredButtonIndex,
completion: nil)
XCTAssertEqual(alertController.preferredStyle, .alert)
XCTAssertEqual(alertController.title, title)
XCTAssertEqual(alertController.message, message)
//check whether the buttons are added in the same order
for action in 0..<alertController.actions.count {
XCTAssertEqual(alertController.actions[action].title, actionButtons[action])
}
XCTAssertEqual(alertController.preferredAction, alertController.actions[preferredButtonIndex])
}
func testAddChildViewController() {
let parentViewController = UIViewController()
let childViewController = UIViewController()
XCTAssert(parentViewController.children.isEmpty)
XCTAssertNil(childViewController.parent)
parentViewController.addChildViewController(childViewController, toContainerView: parentViewController.view)
XCTAssertEqual(parentViewController.children, [childViewController])
XCTAssertNotNil(childViewController.parent)
XCTAssertEqual(childViewController.parent, parentViewController)
}
func testRemoveChildViewController() {
let parentViewController = UIViewController()
let childViewController = UIViewController()
parentViewController.addChild(childViewController)
parentViewController.view.addSubview(childViewController.view)
childViewController.didMove(toParent: parentViewController)
XCTAssertEqual(parentViewController.children, [childViewController])
XCTAssertNotNil(childViewController.parent)
XCTAssertEqual(childViewController.parent, parentViewController)
childViewController.removeViewAndControllerFromParentViewController()
XCTAssert(parentViewController.children.isEmpty)
XCTAssertNil(childViewController.parent)
}
func testRemoveChildViewControllerWithNoParent() {
let childViewController = UIViewController()
XCTAssertNil(childViewController.parent)
childViewController.removeViewAndControllerFromParentViewController()
XCTAssertNil(childViewController.parent)
}
#if os(iOS)
func testPresentPopover() {
let popover = UIViewController()
let presentingViewController = UIViewController()
// Putting the view controller in a window and running a RunLoop seems to be the only way to make
// the presentedViewController and presentingViewController properties to be set.
let window = UIWindow()
window.rootViewController = presentingViewController
window.addSubview(presentingViewController.view)
RunLoop.current.run(until: Date())
presentingViewController.presentPopover(popover, sourcePoint: presentingViewController.view.center, animated: false)
XCTAssertEqual(presentingViewController.presentedViewController, popover)
XCTAssertEqual(popover.presentingViewController, presentingViewController)
XCTAssertEqual(popover.modalPresentationStyle, .popover)
}
func testPresentPopoverWithCustomSize() {
let popover = UIViewController()
let presentingViewController = UIViewController()
let customSize = CGSize(width: 100, height: 100)
// Putting the view controller in a window and running a RunLoop seems to be the only way to make
// the presentedViewController and presentingViewController properties to be set.
let window = UIWindow()
window.rootViewController = presentingViewController
window.addSubview(presentingViewController.view)
RunLoop.current.run(until: Date())
presentingViewController.presentPopover(popover, sourcePoint: presentingViewController.view.center, size: customSize)
XCTAssertEqual(presentingViewController.presentedViewController, popover)
XCTAssertEqual(popover.presentingViewController, presentingViewController)
XCTAssertEqual(popover.modalPresentationStyle, .popover)
XCTAssertEqual(popover.preferredContentSize, customSize)
}
func testPresentPopoverWithDelegate() {
// swiftlint:disable:next nesting
class PopoverDelegate: NSObject, UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .popover
}
}
let popover = UIViewController()
let presentingViewController = UIViewController()
let delegate = PopoverDelegate()
// Putting the view controller in a window and running a RunLoop seems to be the only way to make
// the presentedViewController and presentingViewController properties to be set.
let window = UIWindow()
window.rootViewController = presentingViewController
window.addSubview(presentingViewController.view)
RunLoop.current.run(until: Date(timeIntervalSinceNow: 5))
presentingViewController.presentPopover(popover, sourcePoint: presentingViewController.view.center, delegate: delegate)
XCTAssertEqual(presentingViewController.presentedViewController, popover)
XCTAssertEqual(popover.presentingViewController, presentingViewController)
XCTAssertEqual(popover.modalPresentationStyle, .popover)
let popoverDelegate = popover.popoverPresentationController?.delegate as? PopoverDelegate
XCTAssertNotNil(popoverDelegate)
XCTAssertEqual(popoverDelegate, delegate)
}
#endif
}
#endif
| mit |
seivan/SpriteKitComposition | TestsAndSample/Sample/Components/RepeatAnimating.swift | 1 | 659 | //
// RepeatAnimating.swift
// TestsAndSample
//
// Created by Seivan Heidari on 18/12/14.
// Copyright (c) 2014 Seivan Heidari. All rights reserved.
//
import Foundation
import SpriteKit
class RepeatAnimating: Component {
let animation:SKAction
let key:NSUUID = NSUUID()
init(textures:[SKTexture], timePerFrame:NSTimeInterval) {
let anim = SKAction.animateWithTextures(textures, timePerFrame: 0.2)
self.animation = SKAction.repeatActionForever(anim)
}
func didAddToNode(node:SKNode) {
self.node?.removeActionForKey(self.key.UUIDString)
self.node?.runAction(self.animation, withKey: self.key.UUIDString)
}
}
| mit |
kitasuke/CommandlineTool | GithubCLITests/GithubCLITests.swift | 2 | 908 | //
// GithubCLITests.swift
// GithubCLITests
//
// Created by Yusuke Kita on 7/19/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import Cocoa
import XCTest
class GithubCLITestsTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/15795-swift-sourcemanager-getmessage.swift | 11 | 237 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case
let
start = a( {
let c = {
class B {
struct S
{
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/19061-swift-parser-skipsingle.swift | 11 | 361 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum e {
enum S
{
}
enum S<T where g: T> : N
{
var f = {
class A {
{
{
( (
{
( [
{
{
{
{
{
( [
{
{
{
{
{
{
{
( [ {
( ( [
{
( [
( {
{
{
{
{
{
{
{
( (
{
{
{
{
{
{
{
( {
{
{
{
{
{
{
{
{
{
{
{
c,
| mit |
ipagong/PGTabBar-Swift | PGTabBar/Classes/TabItemProtocol.swift | 1 | 2110 | //
// TabItemProtocol.swift
// Pods
//
// Created by ipagong on 2017. 4. 28..
//
//
import Foundation
//-------------------------------------//
// MARK: - TabItemProtocol
//-------------------------------------//
public protocol TabItemProtocol {
var tabItemKey:String! { get set }
var tabCellType:TabCellType! { get set }
var tabIdentifier:String { get }
var tabSelected:Bool { get set }
var itemMinimumWidth:CGFloat { get }
var padding:UIEdgeInsets { get }
var expectedWidth:CGFloat { get }
}
extension TabItemProtocol {
public func isValidTabCell() -> Bool {
guard let _ = tabCellType.preloadForValidation() as? TabCellProtocol else { return false }
return true
}
public var tabIdentifier:String {
switch self.tabCellType! {
case .clazz(let type): return NSStringFromClass(type) as String
case .nib(let nibName): return nibName
}
}
public var itemMinimumWidth:CGFloat { return 80 }
public var padding:UIEdgeInsets { return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) }
public var expectedWidth:CGFloat { return padding.left + itemMinimumWidth + padding.right }
}
public enum TabCellType {
case clazz(type: UICollectionViewCell.Type)
case nib(nibName: String)
func preloadForValidation() -> Any? {
switch self {
case .clazz(let type):
return type.init()
case .nib(let nibName):
guard nibName.isEmpty == false else { return nil }
return UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil).first
}
}
func registTabCell(_ collectionView:UICollectionView, tabIdentifier:String) {
switch self {
case .clazz(let type):
collectionView.register(type, forCellWithReuseIdentifier: tabIdentifier)
case .nib(let nibName):
collectionView.register(UINib(nibName: nibName, bundle: nil), forCellWithReuseIdentifier: tabIdentifier)
}
}
}
| mit |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Views/Chat/New Chat/ChatItems/QuoteChatItem.swift | 1 | 1379 | //
// QuoteChatItem.swift
// Rocket.Chat
//
// Created by Filipe Alvarenga on 03/10/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
import DifferenceKit
import RocketChatViewController
import RealmSwift
final class QuoteChatItem: BaseTextAttachmentChatItem, ChatItem, Differentiable {
var relatedReuseIdentifier: String {
return hasText ? QuoteCell.identifier : QuoteMessageCell.identifier
}
let identifier: String
let purpose: String
let title: String
let text: String?
let hasText: Bool
init(identifier: String,
purpose: String,
title: String,
text: String?,
collapsed: Bool,
hasText: Bool,
user: UnmanagedUser?,
message: UnmanagedMessage?) {
self.identifier = identifier
self.purpose = purpose
self.title = title
self.text = text
self.hasText = hasText
super.init(
collapsed: collapsed,
user: user,
message: message
)
}
var differenceIdentifier: String {
return identifier
}
func isContentEqual(to source: QuoteChatItem) -> Bool {
return title == source.title &&
text == source.text &&
collapsed == source.collapsed &&
purpose.isEmpty == source.purpose.isEmpty
}
}
| mit |
brave/browser-ios | ThirdParty/SQLiteSwift/Tests/SQLiteTests/RowTests.swift | 4 | 2890 | import XCTest
@testable import SQLite
class RowTests : XCTestCase {
public func test_get_value() {
let row = Row(["\"foo\"": 0], ["value"])
let result = try! row.get(Expression<String>("foo"))
XCTAssertEqual("value", result)
}
public func test_get_value_subscript() {
let row = Row(["\"foo\"": 0], ["value"])
let result = row[Expression<String>("foo")]
XCTAssertEqual("value", result)
}
public func test_get_value_optional() {
let row = Row(["\"foo\"": 0], ["value"])
let result = try! row.get(Expression<String?>("foo"))
XCTAssertEqual("value", result)
}
public func test_get_value_optional_subscript() {
let row = Row(["\"foo\"": 0], ["value"])
let result = row[Expression<String?>("foo")]
XCTAssertEqual("value", result)
}
public func test_get_value_optional_nil() {
let row = Row(["\"foo\"": 0], [nil])
let result = try! row.get(Expression<String?>("foo"))
XCTAssertNil(result)
}
public func test_get_value_optional_nil_subscript() {
let row = Row(["\"foo\"": 0], [nil])
let result = row[Expression<String?>("foo")]
XCTAssertNil(result)
}
public func test_get_type_mismatch_throws_unexpected_null_value() {
let row = Row(["\"foo\"": 0], ["value"])
XCTAssertThrowsError(try row.get(Expression<Int>("foo"))) { error in
if case QueryError.unexpectedNullValue(let name) = error {
XCTAssertEqual("\"foo\"", name)
} else {
XCTFail("unexpected error: \(error)")
}
}
}
public func test_get_type_mismatch_optional_returns_nil() {
let row = Row(["\"foo\"": 0], ["value"])
let result = try! row.get(Expression<Int?>("foo"))
XCTAssertNil(result)
}
public func test_get_non_existent_column_throws_no_such_column() {
let row = Row(["\"foo\"": 0], ["value"])
XCTAssertThrowsError(try row.get(Expression<Int>("bar"))) { error in
if case QueryError.noSuchColumn(let name, let columns) = error {
XCTAssertEqual("\"bar\"", name)
XCTAssertEqual(["\"foo\""], columns)
} else {
XCTFail("unexpected error: \(error)")
}
}
}
public func test_get_ambiguous_column_throws() {
let row = Row(["table1.\"foo\"": 0, "table2.\"foo\"": 1], ["value"])
XCTAssertThrowsError(try row.get(Expression<Int>("foo"))) { error in
if case QueryError.ambiguousColumn(let name, let columns) = error {
XCTAssertEqual("\"foo\"", name)
XCTAssertEqual(["table1.\"foo\"", "table2.\"foo\""], columns.sorted())
} else {
XCTFail("unexpected error: \(error)")
}
}
}
}
| mpl-2.0 |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Backend/IMGLYFontImporter.swift | 1 | 1459 | //
// IMGLYFontImporter.swift
// imglyKit
//
// Created by Carsten Przyluczky on 09/03/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import Foundation
import CoreGraphics
import CoreText
/**
Provides functions to import font added as resource. It also registers them,
so that the application can load them like any other pre-installed font.
*/
public class IMGLYFontImporter {
private static var fontsRegistered = false
/**
Imports all fonts added as resource. Supported formats are TTF and OTF.
*/
public func importFonts() {
if !IMGLYFontImporter.fontsRegistered {
importFontsWithExtension("ttf")
importFontsWithExtension("otf")
IMGLYFontImporter.fontsRegistered = true
}
}
private func importFontsWithExtension(ext: String) {
let paths = NSBundle(forClass: self.dynamicType).pathsForResourcesOfType(ext, inDirectory: nil)
for fontPath in paths as! [String] {
let data: NSData? = NSFileManager.defaultManager().contentsAtPath(fontPath)
var error: Unmanaged<CFError>?
var provider = CGDataProviderCreateWithCFData(data as! CFDataRef)
var font = CGFontCreateWithDataProvider(provider)
if (!CTFontManagerRegisterGraphicsFont(font, &error)) {
println("Failed to register font, error: \(error)")
return
}
}
}
} | apache-2.0 |
wqhiOS/WeiBo | WeiBo/WeiBo/Classes/Controller/Home/HomePopoverViewController/HomePresentationController.swift | 1 | 1293 | //
// HomePresentationController.swift
// WeiBo
//
// Created by wuqh on 2017/6/13.
// Copyright © 2017年 吴启晗. All rights reserved.
//
import UIKit
class HomePresentationController: UIPresentationController {
var presentedFrame: CGRect = CGRect.zero
fileprivate lazy var coverView: UIView = UIView()
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
// 设置弹出view 的尺寸
presentedView?.frame = presentedFrame
// 添加蒙版
setupCoverView()
}
}
// MARK: - UI
extension HomePresentationController {
fileprivate func setupCoverView() {
containerView?.insertSubview(coverView, belowSubview: presentedView!)
coverView.backgroundColor = UIColor.black
coverView.alpha = 0.4
coverView.frame = containerView?.bounds ?? CGRect.zero
coverView.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(coverViewClick))
coverView.addGestureRecognizer(tapGes)
}
}
// MARK: - Action
extension HomePresentationController {
@objc fileprivate func coverViewClick() {
presentedViewController.dismiss(animated: true, completion: nil)
}
}
| mit |
tuffz/pi-weather-app | Pi-WeatherWatch Extension/ExtensionDelegate.swift | 2 | 2584 | //
// ExtensionDelegate.swift
// Pi-WeatherWatch Extension
//
// Created by Hendrik on 09/10/2016.
// Copyright © 2016 JG-Bits UG (haftungsbeschränkt). All rights reserved.
//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
print(#function)
}
func applicationDidBecomeActive() {
// 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.
print(#function)
}
func applicationWillResignActive() {
// 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, etc.
print(#function)
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks.
//Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
backgroundTask.setTaskCompleted()
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// Be sure to complete the connectivity task once you’re done.
connectivityTask.setTaskCompleted()
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
urlSessionTask.setTaskCompleted()
default:
// make sure to complete unhandled task types
task.setTaskCompleted()
}
}
}
}
| mit |
everald/JetPack | Sources/Measures/UnitSystem.swift | 2 | 248 | public enum UnitSystem {
case american
case british
case si
public func select<T>(si: T, american: T, british: T) -> T {
switch self {
case .american: return american
case .british: return british
case .si: return si
}
}
}
| mit |
strava/thrift | lib/swift/Sources/Thrift.swift | 2 | 41 | class Thrift {
let version = "0.16.0"
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.