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
NoryCao/zhuishushenqi
zhuishushenqi/Base/Views/DarkStarView.swift
1
803
// // DarkStarView.swift // zhuishushenqi // // Created by Nory Cao on 2017/3/9. // Copyright © 2017年 QS. All rights reserved. // import UIKit class DarkStarView: UIImageView { // override init(frame: CGRect) { // super.init(frame: frame) // self.image = UIImage(named: "bd_star_empty") //// bd_star_empty // } init(frame: CGRect,image:UIImage?) { super.init(frame: frame) self.image = image } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/09710-swift-sourcemanager-getmessage.swift
11
251
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension NSSet { let a { for in ( { enum A { { } func g { class A { class case ,
mit
audiokit/AudioKit
Sources/AudioKit/Operations/Operation.swift
2
7620
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ /// A computed parameter differs from a regular parameter in that it only exists within an operation /// (unlike float, doubles, and ints which have a value outside of an operation) public protocol ComputedParameter: OperationParameter {} /// An Operation is a computed parameter that can be passed to other operations in the same operation node open class Operation: ComputedParameter { // MARK: - Dependency Management fileprivate var inputs = [OperationParameter]() internal var savedLocation = -1 fileprivate var dependencies = [Operation]() internal var recursiveDependencies: [Operation] { var all = [Operation]() var uniq = [Operation]() var added = Set<String>() for dep in dependencies { all += dep.recursiveDependencies all.append(dep) } for elem in all { if !added.contains(elem.inlineSporth) { uniq.append(elem) added.insert(elem.inlineSporth) } } return uniq } // MARK: - String Representations fileprivate var valueText = "" internal var setupSporth = "" fileprivate var module = "" internal var inlineSporth: String { if valueText != "" { return valueText } var opString = "" for input in inputs { if type(of: input) == Operation.self { if let operation = input as? Operation { if operation.savedLocation >= 0 { opString += "\(operation.savedLocation) \"ak\" tget " } else { opString += operation.inlineSporth } } } else { opString += "\(input) " } } opString += "\(module) " return opString } func getSetup() -> String { return setupSporth == "" ? "" : setupSporth + " " } /// Final sporth string when this operation is the last operation in the stack internal var sporth: String { let rd = recursiveDependencies var str = "" if rd.isNotEmpty { str = #""ak" ""# str += rd.compactMap { _ in "0" }.joined(separator: " ") str += #"" gen_vals "# var counter = 0 for op in rd { op.savedLocation = counter str += op.getSetup() str += op.inlineSporth + "\(op.savedLocation) \"ak\" tset " counter += 1 } } str += getSetup() str += inlineSporth return str } /// Redefining description to return the operation string open var description: String { return inlineSporth } // MARK: - Inputs /// Left input to any stereo operation public static var leftInput = Operation("(14 p) ") /// Right input to any stereo operation public static var rightInput = Operation("(15 p) ") /// Dummy trigger public static var trigger = Operation("(14 p) ") // MARK: - Functions /// An= array of 14 parameters which may be sent to operations public static var parameters: [Operation] = [Operation("(0 p) "), Operation("(1 p) "), Operation("(2 p) "), Operation("(3 p) "), Operation("(4 p) "), Operation("(5 p) "), Operation("(6 p) "), Operation("(7 p) "), Operation("(8 p) "), Operation("(9 p) "), Operation("(10 p) "), Operation("(11 p) "), Operation("(12 p) "), Operation("(13 p) ")] /// Convert the operation to a mono operation public func toMono() -> Operation { return self } /// Performs absolute value on the operation public func abs() -> Operation { return Operation(module: "abs", inputs: self) } /// Performs floor calculation on the operation public func floor() -> Operation { return Operation(module: "floor", inputs: self) } /// Returns the fractional part of the operation (as opposed to the integer part) public func fract() -> Operation { return Operation(module: "frac", inputs: self) } /// Performs natural logarithm on the operation public func log() -> Operation { return Operation(module: "log", inputs: self) } /// Performs Base 10 logarithm on the operation public func log10() -> Operation { return Operation(module: "log10", inputs: self) } /// Rounds the operation to the nearest integer public func round() -> Operation { return Operation(module: "round", inputs: self) } /// Returns a frequency for a given MIDI note number public func midiNoteToFrequency() -> Operation { return Operation(module: "mtof", inputs: self) } // MARK: - Initialization /// Initialize the operation as a constant value /// /// - parameter value: Constant value as an operation /// public init(_ value: Double) { self.valueText = "\(value)" } init(global: String) { self.valueText = global } /// Initialize the operation with a Sporth string /// /// - parameter operationString: Valid Sporth string (proceed with caution /// public init(_ operationString: String) { self.valueText = operationString //self.tableIndex = -1 //Operation.nextTableIndex //Operation.nextTableIndex += 1 //Operation.operationArray.append(self) } /// Initialize the operation /// /// - parameter module: Sporth unit generator /// - parameter setup: Any setup Sporth code that this operation may require /// - parameter inputs: All the parameters of the operation /// public init(module: String, setup: String = "", inputs: OperationParameter...) { self.module = module self.setupSporth = setup self.inputs = inputs for input in inputs { if type(of: input) == Operation.self { if let forcedInput = input as? Operation { dependencies.append(forcedInput) } } } } } // MARK: - Global Functions /// Performs absolute value on the operation /// /// - parameter parameter: ComputedParameter to operate on /// public func abs(_ parameter: Operation) -> Operation { return parameter.abs() } /// Performs floor calculation on the operation /// /// - parameter operation: ComputedParameter to operate on /// public func floor(_ operation: Operation) -> Operation { return operation.floor() } /// Returns the fractional part of the operation (as opposed to the integer part) /// /// - parameter operation: ComputedParameter to operate on /// public func fract(_ operation: Operation) -> Operation { return operation.fract() } /// Performs natural logarithm on the operation /// /// - parameter operation: ComputedParameter to operate on /// public func log(_ operation: Operation) -> Operation { return operation.log() } /// Performs Base 10 logarithm on the operation /// /// - parmeter operation: ComputedParameter to operate on /// public func log10(_ operation: Operation) -> Operation { return operation.log10() } /// Rounds the operation to the nearest integer /// /// - parameter operation: ComputedParameter to operate on /// public func round(_ operation: Operation) -> Operation { return operation.round() }
mit
akane/Gaikan
Gaikan/Helpers/Optional+Helpers.swift
1
409
// // This file is part of Gaikan // // Created by JC on 24/06/16. // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code // import Foundation protocol OptionalProtocol { associatedtype WrappedType var value: WrappedType? { get } } extension Optional: OptionalProtocol { var value: Wrapped? { return self } }
mit
scotlandyard/expocity
expocity/Model/Chat/Menu/Status/MChatMenuStatusStandby.swift
1
369
import Foundation class MChatMenuStatusStandby:MChatMenuStatus { init() { let itemPicture:MChatMenuItemPicture = MChatMenuItemPicture() let itemEmoji:MChatMenuItemEmoji = MChatMenuItemEmoji() let items:[MChatMenuItem] = [ itemEmoji, itemPicture ] super.init(items:items) } }
mit
qvacua/vimr
NvimView/Support/MinimalNvimViewDemo/Document.swift
1
2116
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import NvimView import PureLayout import RxSwift class Document: NSDocument, NSWindowDelegate { private var nvimView = NvimView(forAutoLayout: ()) private let disposeBag = DisposeBag() override init() { super.init() self.nvimView.font = NSFont(name: "Fira Code", size: 13) ?? NSFont.userFixedPitchFont(ofSize: 13)! self.nvimView.usesLigatures = true self.nvimView.drawsParallel = true self.nvimView .events .observe(on: MainScheduler.instance) .subscribe(onNext: { event in switch event { case .neoVimStopped: self.close() default: break } }) .disposed(by: self.disposeBag) } func quitWithoutSaving() { try? self.nvimView.quitNeoVimWithoutSaving().wait() self.nvimView.waitTillNvimExits() } func windowShouldClose(_: NSWindow) -> Bool { self.quitWithoutSaving() return false } override func windowControllerDidLoadNib(_ windowController: NSWindowController) { super.windowControllerDidLoadNib(windowController) let window = windowController.window! window.delegate = self let view = window.contentView! let nvimView = self.nvimView // We know that we use custom tabs. let tabBar = nvimView.tabBar! view.addSubview(tabBar) view.addSubview(nvimView) tabBar.autoPinEdge(toSuperviewEdge: .left) tabBar.autoPinEdge(toSuperviewEdge: .top) tabBar.autoPinEdge(toSuperviewEdge: .right) nvimView.autoPinEdge(.top, to: .bottom, of: tabBar) nvimView.autoPinEdge(toSuperviewEdge: .left) nvimView.autoPinEdge(toSuperviewEdge: .right) nvimView.autoPinEdge(toSuperviewEdge: .bottom) } override var windowNibName: NSNib.Name? { NSNib.Name("Document") } override func data(ofType _: String) throws -> Data { throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) } override func read(from _: Data, ofType _: String) throws { throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) } }
mit
apple/swift
validation-test/compiler_crashers_fixed/24798-no-stacktrace.swift
65
21407
// 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 // RUN: %target-swift-frontend %s -typecheck // Issue found by https://github.com/neilpa (neilpa) // http://www.openradar.me/20220559 // ASAN Output: stack-overflow on address 0x7ffc82319f20 (pc 0x000001e54411 bp 0x7ffc8231a050 sp 0x7ffc82319ee0 T0) let records = [ 0x0000: "", 0x0001: "", 0x0002: "", 0x0003: "", 0x0004: "", 0x0005: "", 0x0006: "", 0x0007: "", 0x0008: "", 0x0009: "", 0x000A: "", 0x000B: "", 0x000C: "", 0x000D: "", 0x000E: "", 0x000F: "", 0x0010: "", 0x0011: "", 0x0012: "", 0x0013: "", 0x0014: "", 0x0015: "", 0x0016: "", 0x0017: "", 0x0018: "", 0x0019: "", 0x001A: "", 0x001B: "", 0x001C: "", 0x001D: "", 0x001E: "", 0x001F: "", 0x0020: "", 0x0021: "", 0x0022: "", 0x0023: "", 0x0024: "", 0x0025: "", 0x0026: "", 0x0027: "", 0x0028: "", 0x0029: "", 0x002A: "", 0x002B: "", 0x002C: "", 0x002D: "", 0x002E: "", 0x002F: "", 0x0030: "", 0x0031: "", 0x0032: "", 0x0033: "", 0x0034: "", 0x0035: "", 0x0036: "", 0x0037: "", 0x0038: "", 0x0039: "", 0x003A: "", 0x003B: "", 0x003C: "", 0x003D: "", 0x003E: "", 0x003F: "", 0x0040: "", 0x0041: "", 0x0042: "", 0x0043: "", 0x0044: "", 0x0045: "", 0x0046: "", 0x0047: "", 0x0048: "", 0x0049: "", 0x004A: "", 0x004B: "", 0x004C: "", 0x004D: "", 0x004E: "", 0x004F: "", 0x0050: "", 0x0051: "", 0x0052: "", 0x0053: "", 0x0054: "", 0x0055: "", 0x0056: "", 0x0057: "", 0x0058: "", 0x0059: "", 0x005A: "", 0x005B: "", 0x005C: "", 0x005D: "", 0x005E: "", 0x005F: "", 0x0060: "", 0x0061: "", 0x0062: "", 0x0063: "", 0x0064: "", 0x0065: "", 0x0066: "", 0x0067: "", 0x0068: "", 0x0069: "", 0x006A: "", 0x006B: "", 0x006C: "", 0x006D: "", 0x006E: "", 0x006F: "", 0x0070: "", 0x0071: "", 0x0072: "", 0x0073: "", 0x0074: "", 0x0075: "", 0x0076: "", 0x0077: "", 0x0078: "", 0x0079: "", 0x007A: "", 0x007B: "", 0x007C: "", 0x007D: "", 0x007E: "", 0x007F: "", 0x0080: "", 0x0081: "", 0x0082: "", 0x0083: "", 0x0084: "", 0x0085: "", 0x0086: "", 0x0087: "", 0x0088: "", 0x0089: "", 0x008A: "", 0x008B: "", 0x008C: "", 0x008D: "", 0x008E: "", 0x008F: "", 0x0090: "", 0x0091: "", 0x0092: "", 0x0093: "", 0x0094: "", 0x0095: "", 0x0096: "", 0x0097: "", 0x0098: "", 0x0099: "", 0x009A: "", 0x009B: "", 0x009C: "", 0x009D: "", 0x009E: "", 0x009F: "", 0x00A0: "", 0x00A1: "", 0x00A2: "", 0x00A3: "", 0x00A4: "", 0x00A5: "", 0x00A6: "", 0x00A7: "", 0x00A8: "", 0x00A9: "", 0x00AA: "", 0x00AB: "", 0x00AC: "", 0x00AD: "", 0x00AE: "", 0x00AF: "", 0x00B0: "", 0x00B1: "", 0x00B2: "", 0x00B3: "", 0x00B4: "", 0x00B5: "", 0x00B6: "", 0x00B7: "", 0x00B8: "", 0x00B9: "", 0x00BA: "", 0x00BB: "", 0x00BC: "", 0x00BD: "", 0x00BE: "", 0x00BF: "", 0x00C0: "", 0x00C1: "", 0x00C2: "", 0x00C3: "", 0x00C4: "", 0x00C5: "", 0x00C6: "", 0x00C7: "", 0x00C8: "", 0x00C9: "", 0x00CA: "", 0x00CB: "", 0x00CC: "", 0x00CD: "", 0x00CE: "", 0x00CF: "", 0x00D0: "", 0x00D1: "", 0x00D2: "", 0x00D3: "", 0x00D4: "", 0x00D5: "", 0x00D6: "", 0x00D7: "", 0x00D8: "", 0x00D9: "", 0x00DA: "", 0x00DB: "", 0x00DC: "", 0x00DD: "", 0x00DE: "", 0x00DF: "", 0x00E0: "", 0x00E1: "", 0x00E2: "", 0x00E3: "", 0x00E4: "", 0x00E5: "", 0x00E6: "", 0x00E7: "", 0x00E8: "", 0x00E9: "", 0x00EA: "", 0x00EB: "", 0x00EC: "", 0x00ED: "", 0x00EE: "", 0x00EF: "", 0x00F0: "", 0x00F1: "", 0x00F2: "", 0x00F3: "", 0x00F4: "", 0x00F5: "", 0x00F6: "", 0x00F7: "", 0x00F8: "", 0x00F9: "", 0x00FA: "", 0x00FB: "", 0x00FC: "", 0x00FD: "", 0x00FE: "", 0x00FF: "", 0x0100: "", 0x0101: "", 0x0102: "", 0x0103: "", 0x0104: "", 0x0105: "", 0x0106: "", 0x0107: "", 0x0108: "", 0x0109: "", 0x010A: "", 0x010B: "", 0x010C: "", 0x010D: "", 0x010E: "", 0x010F: "", 0x0110: "", 0x0111: "", 0x0112: "", 0x0113: "", 0x0114: "", 0x0115: "", 0x0116: "", 0x0117: "", 0x0118: "", 0x0119: "", 0x011A: "", 0x011B: "", 0x011C: "", 0x011D: "", 0x011E: "", 0x011F: "", 0x0120: "", 0x0121: "", 0x0122: "", 0x0123: "", 0x0124: "", 0x0125: "", 0x0126: "", 0x0127: "", 0x0128: "", 0x0129: "", 0x012A: "", 0x012B: "", 0x012C: "", 0x012D: "", 0x012E: "", 0x012F: "", 0x0130: "", 0x0131: "", 0x0132: "", 0x0133: "", 0x0134: "", 0x0135: "", 0x0136: "", 0x0137: "", 0x0138: "", 0x0139: "", 0x013A: "", 0x013B: "", 0x013C: "", 0x013D: "", 0x013E: "", 0x013F: "", 0x0140: "", 0x0141: "", 0x0142: "", 0x0143: "", 0x0144: "", 0x0145: "", 0x0146: "", 0x0147: "", 0x0148: "", 0x0149: "", 0x014A: "", 0x014B: "", 0x014C: "", 0x014D: "", 0x014E: "", 0x014F: "", 0x0150: "", 0x0151: "", 0x0152: "", 0x0153: "", 0x0154: "", 0x0155: "", 0x0156: "", 0x0157: "", 0x0158: "", 0x0159: "", 0x015A: "", 0x015B: "", 0x015C: "", 0x015D: "", 0x015E: "", 0x015F: "", 0x0160: "", 0x0161: "", 0x0162: "", 0x0163: "", 0x0164: "", 0x0165: "", 0x0166: "", 0x0167: "", 0x0168: "", 0x0169: "", 0x016A: "", 0x016B: "", 0x016C: "", 0x016D: "", 0x016E: "", 0x016F: "", 0x0170: "", 0x0171: "", 0x0172: "", 0x0173: "", 0x0174: "", 0x0175: "", 0x0176: "", 0x0177: "", 0x0178: "", 0x0179: "", 0x017A: "", 0x017B: "", 0x017C: "", 0x017D: "", 0x017E: "", 0x017F: "", 0x0180: "", 0x0181: "", 0x0182: "", 0x0183: "", 0x0184: "", 0x0185: "", 0x0186: "", 0x0187: "", 0x0188: "", 0x0189: "", 0x018A: "", 0x018B: "", 0x018C: "", 0x018D: "", 0x018E: "", 0x018F: "", 0x0190: "", 0x0191: "", 0x0192: "", 0x0193: "", 0x0194: "", 0x0195: "", 0x0196: "", 0x0197: "", 0x0198: "", 0x0199: "", 0x019A: "", 0x019B: "", 0x019C: "", 0x019D: "", 0x019E: "", 0x019F: "", 0x01A0: "", 0x01A1: "", 0x01A2: "", 0x01A3: "", 0x01A4: "", 0x01A5: "", 0x01A6: "", 0x01A7: "", 0x01A8: "", 0x01A9: "", 0x01AA: "", 0x01AB: "", 0x01AC: "", 0x01AD: "", 0x01AE: "", 0x01AF: "", 0x01B0: "", 0x01B1: "", 0x01B2: "", 0x01B3: "", 0x01B4: "", 0x01B5: "", 0x01B6: "", 0x01B7: "", 0x01B8: "", 0x01B9: "", 0x01BA: "", 0x01BB: "", 0x01BC: "", 0x01BD: "", 0x01BE: "", 0x01BF: "", 0x01C0: "", 0x01C1: "", 0x01C2: "", 0x01C3: "", 0x01C4: "", 0x01C5: "", 0x01C6: "", 0x01C7: "", 0x01C8: "", 0x01C9: "", 0x01CA: "", 0x01CB: "", 0x01CC: "", 0x01CD: "", 0x01CE: "", 0x01CF: "", 0x01D0: "", 0x01D1: "", 0x01D2: "", 0x01D3: "", 0x01D4: "", 0x01D5: "", 0x01D6: "", 0x01D7: "", 0x01D8: "", 0x01D9: "", 0x01DA: "", 0x01DB: "", 0x01DC: "", 0x01DD: "", 0x01DE: "", 0x01DF: "", 0x01E0: "", 0x01E1: "", 0x01E2: "", 0x01E3: "", 0x01E4: "", 0x01E5: "", 0x01E6: "", 0x01E7: "", 0x01E8: "", 0x01E9: "", 0x01EA: "", 0x01EB: "", 0x01EC: "", 0x01ED: "", 0x01EE: "", 0x01EF: "", 0x01F0: "", 0x01F1: "", 0x01F2: "", 0x01F3: "", 0x01F4: "", 0x01F5: "", 0x01F6: "", 0x01F7: "", 0x01F8: "", 0x01F9: "", 0x01FA: "", 0x01FB: "", 0x01FC: "", 0x01FD: "", 0x01FE: "", 0x01FF: "", 0x0200: "", 0x0201: "", 0x0202: "", 0x0203: "", 0x0204: "", 0x0205: "", 0x0206: "", 0x0207: "", 0x0208: "", 0x0209: "", 0x020A: "", 0x020B: "", 0x020C: "", 0x020D: "", 0x020E: "", 0x020F: "", 0x0210: "", 0x0211: "", 0x0212: "", 0x0213: "", 0x0214: "", 0x0215: "", 0x0216: "", 0x0217: "", 0x0218: "", 0x0219: "", 0x021A: "", 0x021B: "", 0x021C: "", 0x021D: "", 0x021E: "", 0x021F: "", 0x0220: "", 0x0221: "", 0x0222: "", 0x0223: "", 0x0224: "", 0x0225: "", 0x0226: "", 0x0227: "", 0x0228: "", 0x0229: "", 0x022A: "", 0x022B: "", 0x022C: "", 0x022D: "", 0x022E: "", 0x022F: "", 0x0230: "", 0x0231: "", 0x0232: "", 0x0233: "", 0x0234: "", 0x0235: "", 0x0236: "", 0x0237: "", 0x0238: "", 0x0239: "", 0x023A: "", 0x023B: "", 0x023C: "", 0x023D: "", 0x023E: "", 0x023F: "", 0x0240: "", 0x0241: "", 0x0242: "", 0x0243: "", 0x0244: "", 0x0245: "", 0x0246: "", 0x0247: "", 0x0248: "", 0x0249: "", 0x024A: "", 0x024B: "", 0x024C: "", 0x024D: "", 0x024E: "", 0x024F: "", 0x0250: "", 0x0251: "", 0x0252: "", 0x0253: "", 0x0254: "", 0x0255: "", 0x0256: "", 0x0257: "", 0x0258: "", 0x0259: "", 0x025A: "", 0x025B: "", 0x025C: "", 0x025D: "", 0x025E: "", 0x025F: "", 0x0260: "", 0x0261: "", 0x0262: "", 0x0263: "", 0x0264: "", 0x0265: "", 0x0266: "", 0x0267: "", 0x0268: "", 0x0269: "", 0x026A: "", 0x026B: "", 0x026C: "", 0x026D: "", 0x026E: "", 0x026F: "", 0x0270: "", 0x0271: "", 0x0272: "", 0x0273: "", 0x0274: "", 0x0275: "", 0x0276: "", 0x0277: "", 0x0278: "", 0x0279: "", 0x027A: "", 0x027B: "", 0x027C: "", 0x027D: "", 0x027E: "", 0x027F: "", 0x0280: "", 0x0281: "", 0x0282: "", 0x0283: "", 0x0284: "", 0x0285: "", 0x0286: "", 0x0287: "", 0x0288: "", 0x0289: "", 0x028A: "", 0x028B: "", 0x028C: "", 0x028D: "", 0x028E: "", 0x028F: "", 0x0290: "", 0x0291: "", 0x0292: "", 0x0293: "", 0x0294: "", 0x0295: "", 0x0296: "", 0x0297: "", 0x0298: "", 0x0299: "", 0x029A: "", 0x029B: "", 0x029C: "", 0x029D: "", 0x029E: "", 0x029F: "", 0x02A0: "", 0x02A1: "", 0x02A2: "", 0x02A3: "", 0x02A4: "", 0x02A5: "", 0x02A6: "", 0x02A7: "", 0x02A8: "", 0x02A9: "", 0x02AA: "", 0x02AB: "", 0x02AC: "", 0x02AD: "", 0x02AE: "", 0x02AF: "", 0x02B0: "", 0x02B1: "", 0x02B2: "", 0x02B3: "", 0x02B4: "", 0x02B5: "", 0x02B6: "", 0x02B7: "", 0x02B8: "", 0x02B9: "", 0x02BA: "", 0x02BB: "", 0x02BC: "", 0x02BD: "", 0x02BE: "", 0x02BF: "", 0x02C0: "", 0x02C1: "", 0x02C2: "", 0x02C3: "", 0x02C4: "", 0x02C5: "", 0x02C6: "", 0x02C7: "", 0x02C8: "", 0x02C9: "", 0x02CA: "", 0x02CB: "", 0x02CC: "", 0x02CD: "", 0x02CE: "", 0x02CF: "", 0x02D0: "", 0x02D1: "", 0x02D2: "", 0x02D3: "", 0x02D4: "", 0x02D5: "", 0x02D6: "", 0x02D7: "", 0x02D8: "", 0x02D9: "", 0x02DA: "", 0x02DB: "", 0x02DC: "", 0x02DD: "", 0x02DE: "", 0x02DF: "", 0x02E0: "", 0x02E1: "", 0x02E2: "", 0x02E3: "", 0x02E4: "", 0x02E5: "", 0x02E6: "", 0x02E7: "", 0x02E8: "", 0x02E9: "", 0x02EA: "", 0x02EB: "", 0x02EC: "", 0x02ED: "", 0x02EE: "", 0x02EF: "", 0x02F0: "", 0x02F1: "", 0x02F2: "", 0x02F3: "", 0x02F4: "", 0x02F5: "", 0x02F6: "", 0x02F7: "", 0x02F8: "", 0x02F9: "", 0x02FA: "", 0x02FB: "", 0x02FC: "", 0x02FD: "", 0x02FE: "", 0x02FF: "", 0x0300: "", 0x0301: "", 0x0302: "", 0x0303: "", 0x0304: "", 0x0305: "", 0x0306: "", 0x0307: "", 0x0308: "", 0x0309: "", 0x030A: "", 0x030B: "", 0x030C: "", 0x030D: "", 0x030E: "", 0x030F: "", 0x0310: "", 0x0311: "", 0x0312: "", 0x0313: "", 0x0314: "", 0x0315: "", 0x0316: "", 0x0317: "", 0x0318: "", 0x0319: "", 0x031A: "", 0x031B: "", 0x031C: "", 0x031D: "", 0x031E: "", 0x031F: "", 0x0320: "", 0x0321: "", 0x0322: "", 0x0323: "", 0x0324: "", 0x0325: "", 0x0326: "", 0x0327: "", 0x0328: "", 0x0329: "", 0x032A: "", 0x032B: "", 0x032C: "", 0x032D: "", 0x032E: "", 0x032F: "", 0x0330: "", 0x0331: "", 0x0332: "", 0x0333: "", 0x0334: "", 0x0335: "", 0x0336: "", 0x0337: "", 0x0338: "", 0x0339: "", 0x033A: "", 0x033B: "", 0x033C: "", 0x033D: "", 0x033E: "", 0x033F: "", 0x0340: "", 0x0341: "", 0x0342: "", 0x0343: "", 0x0344: "", 0x0345: "", 0x0346: "", 0x0347: "", 0x0348: "", 0x0349: "", 0x034A: "", 0x034B: "", 0x034C: "", 0x034D: "", 0x034E: "", 0x034F: "", 0x0350: "", 0x0351: "", 0x0352: "", 0x0353: "", 0x0354: "", 0x0355: "", 0x0356: "", 0x0357: "", 0x0358: "", 0x0359: "", 0x035A: "", 0x035B: "", 0x035C: "", 0x035D: "", 0x035E: "", 0x035F: "", 0x0360: "", 0x0361: "", 0x0362: "", 0x0363: "", 0x0364: "", 0x0365: "", 0x0366: "", 0x0367: "", 0x0368: "", 0x0369: "", 0x036A: "", 0x036B: "", 0x036C: "", 0x036D: "", 0x036E: "", 0x036F: "", 0x0370: "", 0x0371: "", 0x0372: "", 0x0373: "", 0x0374: "", 0x0375: "", 0x0376: "", 0x0377: "", 0x037A: "", 0x037B: "", 0x037C: "", 0x037D: "", 0x037E: "", 0x037F: "", 0x0384: "", 0x0385: "", 0x0386: "", 0x0387: "", 0x0388: "", 0x0389: "", 0x038A: "", 0x038C: "", 0x038E: "", 0x038F: "", 0x0390: "", 0x0391: "", 0x0392: "", 0x0393: "", 0x0394: "", 0x0395: "", 0x0396: "", 0x0397: "", 0x0398: "", 0x0399: "", 0x039A: "", 0x039B: "", 0x039C: "", 0x039D: "", 0x039E: "", 0x039F: "", 0x03A0: "", 0x03A1: "", 0x03A3: "", 0x03A4: "", 0x03A5: "", 0x03A6: "", 0x03A7: "", 0x03A8: "", 0x03A9: "", 0x03AA: "", 0x03AB: "", 0x03AC: "", 0x03AD: "", 0x03AE: "", 0x03AF: "", 0x03B0: "", 0x03B1: "", 0x03B2: "", 0x03B3: "", 0x03B4: "", 0x03B5: "", 0x03B6: "", 0x03B7: "", 0x03B8: "", 0x03B9: "", 0x03BA: "", 0x03BB: "", 0x03BC: "", 0x03BD: "", 0x03BE: "", 0x03BF: "", 0x03C0: "", 0x03C1: "", 0x03C2: "", 0x03C3: "", 0x03C4: "", 0x03C5: "", 0x03C6: "", 0x03C7: "", 0x03C8: "", 0x03C9: "", 0x03CA: "", 0x03CB: "", 0x03CC: "", 0x03CD: "", 0x03CE: "", 0x03CF: "", 0x03D0: "", 0x03D1: "", 0x03D2: "", 0x03D3: "", 0x03D4: "", 0x03D5: "", 0x03D6: "", 0x03D7: "", 0x03D8: "", 0x03D9: "", 0x03DA: "", 0x03DB: "", 0x03DC: "", 0x03DD: "", 0x03DE: "", 0x03DF: "", 0x03E0: "", 0x03E1: "", 0x03E2: "", 0x03E3: "", 0x03E4: "", 0x03E5: "", 0x03E6: "", 0x03E7: "", 0x03E8: "", 0x03E9: "", 0x03EA: "", 0x03EB: "", 0x03EC: "", 0x03ED: "", 0x03EE: "", 0x03EF: "", 0x03F0: "", 0x03F1: "", 0x03F2: "", 0x03F3: "", 0x03F4: "", 0x03F5: "", 0x03F6: "", 0x03F7: "", 0x03F8: "", 0x03F9: "", 0x03FA: "", 0x03FB: "", 0x03FC: "", 0x03FD: "", 0x03FE: "", 0x03FF: "", 0x0400: "", 0x0401: "", 0x0402: "", 0x0403: "", 0x0404: "", 0x0405: "", 0x0406: "", 0x0407: "", 0x0408: "", 0x0409: "", 0x040A: "", 0x040B: "", 0x040C: "", 0x040D: "", 0x040E: "", 0x040F: "", 0x0410: "", 0x0411: "", 0x0412: "", 0x0413: "", 0x0414: "", 0x0415: "", 0x0416: "", 0x0417: "", 0x0418: "", 0x0419: "", 0x041A: "", 0x041B: "", 0x041C: "", 0x041D: "", 0x041E: "", 0x041F: "", 0x0420: "", 0x0421: "", 0x0422: "", 0x0423: "", 0x0424: "", 0x0425: "", 0x0426: "", 0x0427: "", 0x0428: "", 0x0429: "", 0x042A: "", 0x042B: "", 0x042C: "", 0x042D: "", 0x042E: "", 0x042F: "", 0x0430: "", 0x0431: "", 0x0432: "", 0x0433: "", 0x0434: "", 0x0435: "", 0x0436: "", 0x0437: "", 0x0438: "", 0x0439: "", 0x043A: "", 0x043B: "", 0x043C: "", 0x043D: "", 0x043E: "", 0x043F: "", 0x0440: "", 0x0441: "", 0x0442: "", 0x0443: "", 0x0444: "", 0x0445: "", 0x0446: "", 0x0447: "", 0x0448: "", 0x0449: "", 0x044A: "", 0x044B: "", 0x044C: "", 0x044D: "", 0x044E: "", 0x044F: "", 0x0450: "", 0x0451: "", 0x0452: "", 0x0453: "", 0x0454: "", 0x0455: "", 0x0456: "", 0x0457: "", 0x0458: "", 0x0459: "", 0x045A: "", 0x045B: "", 0x045C: "", 0x045D: "", 0x045E: "", 0x045F: "", 0x0460: "", 0x0461: "", 0x0462: "", 0x0463: "", 0x0464: "", 0x0465: "", 0x0466: "", 0x0467: "", 0x0468: "", 0x0469: "", 0x046A: "", 0x046B: "", 0x046C: "", 0x046D: "", 0x046E: "", 0x046F: "", 0x0470: "", 0x0471: "", 0x0472: "", 0x0473: "", 0x0474: "", 0x0475: "", 0x0476: "", 0x0477: "", 0x0478: "", 0x0479: "", 0x047A: "", 0x047B: "", 0x047C: "", 0x047D: "", 0x047E: "", 0x047F: "", 0x0480: "", 0x0481: "", 0x0482: "", 0x0483: "", 0x0484: "", 0x0485: "", 0x0486: "", 0x0487: "", 0x0488: "", 0x0489: "", 0x048A: "", 0x048B: "", 0x048C: "", 0x048D: "", 0x048E: "", 0x048F: "", 0x0490: "", 0x0491: "", 0x0492: "", 0x0493: "", 0x0494: "", 0x0495: "", 0x0496: "", 0x0497: "", 0x0498: "", 0x0499: "", 0x049A: "", 0x049B: "", 0x049C: "", 0x049D: "", 0x049E: "", 0x049F: "", 0x04A0: "", 0x04A1: "", 0x04A2: "", 0x04A3: "", 0x04A4: "", 0x04A5: "", 0x04A6: "", 0x04A7: "", 0x04A8: "", 0x04A9: "", 0x04AA: "", 0x04AB: "", 0x04AC: "", 0x04AD: "", 0x04AE: "", 0x04AF: "", 0x04B0: "", 0x04B1: "", 0x04B2: "", 0x04B3: "", 0x04B4: "", 0x04B5: "", 0x04B6: "", 0x04B7: "", 0x04B8: "", 0x04B9: "", 0x04BA: "", 0x04BB: "", 0x04BC: "", 0x04BD: "", 0x04BE: "", 0x04BF: "", 0x04C0: "", 0x04C1: "", 0x04C2: "", 0x04C3: "", 0x04C4: "", 0x04C5: "", 0x04C6: "", 0x04C7: "", 0x04C8: "", 0x04C9: "", 0x04CA: "", 0x04CB: "", 0x04CC: "", 0x04CD: "", 0x04CE: "", 0x04CF: "", 0x04D0: "", 0x04D1: "", 0x04D2: "", 0x04D3: "", 0x04D4: "", 0x04D5: "", 0x04D6: "", 0x04D7: "", 0x04D8: "", 0x04D9: "", 0x04DA: "", 0x04DB: "", 0x04DC: "", 0x04DD: "", 0x04DE: "", 0x04DF: "", 0x04E0: "", 0x04E1: "", 0x04E2: "", 0x04E3: "", 0x04E4: "", 0x04E5: "", 0x04E6: "", 0x04E7: "", 0x04E8: "", 0x04E9: "", 0x04EA: "", 0x04EB: "", 0x04EC: "", 0x04ED: "", 0x04EE: "", 0x04EF: "", 0x04F0: "", 0x04F1: "", 0x04F2: "", 0x04F3: "", 0x04F4: "", 0x04F5: "", 0x04F6: "", 0x04F7: "", 0x04F8: "", 0x04F9: "", 0x04FA: "", 0x04FB: "", 0x04FC: "", 0x04FD: "", 0x04FE: "", 0x04FF: "", 0x0500: "", 0x0501: "", 0x0502: "", 0x0503: "", 0x0504: "", 0x0505: "", 0x0506: "", 0x0507: "", 0x0508: "", 0x0509: "", 0x050A: "", 0x050B: "", 0x050C: "", 0x050D: "", 0x050E: "", 0x050F: "", 0x0510: "", 0x0511: "", 0x0512: "", 0x0513: "", 0x0514: "", 0x0515: "", 0x0516: "", 0x0517: "", 0x0518: "", 0x0519: "", 0x051A: "", 0x051B: "", ]
apache-2.0
NoodleOfDeath/PastaParser
runtime/swift/GrammarKit/Classes/model/grammar/token/Grammar.Token.swift
1
4758
// // The MIT License (MIT) // // Copyright © 2020 NoodleOfDeath. All rights reserved. // NoodleOfDeath // // 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 extension Grammar { /// Simple data structure representing a token read by a lexer grammatical scanner. open class Token: IO.Token { enum CodingKeys: String, CodingKey { case rules } // MARK: - CustomStringConvertible Properties override open var description: String { return String(format: "%@ (%d, %d)[%d]: \"%@\"", rules.keys.joined(separator: "/"), range.location, range.max, range.length, value) } open func descriptionWith(format: StringFormattingOption) -> String { return String(format: "%@ (%d, %d)[%d]: \"%@\" ", rules.keys.joined(separator: "/"), range.location, range.max, range.length, value.format(using: format)) } // MARK: - Instance Properties /// Rules associated with this token. open var rules = [String: GrammarRule]() // MARK: - Constructor Methods /// Constructs a new token instance with an initial rule, value, and range. /// /// - Parameters: /// - value: of the new token. /// - range: of the new token. /// - rules: of the new token. public init(value: String, range: NSRange, rules: [GrammarRule] = []) { super.init(value: value, range: range) add(rules: rules) } /// Constructs a new token instance with an initial rul, value, start, /// and length. /// /// Alias for `.init(rule: rule, value: value, /// range: NSMakeRange(start, length))` /// /// - Parameters: /// - rules: of the new token. /// - value: of the new token. /// - start: of the new token. /// - length: of the new token. public convenience init(value: String, start: Int, length: Int, rules: [GrammarRule] = []) { self.init(value: value, range: NSMakeRange(start, length), rules: rules) } // MARK: - Decodable Constructor Methods public required init(from decoder: Decoder) throws { try super.init(from: decoder) let values = try decoder.container(keyedBy: CodingKeys.self) rules = try values.decode([String: GrammarRule].self, forKey: .rules) } // MARK: - Encodable Methods open func encode(with encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(rules, forKey: .rules) } // MARK: - Instance Methods open func add(rule: GrammarRule) { rules[rule.id] = rule } open func add(rules: [GrammarRule]) { rules.forEach({ add(rule: $0 )}) } open func matches(_ rule: GrammarRule) -> Bool { return matches(rule.id) } open func matches(_ id: String) -> Bool { return rules.keys.contains(id) } } } extension IO.TokenStream where Atom: Grammar.Token { open func reduce(over range: Range<Int>) -> String { return reduce(over: range, "", { (a, b) -> String in "\(a)\(b.value)" }) } open func reduce(over range: NSRange) -> String { return reduce(over: range.bridgedRange) } }
mit
collegboi/DIT-Timetable-iOS
DIT-Timetable-V2/Extensions/Integer.swift
1
2115
// // Integer.swift // DIT-Timetable-V2 // // Created by Timothy Barnard on 26/09/2016. // Copyright © 2016 Timothy Barnard. All rights reserved. // import Foundation import UIKit extension Array { func randomValue() -> NSObject { let randomNum:UInt32 = arc4random_uniform(UInt32(self.count)) return self[Int(randomNum)] as! NSObject } } extension UIImageView { func downloadedFrom( actInd: UIActivityIndicatorView, url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) { contentMode = mode actInd.startAnimating() URLSession.shared.dataTask(with: url) { (data, response, error) in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let image = UIImage(data: data) else { return } DispatchQueue.main.async() { () -> Void in self.image = image actInd.stopAnimating() } }.resume() } func downloadedFrom( actInd: UIActivityIndicatorView, link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) { guard let url = URL(string: link) else { return } downloadedFrom( actInd: actInd, url: url, contentMode: mode) } } extension String { func StringTimetoTime( )-> Date { let today = Date() let myCalendar = NSCalendar(calendarIdentifier: .gregorian)! var todayComponents = myCalendar.components([.year, .month, .day, .hour, .minute, .second], from: today) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" let strDate = dateFormatter.date(from: self)! let strDateComp = myCalendar.components([.hour, .minute], from: strDate) todayComponents.hour = strDateComp.hour todayComponents.minute = strDateComp.minute return myCalendar.date(from: todayComponents)! } }
mit
davidlivadaru/DLSuggestionsTextField
Tests/DLSuggestionsTextFieldTests/DLSuggestionsTextFieldTests.swift
1
446
import XCTest @testable import DLSuggestionsTextField class DLSuggestionsTextFieldTests: XCTestCase { func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct // results. XCTAssertEqual(DLSuggestionsTextField().text, "Hello, World!") } static var allTests = [ ("testExample", testExample), ] }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/20823-swift-sourcemanager-getmessage.swift
11
261
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension g { { { { } } { } { } } func a { case var { ( [ [ { for { struct c { class case ,
mit
cnoon/swift-compiler-crashes
crashes-duplicates/12209-swift-modulefile-gettype.swift
11
274
// 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 a { enum S { protocol C { class B { var d = { { { } { var : { struct S { let a { class case c, var }
mit
rentpath/Atlas
AtlasTests/TestModels/User.swift
1
2242
// // User.swift // Atlas // // Created by Jeremy Fox on 3/30/16. // Copyright © 2016 RentPath. All rights reserved. // import Foundation import Atlas struct User { let firstName: String? let lastName: String? let email: String let phone: Int? let avatarURL: String? let isActive: Bool let memberSince: Date? let address: Address? let photos: [Photo]? let floorPlans: [FloorPlan]? } extension User: AtlasMap { func toJSON() -> JSON? { return nil } init?(json: JSON) throws { do { let map = try Atlas(json) firstName = try map.object(forOptional: "first_name") lastName = try map.object(forOptional: "last_name") email = try map.object(for: "email") phone = try map.object(forOptional: "phone") avatarURL = try map.object(forOptional: "avatar") isActive = try map.object(for: "is_active") memberSince = try map.date(for: "member_since", to: .rfc3339) address = try map.object(forOptional: "address") photos = try map.array(forOptional: "photos") floorPlans = try map.array(forOptional: "floorplans") } catch let error { throw error } } } ////////////////////////////////// struct UserNoKey { let firstName: String? let lastName: String? let email: String let phone: Int? let avatarURL: String? let isActive: Bool let memberSince: Date? } extension UserNoKey: AtlasMap { func toJSON() -> JSON? { return nil } init?(json: JSON) throws { do { let map = try Atlas(json) firstName = try map.object(forOptional: "first_name") lastName = try map.object(forOptional: "last_name") email = try map.object(for: "foo") // foo is not a valid key in user json, this is for a test phone = try map.object(forOptional: "phone") avatarURL = try map.object(forOptional: "avatar") isActive = try map.object(for: "is_active") memberSince = try map.date(for: "member_since", to: .rfc3339) } catch let error { throw error } } }
mit
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/LocationPoints/HLLocationPoints.swift
1
5440
import CoreLocation class HLCityAndNearbyPoint: HDKLocationPoint { let city: HDKCity init(name: String, location: CLLocation, city: HDKCity) { self.city = city super.init(name: name, location: location, category: HDKLocationPointCategory.kCityCenter) } required init(from other: Any) { guard let other = other as? HLCityAndNearbyPoint else { fatalError() } city = other.city super.init(from: other) } required init?(coder aDecoder: NSCoder) { guard let city = aDecoder.decodeObject(forKey: "city") as? HDKCity else { return nil } self.city = city super.init(coder: aDecoder) } override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(city, forKey: "city") } override var actionCardDescription: String { return String(format: NSLS("HL_LOC_ACTION_CARD_DISTANCE_CITY_AND_NEARBY"), city.name ?? "") } override func isEqual(_ object: Any?) -> Bool { guard let other = object as? HLCityAndNearbyPoint else { return false } if city != other.city { return false } return super.isEqual(object) } } class HLCustomLocationPoint: HDKLocationPoint { override init(name: String, location: CLLocation) { super.init(name: name, location: location, category: HDKLocationPointCategory.kCustomLocation) } required init(from other: Any) { super.init(from: other) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override var actionCardDescription: String { return NSLS("HL_LOC_ACTION_CARD_DISTANCE_CUSTOM_SEARCH_POINT_TITLE") } } class HLUserLocationPoint: HDKLocationPoint { init(location: CLLocation) { super.init(name: NSLS("HL_LOC_FILTERS_POINT_MY_LOCATION_TEXT"), location: location, category: HDKLocationPointCategory.kUserLocation) } required init(from other: Any) { super.init(from: other) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override var actionCardDescription: String { return NSLS("HL_LOC_ACTION_CARD_DISTANCE_USER_TITLE") } } class HLGenericCategoryLocationPoint: HDKLocationPoint { init(category: String) { super.init(name: HLGenericCategoryLocationPoint.name(for: category), location: CLLocation(latitude: 0, longitude: 0), category: category) } required init(from other: Any) { super.init(from: other) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override var actionCardDescription: String { switch category { case HDKLocationPointCategory.kBeach: return NSLS("HL_LOC_ACTION_CARD_DISTANCE_BEACH_TITLE") case HDKLocationPointCategory.kSkilift: return NSLS("HL_LOC_ACTION_CARD_DISTANCE_SKILIFT_TITLE") default: assertionFailure() return "" } } private static func name(for category: String) -> String { switch category { case HDKLocationPointCategory.kBeach: return NSLS("HL_LOC_FILTERS_POINT_ANY_BEACH_TEXT") case HDKLocationPointCategory.kSkilift: return NSLS("HL_LOC_FILTERS_POINT_ANY_SKILIFT_TEXT") case HDKLocationPointCategory.kMetroStation: return NSLS("HL_LOC_FILTERS_POINT_ANY_METRO_TEXT") default: return "" } } } @objcMembers class HLCityLocationPoint: HDKLocationPoint { let cityName: String? init(city: HDKCity) { let location = CLLocation(latitude: city.latitude, longitude: city.longitude) cityName = city.name super.init(name: NSLS("HL_LOC_FILTERS_POINT_CITY_CENTER_TEXT"), location: location, category: HDKLocationPointCategory.kCityCenter) } required init(from other: Any) { guard let other = other as? HLCityLocationPoint else { fatalError() } cityName = other.cityName super.init(from: other) } required init?(coder aDecoder: NSCoder) { cityName = aDecoder.decodeObject(forKey: "cityName") as? String super.init(coder: aDecoder) } override func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(cityName, forKey: "cityName") } override var actionCardDescription: String { return NSLS("HL_LOC_ACTION_CARD_DISTANCE_CENTER_TITLE") } override func isEqual(_ object: Any?) -> Bool { guard let other = object as? HLCityLocationPoint else { return false } if cityName != other.cityName { return false } return super.isEqual(object) } } class HLAirportLocationPoint: HDKLocationPoint { override init(name: String, location: CLLocation) { super.init(name: name, location: location, category: HDKLocationPointCategory.kAirport) } required init(from other: Any) { super.init(from: other) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override var actionCardDescription: String { return String(format: "%@%@", NSLS("HL_LOC_ACTION_CARD_DISTANCE_FROM_TITLE"), name) } }
mit
glenyi/FloatRatingView
Rating Demo/Rating Demo/AppDelegate.swift
2
2205
// // AppDelegate.swift // Rating Demo // // Created by Glen Yi on 2014-09-05. // Copyright (c) 2014 On The Pursuit. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
quickthyme/PUTcat
PUTcat/Presentation/TransactionResponse/ViewModel/TransactionResponseViewData.swift
1
1731
import UIKit struct TransactionResponseViewData { var section : [TransactionResponseViewDataSection] } struct TransactionResponseViewDataSection { var title : String var item : [TransactionResponseViewDataItem] } struct TransactionResponseViewDataItem { var refID : String = "" var cellID : String = "" var title : String? var detail : String? var icon : UIImage? var accessory : UITableViewCellAccessoryType = .none var sizing : Sizing = .default enum Sizing { case auto, fixed, `default` var tableRowHeight: CGFloat { switch (self) { case .auto: return UITableViewAutomaticDimension case .fixed: return 36.0 case .default: return 55.0 } } } } extension TransactionResponseViewDataItem : ViewDataItem {} extension TransactionResponseViewData : Equatable {} func == (lhs: TransactionResponseViewData, rhs: TransactionResponseViewData) -> Bool { return (lhs.section == rhs.section) } extension TransactionResponseViewDataSection : Equatable {} func == (lhs: TransactionResponseViewDataSection, rhs: TransactionResponseViewDataSection) -> Bool { return (lhs.title == rhs.title && lhs.item == rhs.item) } extension TransactionResponseViewDataItem : Equatable {} func == (lhs: TransactionResponseViewDataItem, rhs: TransactionResponseViewDataItem) -> Bool { return (lhs.refID == rhs.refID && lhs.cellID == rhs.cellID && lhs.title == rhs.title && lhs.detail == rhs.detail) } protocol TransactionResponseViewDataItemConfigurable : class { func configure(transactionResponseViewDataItem item: TransactionResponseViewDataItem) }
apache-2.0
tardieu/swift
benchmark/single-source/StrComplexWalk.swift
10
1870
//===--- StrComplexWalk.swift ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils @inline(never) public func run_StrComplexWalk(_ N: Int) { var s = "निरन्तरान्धकारिता-दिगन्तर-कन्दलदमन्द-सुधारस-बिन्दु-सान्द्रतर-घनाघन-वृन्द-सन्देहकर-स्यन्दमान-मकरन्द-बिन्दु-बन्धुरतर-माकन्द-तरु-कुल-तल्प-कल्प-मृदुल-सिकता-जाल-जटिल-मूल-तल-मरुवक-मिलदलघु-लघु-लय-कलित-रमणीय-पानीय-शालिका-बालिका-करार-विन्द-गलन्तिका-गलदेला-लवङ्ग-पाटल-घनसार-कस्तूरिकातिसौरभ-मेदुर-लघुतर-मधुर-शीतलतर-सलिलधारा-निराकरिष्णु-तदीय-विमल-विलोचन-मयूख-रेखापसारित-पिपासायास-पथिक-लोकान्" let ref_result = 379 for _ in 1...2000*N { var count = 0 for _ in s.unicodeScalars { count += 1 } CheckResults(count == ref_result, "Incorrect results in StrComplexWalk: \(count) != \(ref_result)") } }
apache-2.0
box/box-ios-sdk
Tests/Responses/SignRequestSignerInputContentTypeSpecs.swift
1
2728
// // SignRequestSignerInputContentTypeSpecs.swift // BoxSDKTests-iOS // // Created by Minh Nguyen Cong on 30/08/2022. // Copyright © 2022 box. All rights reserved. // @testable import BoxSDK import Nimble import Quick class SignRequestSignerInputContentTypeSpecs: QuickSpec { override func spec() { describe("SignRequestSignerInputContentType") { describe("init()") { it("should correctly create an enum value from it's string representation") { expect(SignRequestSignerInputContentType.initial).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.initial.description))) expect(SignRequestSignerInputContentType.stamp).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.stamp.description))) expect(SignRequestSignerInputContentType.signature).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.signature.description))) expect(SignRequestSignerInputContentType.company).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.company.description))) expect(SignRequestSignerInputContentType.title).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.title.description))) expect(SignRequestSignerInputContentType.email).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.email.description))) expect(SignRequestSignerInputContentType.fullName).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.fullName.description))) expect(SignRequestSignerInputContentType.firstName).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.firstName.description))) expect(SignRequestSignerInputContentType.lastName).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.lastName.description))) expect(SignRequestSignerInputContentType.text).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.text.description))) expect(SignRequestSignerInputContentType.date).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.date.description))) expect(SignRequestSignerInputContentType.checkbox).to(equal(SignRequestSignerInputContentType(SignRequestSignerInputContentType.checkbox.description))) expect(SignRequestSignerInputContentType.customValue("custom value")).to(equal(SignRequestSignerInputContentType("custom value"))) } } } } }
apache-2.0
boluomeng/Charts
ChartsDemo-OSX/ChartsDemo-OSX/Demos/BarDemoViewController.swift
1
2281
// // BarDemoViewController.swift // ChartsDemo-OSX // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts import Foundation import Cocoa import Charts open class BarDemoViewController: NSViewController { @IBOutlet var barChartView: BarChartView! override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let xs = Array(1..<10).map { return Double($0) } let ys1 = xs.map { i in return sin(Double(i / 2.0 / 3.141 * 1.5)) } let ys2 = xs.map { i in return cos(Double(i / 2.0 / 3.141)) } let yse1 = ys1.enumerated().map { idx, i in return BarChartDataEntry(value: i, xIndex: idx) } let yse2 = ys2.enumerated().map { idx, i in return BarChartDataEntry(value: i, xIndex: idx) } let data = BarChartData(xVals: xs as [NSObject]) let ds1 = BarChartDataSet(yVals: yse1, label: "Hello") ds1.colors = [NSUIColor.red] data.addDataSet(ds1) let ds2 = BarChartDataSet(yVals: yse2, label: "World") ds2.colors = [NSUIColor.blue] data.addDataSet(ds2) self.barChartView.data = data self.barChartView.gridBackgroundColor = NSUIColor.white self.barChartView.descriptionText = "Barchart Demo" } @IBAction func save(_ sender: AnyObject) { let panel = NSSavePanel() panel.allowedFileTypes = ["png"] panel.beginSheetModal(for: self.view.window!) { (result) -> Void in if result == NSFileHandlingPanelOKButton { if let path = panel.url?.path { do { _ = try self.barChartView.saveToPath(path, format: .png, compressionQuality: 1.0) } catch { print("Saving encounter errors") } } } } } override open func viewWillAppear() { self.barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0) } }
apache-2.0
michaelgwelch/pandemic
Pandemic/GameBoardCity.swift
1
5516
// // GameBoardCity.swift // Pandemic // // Created by Michael Welch on 3/11/16. // Copyright © 2016 Michael Welch. All rights reserved. // import Foundation public class GameBoardCityFactory { public let algiers = { () in GameBoardCity(city: City.algiers) } public let atlanta = { () in GameBoardCity(city: City.atlanta) } public let baghdad = { () in GameBoardCity(city: City.baghdad) } public let bangkok = { () in GameBoardCity(city: City.bangkok) } public let beijing = { () in GameBoardCity(city: City.beijing) } public let bogotá = { () in GameBoardCity(city: City.bogotá) } public let buenosaires = { () in GameBoardCity(city: City.buenosaires) } public let cairo = { () in GameBoardCity(city: City.cairo) } public let chennai = { () in GameBoardCity(city: City.chennai) } public let chicago = { () in GameBoardCity(city: City.chicago) } public let delhi = { () in GameBoardCity(city: City.delhi) } public let essen = { () in GameBoardCity(city: City.essen) } public let hochiminhcity = { () in GameBoardCity(city: City.hochiminhcity) } public let hongkong = { () in GameBoardCity(city: City.hongkong) } public let istanbul = { () in GameBoardCity(city: City.istanbul) } public let jakarta = { () in GameBoardCity(city: City.jakarta) } public let johannesburg = { () in GameBoardCity(city: City.johannesburg) } public let karachi = { () in GameBoardCity(city: City.karachi) } public let khartoum = { () in GameBoardCity(city: City.khartoum) } public let kinshasa = { () in GameBoardCity(city: City.kinshasa) } public let kolkata = { () in GameBoardCity(city: City.kolkata) } public let lagos = { () in GameBoardCity(city: City.lagos) } public let lima = { () in GameBoardCity(city: City.lima) } public let london = { () in GameBoardCity(city: City.london) } public let losangeles = { () in GameBoardCity(city: City.losangeles) } public let madrid = { () in GameBoardCity(city: City.madrid) } public let manila = { () in GameBoardCity(city: City.manila) } public let mexicocity = { () in GameBoardCity(city: City.mexicocity) } public let miami = { () in GameBoardCity(city: City.miami) } public let milan = { () in GameBoardCity(city: City.milan) } public let montreal = { () in GameBoardCity(city: City.montreal) } public let moscow = { () in GameBoardCity(city: City.moscow) } public let mumbai = { () in GameBoardCity(city: City.mumbai) } public let newyork = { () in GameBoardCity(city: City.newyork) } public let osaka = { () in GameBoardCity(city: City.osaka) } public let paris = { () in GameBoardCity(city: City.paris) } public let riyadh = { () in GameBoardCity(city: City.riyadh) } public let sanfrancisco = { () in GameBoardCity(city: City.sanfrancisco) } public let santiago = { () in GameBoardCity(city: City.santiago) } public let sãopaulo = { () in GameBoardCity(city: City.sãopaulo) } public let seoul = { () in GameBoardCity(city: City.seoul) } public let shanghai = { () in GameBoardCity(city: City.shanghai) } public let stpetersburg = { () in GameBoardCity(city: City.stpetersburg) } public let sydney = { () in GameBoardCity(city: City.sydney) } public let taipei = { () in GameBoardCity(city: City.taipei) } public let tehran = { () in GameBoardCity(city: City.tehran) } public let tokyo = { () in GameBoardCity(city: City.tokyo) } public let washington = { () in GameBoardCity(city: City.washington) } } public class GameBoardCity : Equatable { private let city:City let counters:[Color:DiseaseCounter] convenience init(city:City) { self.init(city:city, initialCount:0) } init(city:City, initialCount:Int) { self.city = city var counters = [Color:DiseaseCounter]() counters[.Red] = DiseaseCounter() counters[.Yellow] = DiseaseCounter() counters[.Black] = DiseaseCounter() counters[.Blue] = DiseaseCounter() let counter = DiseaseCounter(initialValue: initialCount) switch city.color { case .Yellow: counters[.Yellow] = counter case .Red: counters[.Red] = counter case .Blue: counters[.Blue] = counter case .Black: counters[.Black] = counter } self.counters = counters } func infect() { counters[city.color]!.increment() } func isOutbreakingInColor(color:Color) -> Bool { return counters[color]!.error } func diseaseCountForColor(color:Color) -> Int { return counters[color]!.value } func treatColor(color:Color) { counters[color]!.decrement() } func treatAllColor(color:Color) { counters[color]!.reset() } /** Clears the outbreak flag. */ func clearOutbreak() { Color.colors.forEach { counters[$0]!.clearError() } } class func outbreakingCity(city:City) -> GameBoardCity { let city = GameBoardCity(city: city, initialCount: 3) city.infect() return city } } extension GameBoardCity : CustomStringConvertible { public var description:String { return self.city.name } } extension GameBoardCity : CityInfo { public var name:String { return city.name } public var color:Color { return city.color } } public func ==(lhs:GameBoardCity, rhs:GameBoardCity) -> Bool { return lhs === rhs }
mit
OscarSwanros/swift
test/multifile/class-layout/final-stored-property/main.swift
2
250
// RUN: %target-build-swift %S/library.swift %S/main.swift // RUN: %target-build-swift -whole-module-optimization %S/library.swift %S/main.swift // REQUIRES: executable_test func meltCheese(_ burger: Burger) -> Int { return burger.cheeseSlices }
apache-2.0
lorentey/swift
test/Parse/ConditionalCompilation/i386WatchOSTarget.swift
30
409
// RUN: %swift -typecheck %s -verify -target i386-apple-watchos2.0 -parse-stdlib // RUN: %swift-ide-test -test-input-complete -source-filename=%s -target i386-apple-watchos2.0 #if os(iOS) // This block should not parse. // os(tvOS) or os(watchOS) does not imply os(iOS). let i: Int = "Hello" #endif #if arch(i386) && os(watchOS) && _runtime(_ObjC) && _endian(little) class C {} var x = C() #endif var y = x
apache-2.0
JiriTrecak/Warp
Source/WRPExtensions.swift
3
7495
// // WRPExtensions.swift // // Copyright (c) 2016 Jiri Trecak (http://jiritrecak.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. // // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Imports import Foundation // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Extension - NSDictionary extension NSMutableDictionary { /** * Set an object for the property identified by a given key path to a given value. * * @param object The object for the property identified by _keyPath_. * @param keyPath A key path of the form _relationship.property_ (with one or more relationships): for example “department.name” or “department.manager.lastName.” */ func setObject(_ object : AnyObject!, forKeyPath : String) { self.setObject(object, onObject : self, forKeyPath: forKeyPath, createIntermediates: true, replaceIntermediates: true); } /** * Set an object for the property identified by a given key path to a given value, with optional parameters to control creation and replacement of intermediate objects. * * @param object The object for the property identified by _keyPath_. * @param keyPath A key path of the form _relationship.property_ (with one or more relationships): for example “department.name” or “department.manager.lastName.” * @param createIntermediates Intermediate dictionaries defined within the key path that do not currently exist in the receiver are created. * @param replaceIntermediates Intermediate objects encountered in the key path that are not a direct subclass of `NSDictionary` are replaced. */ func setObject(_ object : AnyObject, onObject : AnyObject, forKeyPath : String, createIntermediates: Bool, replaceIntermediates: Bool) { // Path delimiter = . let pathDelimiter : String = "." // There is no keypath, just assign object if forKeyPath.range(of: pathDelimiter) == nil { onObject.set(object, forKey: forKeyPath); } // Create path components separated by delimiter (. by default) and get key for root object let pathComponents : Array<String> = forKeyPath.components(separatedBy: pathDelimiter); let rootKey : String = pathComponents[0]; let replacementDictionary : NSMutableDictionary = NSMutableDictionary(); // Store current state for further replacement var previousObject : AnyObject? = onObject; var previousReplacement : NSMutableDictionary = replacementDictionary; var reachedDictionaryLeaf : Bool = false; // Traverse through path from root to deepest level for path : String in pathComponents { let currentObject : AnyObject? = reachedDictionaryLeaf ? nil : previousObject?.object(forKey: path) as AnyObject?; // Check if object already exists. If not, create new level, if allowed, or end if currentObject == nil { reachedDictionaryLeaf = true; if createIntermediates { let newNode : NSMutableDictionary = NSMutableDictionary(); previousReplacement.setObject(newNode, forKey: path as NSCopying); previousReplacement = newNode; } else { return; } // If it does and it is dictionary, create mutable copy and assign new node there } else if currentObject is NSDictionary { let newNode : NSMutableDictionary = NSMutableDictionary(dictionary: currentObject as! [AnyHashable: Any]); previousReplacement.setObject(newNode, forKey: path as NSCopying); previousReplacement = newNode; // It exists but it is not NSDictionary, so we replace it, if allowed, or end } else { reachedDictionaryLeaf = true; if replaceIntermediates { let newNode : NSMutableDictionary = NSMutableDictionary(); previousReplacement.setObject(newNode, forKey: path as NSCopying); previousReplacement = newNode; } else { return; } } // Replace previous object with the new one previousObject = currentObject; } // Replace root object with newly created n-level dictionary replacementDictionary.setValue(object, forKeyPath: forKeyPath); onObject.set(replacementDictionary.object(forKey: rootKey), forKey: rootKey); } } extension NSRange { init(location:Int, length:Int) { self.location = location self.length = length } init(_ location:Int, _ length:Int) { self.location = location self.length = length } init(range:Range <Int>) { self.location = range.lowerBound self.length = range.upperBound - range.lowerBound } init(_ range:Range <Int>) { self.location = range.lowerBound self.length = range.upperBound - range.lowerBound } var startIndex:Int { get { return location } } var endIndex:Int { get { return location + length } } var asRange:CountableRange<Int> { get { return location..<location + length } } var isEmpty:Bool { get { return length == 0 } } func contains(_ index:Int) -> Bool { return index >= location && index < endIndex } func clamp(_ index:Int) -> Int { return max(self.startIndex, min(self.endIndex - 1, index)) } func intersects(_ range:NSRange) -> Bool { return NSIntersectionRange(self, range).isEmpty == false } func intersection(_ range:NSRange) -> NSRange { return NSIntersectionRange(self, range) } func union(_ range:NSRange) -> NSRange { return NSUnionRange(self, range) } }
mit
tinrobots/Mechanica
Sources/UIKit/UIImage+Utils.swift
1
11026
#if canImport(UIKit) && (os(iOS) || os(tvOS) || watchOS) import UIKit extension UIImage { /// **Mechanica** /// /// Returns an image with a background `color`, `size` and `scale`. /// - Parameters: /// - color: The background UIColor. /// - size: The image size (default is 1x1). /// - scaleFactor: The scale factor to apply; if you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen. /// - Note: The size of the rectangle is beeing rounded from UIKit. public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1), scale scaleFactor: CGFloat = 0.0) { let rect = CGRect(origin: .zero, size: size) let format = UIGraphicsImageRendererFormat() format.scale = scaleFactor let renderer = UIGraphicsImageRenderer(size: size, format: format) let image = renderer.image { (context) in color.setFill() context.fill(rect) } guard let cgImage = image.cgImage else { return nil } self.init(cgImage: cgImage) /// left only for reference /* UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } color.setFill() UIRectFill(rect) guard let cgImage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { return nil } self.init(cgImage: cgImage) */ } } // MARK: - Scaling extension UIImage { /// **Mechanica** /// /// Returns a new version of the image scaled to the specified size. /// /// - Parameters: /// - size: The size to use when scaling the new image. /// - scale scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - Returns: A `new` scaled UIImage. /// - Note: The opaqueness is the same of the initial images. public func scaled(to size: CGSize, scale scaleFactor: CGFloat = 0.0) -> UIImage { return scaled(to: size, opaque: isOpaque, scale: scale) } /// **Mechanica** /// /// Returns a new version of the image scaled to the specified size. /// /// - Parameters: /// - size: The size to use when scaling the new image. /// - scale scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// - opaque: Specifying `false` means that the image will include an alpha channel. /// /// - Returns: A `new` scaled UIImage. public func scaled(to size: CGSize, opaque: Bool = false, scale scaleFactor: CGFloat = 0.0) -> UIImage { assert(size.width > 0 && size.height > 0, "An image with zero width or height cannot be scaled properly.") UIGraphicsBeginImageContextWithOptions(size, opaque, scaleFactor) draw(in: CGRect(origin: .zero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } /// **Mechanica** /// /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within /// a specified size. /// /// - Parameters: /// - size: The size to use when scaling the new image. /// - scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - Returns: A new image object. public func aspectScaled(toFit size: CGSize, scale scaleFactor: CGFloat = 0.0) -> UIImage { assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height") let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.width / self.size.width } else { resizeFactor = size.height / self.size.height } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) let format = UIGraphicsImageRendererFormat() format.scale = scaleFactor let renderer = UIGraphicsImageRenderer(size: size, format: format) let scaledImage = renderer.image { _ in draw(in: CGRect(origin: origin, size: scaledSize)) } return scaledImage } /// **Mechanica** /// /// Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a /// specified size. Any pixels that fall outside the specified size are clipped. /// /// - Parameters: /// - size: The size to use when scaling the new image. /// - scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - returns: A new `UIImage` object. public func aspectScaled(toFill size: CGSize, scale scaleFactor: CGFloat = 0.0) -> UIImage { assert(size.width > 0 && size.height > 0, "An image with zero width or height cannot be scaled properly.") let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.height / self.size.height } else { resizeFactor = size.width / self.size.width } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, isOpaque, scaleFactor) draw(in: CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self UIGraphicsEndImageContext() return scaledImage } } // MARK: - Rounding extension UIImage { /// **Mechanica** /// /// Returns a new version of the image with the corners rounded to the specified radius. /// /// - parameter radius: The radius to use when rounding the new image. /// - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the /// image has the same resolution for all screen scales such as @1x, @2x and /// @3x (i.e. single image from web server). Set to `false` for images loaded /// from an asset catalog with varying resolutions for each screen scale. /// `false` by default. /// - parameter scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - returns: A new `UIImage` object. public func rounded(withCornerRadius radius: CGFloat, divideRadiusByImageScale: Bool = false, scale scaleFactor: CGFloat = 0.0) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, scaleFactor) let scaledRadius = divideRadiusByImageScale ? radius / scale : radius let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: scaledRadius) clippingPath.addClip() draw(in: CGRect(origin: CGPoint.zero, size: size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } /// **Mechanica** /// /// Returns a new version of the image rounded into a circle. /// /// - parameter scaleFactor: The display scale of the image renderer context (defaults to the scale of the main screen). /// /// - returns: A new `UIImage` object. public func roundedIntoCircle(scale scaleFactor: CGFloat = 0.0) -> UIImage { let radius = min(size.width, size.height) / 2.0 var squareImage = self if size.width != size.height { let squareDimension = min(size.width, size.height) let squareSize = CGSize(width: squareDimension, height: squareDimension) squareImage = aspectScaled(toFill: squareSize) } UIGraphicsBeginImageContextWithOptions(squareImage.size, false, scaleFactor) let clippingPath = UIBezierPath( roundedRect: CGRect(origin: CGPoint.zero, size: squareImage.size), cornerRadius: radius ) clippingPath.addClip() squareImage.draw(in: CGRect(origin: CGPoint.zero, size: squareImage.size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return roundedImage } /// **Mechanica** /// /// Returns a new decoded version of the image. /// /// It allows a bitmap representation to be decoded in the background rather than on the main thread. /// /// - Parameters: /// - scale: The scale factor to assume when interpreting the image data (defaults to `self.scale`); the decoded image will have its size divided by this scale parameter. /// - allowedMaxSize: The allowed max size, if the image is too large the decoding operation will return nil. /// - returns: A new decoded `UIImage` object. public func decoded(scale: CGFloat? = .none, allowedMaxSize: Int = 4096 * 4096) -> UIImage? { // Do not attempt to render animated images guard images == nil else { return nil } // Do not attempt to render if not backed by a CGImage guard let image = cgImage?.copy() else { return nil } let width = image.width let height = image.height let bitsPerComponent = image.bitsPerComponent // Do not attempt to render if too large or has more than 8-bit components guard width * height <= allowedMaxSize && bitsPerComponent <= 8 else { return nil } //TODO: remove this condition? let bytesPerRow: Int = 0 let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo = image.bitmapInfo // Fix alpha channel issues if necessary let alpha = (bitmapInfo.rawValue & CGBitmapInfo.alphaInfoMask.rawValue) if alpha == CGImageAlphaInfo.none.rawValue { bitmapInfo.remove(.alphaInfoMask) bitmapInfo = CGBitmapInfo(rawValue: bitmapInfo.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue) } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) { bitmapInfo.remove(.alphaInfoMask) bitmapInfo = CGBitmapInfo(rawValue: bitmapInfo.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) } // Render the image let context = CGContext( data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue ) context?.draw(image, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(width), height: CGFloat(height))) // Make sure the inflation was successful guard let renderedImage = context?.makeImage() else { return nil } let imageScale = scale ?? self.scale return UIImage(cgImage: renderedImage, scale: imageScale, orientation: imageOrientation) } } #endif
mit
imchenglibin/XTPopupView
XTPopupView/Window.swift
1
702
// // Window.swift // XTPopupView // // Created by imchenlibin on 16/1/29. // Copyright © 2016年 xt. All rights reserved. // import UIKit public class Window: UIWindow { public static let sharedWindow:Window = { let window = Window(frame: UIScreen.mainScreen().bounds) window.rootViewController = UIViewController() window.rootViewController!.view.backgroundColor = UIColor(white: 0.5, alpha: 0.5) window.hidden = true window.windowLevel = UIWindowLevelStatusBar + 1 window.makeKeyAndVisible() return window }() public func mainView() -> UIView { return Window.sharedWindow.rootViewController!.view; } }
mit
Palleas/Batman
Batman/Domain/ProjectsController.swift
1
2226
import Foundation import Result import ReactiveSwift import Unbox final class ProjectsController { enum ProjectsError: Error, AutoEquatable { case noCache case fetchingError(Client.ClientError) } private let client: Client let selectedProject = MutableProperty<Project?>(nil) private let projectsPath: URL init(client: Client, cacheDirectory: URL) { self.client = client self.projectsPath = cacheDirectory.appendingPathComponent("projects.json") } typealias Projects = SignalProducer<[Project], ProjectsError> func fetch() -> Projects { return fetchFromCache().flatMapError { error in guard error == ProjectsError.noCache else { return SignalProducer(error: error) } return self.fetchFromRemote() } } func fetchFromCache() -> Projects { return SignalProducer<Data, ProjectsError> { sink, _ in guard FileManager.default.fileExists(atPath: self.projectsPath.path) else { sink.send(error: .noCache) return } do { // TODO: Expiration date sink.send(value: try Data(contentsOf: self.projectsPath)) sink.sendCompleted() } catch { sink.send(error: .noCache) } } .attemptMap { return decodeArray(from: $0).mapError { _ in ProjectsError.noCache } } } func fetchFromRemote() -> Projects { return self.client.projects() .mapError(ProjectsError.fetchingError) .flatMap(.latest, self.save) } func save(projects: [Project]) -> SignalProducer<[Project], NoError> { return SignalProducer { sink, _ in defer { // Sending projects anyway sink.send(value: projects) sink.sendCompleted() } do { let encoded = try projects.encode() try encoded.write(to: self.projectsPath) print("Cached to \(self.projectsPath)") } catch { print("Unable to cache projects") } } } }
mit
thdtjsdn/realm-cocoa
RealmSwift-swift2.0/Tests/ObjectTests.swift
4
12871
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // 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 import RealmSwift import Foundation class ObjectTests: TestCase { // init() Tests are in ObjectCreationTests.swift // init(value:) tests are in ObjectCreationTests.swift func testRealm() { let standalone = SwiftStringObject() XCTAssertNil(standalone.realm) let realm = try! Realm() var persisted: SwiftStringObject! realm.write { persisted = realm.create(SwiftStringObject.self, value: [:]) XCTAssertNotNil(persisted.realm) XCTAssertEqual(realm, persisted.realm!) } XCTAssertNotNil(persisted.realm) XCTAssertEqual(realm, persisted.realm!) dispatchSyncNewThread { autoreleasepool { XCTAssertNotEqual(try! Realm(), persisted.realm!) } } } func testObjectSchema() { let object = SwiftObject() let schema = object.objectSchema XCTAssert(schema as AnyObject is ObjectSchema) XCTAssert(schema.properties as AnyObject is [Property]) XCTAssertEqual(schema.className, "SwiftObject") XCTAssertEqual(schema.properties.map { $0.name }, ["boolCol", "intCol", "floatCol", "doubleCol", "stringCol", "binaryCol", "dateCol", "objectCol", "arrayCol"]) } func testInvalidated() { let object = SwiftObject() XCTAssertFalse(object.invalidated) let realm = try! Realm() realm.write { realm.add(object) XCTAssertFalse(object.invalidated) } realm.write { realm.deleteAll() XCTAssertTrue(object.invalidated) } XCTAssertTrue(object.invalidated) } func testDescription() { let object = SwiftObject() XCTAssertEqual(object.description, "SwiftObject {\n\tboolCol = 0;\n\tintCol = 123;\n\tfloatCol = 1.23;\n\tdoubleCol = 12.3;\n\tstringCol = a;\n\tbinaryCol = <61 — 1 total bytes>;\n\tdateCol = 1970-01-01 00:00:01 +0000;\n\tobjectCol = SwiftBoolObject {\n\t\tboolCol = 0;\n\t};\n\tarrayCol = List<SwiftBoolObject> (\n\t\n\t);\n}") let recursiveObject = SwiftRecursiveObject() recursiveObject.objects.append(recursiveObject) XCTAssertEqual(recursiveObject.description, "SwiftRecursiveObject {\n\tobjects = List<SwiftRecursiveObject> (\n\t\t[0] SwiftRecursiveObject {\n\t\t\tobjects = List<SwiftRecursiveObject> (\n\t\t\t\t[0] SwiftRecursiveObject {\n\t\t\t\t\tobjects = <Maximum depth exceeded>;\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t);\n}") } func testPrimaryKey() { XCTAssertNil(Object.primaryKey(), "primary key should default to nil") XCTAssertNil(SwiftStringObject.primaryKey()) XCTAssertNil(SwiftStringObject().objectSchema.primaryKeyProperty) XCTAssertEqual(SwiftPrimaryStringObject.primaryKey()!, "stringCol") XCTAssertEqual(SwiftPrimaryStringObject().objectSchema.primaryKeyProperty!.name, "stringCol") } func testIgnoredProperties() { XCTAssertEqual(Object.ignoredProperties(), [], "ignored properties should default to []") XCTAssertEqual(SwiftIgnoredPropertiesObject.ignoredProperties().count, 2) XCTAssertNil(SwiftIgnoredPropertiesObject().objectSchema["runtimeProperty"]) } func testIndexedProperties() { XCTAssertEqual(Object.indexedProperties(), [], "indexed properties should default to []") XCTAssertEqual(SwiftIndexedPropertiesObject.indexedProperties().count, 1) XCTAssertTrue(SwiftIndexedPropertiesObject().objectSchema["stringCol"]!.indexed) } func testLinkingObjects() { let realm = try! Realm() let object = SwiftEmployeeObject() assertThrows(object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees")) realm.write { realm.add(object) self.assertThrows(object.linkingObjects(SwiftCompanyObject.self, forProperty: "noSuchCol")) XCTAssertEqual(0, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) for _ in 0..<10 { realm.create(SwiftCompanyObject.self, value: [[object]]) } XCTAssertEqual(10, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) } XCTAssertEqual(10, object.linkingObjects(SwiftCompanyObject.self, forProperty: "employees").count) } func testValueForKey() { let test: (SwiftObject) -> () = { object in XCTAssertEqual(object.valueForKey("boolCol") as! Bool!, false) XCTAssertEqual(object.valueForKey("intCol") as! Int!, 123) XCTAssertEqual(object.valueForKey("floatCol") as! Float!, 1.23 as Float) XCTAssertEqual(object.valueForKey("doubleCol") as! Double!, 12.3) XCTAssertEqual(object.valueForKey("stringCol") as! String!, "a") XCTAssertEqual(object.valueForKey("binaryCol") as! NSData, "a".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) XCTAssertEqual(object.valueForKey("dateCol") as! NSDate!, NSDate(timeIntervalSince1970: 1)) XCTAssertEqual((object.valueForKey("objectCol")! as! SwiftBoolObject).boolCol, false) XCTAssert(object.valueForKey("arrayCol")! is List<SwiftBoolObject>) } test(SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) test(persistedObject) } } func setAndTestAllTypes(setter: (SwiftObject, AnyObject?, String) -> (), getter: (SwiftObject, String) -> (AnyObject?), object: SwiftObject) { setter(object, true, "boolCol") XCTAssertEqual(getter(object, "boolCol") as! Bool!, true) setter(object, 321, "intCol") XCTAssertEqual(getter(object, "intCol") as! Int!, 321) setter(object, 32.1 as Float, "floatCol") XCTAssertEqual(getter(object, "floatCol") as! Float!, 32.1 as Float) setter(object, 3.21, "doubleCol") XCTAssertEqual(getter(object, "doubleCol") as! Double!, 3.21) setter(object, "z", "stringCol") XCTAssertEqual(getter(object, "stringCol") as! String!, "z") setter(object, "z".dataUsingEncoding(NSUTF8StringEncoding), "binaryCol") XCTAssertEqual(getter(object, "binaryCol") as! NSData, "z".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) setter(object, NSDate(timeIntervalSince1970: 333), "dateCol") XCTAssertEqual(getter(object, "dateCol") as! NSDate!, NSDate(timeIntervalSince1970: 333)) let boolObject = SwiftBoolObject(value: [true]) setter(object, boolObject, "objectCol") XCTAssertEqual(getter(object, "objectCol") as! SwiftBoolObject, boolObject) XCTAssertEqual((getter(object, "objectCol")! as! SwiftBoolObject).boolCol, true) let list = List<SwiftBoolObject>() list.append(boolObject) setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).first!, boolObject) list.removeAll(); setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 0) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<SwiftBoolObject>).first!, boolObject) } func dynamicSetAndTestAllTypes(setter: (DynamicObject, AnyObject?, String) -> (), getter: (DynamicObject, String) -> (AnyObject?), object: DynamicObject, boolObject: DynamicObject) { setter(object, true, "boolCol") XCTAssertEqual(getter(object, "boolCol") as! Bool, true) setter(object, 321, "intCol") XCTAssertEqual(getter(object, "intCol") as! Int, 321) setter(object, 32.1 as Float, "floatCol") XCTAssertEqual(getter(object, "floatCol") as! Float, 32.1 as Float) setter(object, 3.21, "doubleCol") XCTAssertEqual(getter(object, "doubleCol") as! Double, 3.21) setter(object, "z", "stringCol") XCTAssertEqual(getter(object, "stringCol") as! String, "z") setter(object, "z".dataUsingEncoding(NSUTF8StringEncoding), "binaryCol") XCTAssertEqual(getter(object, "binaryCol") as! NSData, "z".dataUsingEncoding(NSUTF8StringEncoding)! as NSData) setter(object, NSDate(timeIntervalSince1970: 333), "dateCol") XCTAssertEqual(getter(object, "dateCol") as! NSDate, NSDate(timeIntervalSince1970: 333)) setter(object, boolObject, "objectCol") XCTAssertEqual(getter(object, "objectCol") as! DynamicObject, boolObject) XCTAssertEqual((getter(object, "objectCol") as! DynamicObject)["boolCol"] as! NSNumber, true as NSNumber) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).first!, boolObject) let list = getter(object, "arrayCol") as! List<DynamicObject> list.removeAll(); setter(object, list, "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 0) setter(object, [boolObject], "arrayCol") XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).count, 1) XCTAssertEqual((getter(object, "arrayCol") as! List<DynamicObject>).first!, boolObject) } /// Yields a read-write migration `SwiftObject` to the given block private func withMigrationObject(block: ((MigrationObject, Migration) -> ())) { autoreleasepool { let realm = self.realmWithTestPath() realm.write { _ = realm.create(SwiftObject) } } autoreleasepool { var enumerated = false setSchemaVersion(1, realmPath: self.testRealmPath()) { migration, _ in migration.enumerate(SwiftObject.className()) { oldObject, newObject in if let newObject = newObject { block(newObject, migration) enumerated = true } } } self.realmWithTestPath() XCTAssert(enumerated) } } func testSetValueForKey() { let setter : (Object, AnyObject?, String) -> () = { object, value, key in object.setValue(value, forKey: key) return } let getter : (Object, String) -> (AnyObject?) = { object, key in object.valueForKey(key) } withMigrationObject { migrationObject, migration in let boolObject = migration.create("SwiftBoolObject", value: [true]) self.dynamicSetAndTestAllTypes(setter, getter: getter, object: migrationObject, boolObject: boolObject) } setAndTestAllTypes(setter, getter: getter, object: SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) self.setAndTestAllTypes(setter, getter: getter, object: persistedObject) } } func testSubscript() { let setter : (Object, AnyObject?, String) -> () = { object, value, key in object[key] = value return } let getter : (Object, String) -> (AnyObject?) = { object, key in object[key] } withMigrationObject { migrationObject, migration in let boolObject = migration.create("SwiftBoolObject", value: [true]) self.dynamicSetAndTestAllTypes(setter, getter: getter, object: migrationObject, boolObject: boolObject) } setAndTestAllTypes(setter, getter: getter, object: SwiftObject()) try! Realm().write { let persistedObject = try! Realm().create(SwiftObject.self, value: [:]) self.setAndTestAllTypes(setter, getter: getter, object: persistedObject) } } }
apache-2.0
mozilla-mobile/prox
Prox/ProxTests/ProxTests.swift
2
820
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import XCTest @testable import Prox class ProxTests: 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. } }
mpl-2.0
xsunsmile/zentivity
zentivity/AppDelegate.swift
1
5413
// // AppDelegate.swift // zentivity // // Created by Andrew Wen on 3/5/15. // Copyright (c) 2015 Zendesk. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var storyboard = UIStoryboard(name: "Main", bundle: nil) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Parse setup User.registerSubclass() Photo.registerSubclass() Event.registerSubclass() Comment.registerSubclass() Parse.setApplicationId("LEwfLcFvUwXtT8A7y2dJMlHL7FLiEybY8x5kOaZP", clientKey: "YRAwfZdssZrBJtNGqE0wIEyiAaBoARiCih5hrNau") NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleGoogleLogin:", name: "userDidLoginNotification", object: nil) return true } func loginToParseWithUserInfo(userInfo: NSDictionary) { let email = userInfo["email"] as! String let name = userInfo["name"] as! String let image = userInfo["imageUrl"] as! String let aboutMe = userInfo["aboutMe"] as! String PFCloud.callFunctionInBackground("getUserSessionToken", withParameters: ["username" : email]) { (sessionToken, error) -> Void in if let sessionToken = sessionToken as? String { PFUser.becomeInBackground(sessionToken, block: { (user, error) -> Void in if error == nil { // Found user with sessionToken println("Logged in user with session token") User.currentUser()!.name = name User.currentUser()!.imageUrl = image User.currentUser()!.aboutMe = aboutMe User.currentUser()!.saveInBackgroundWithBlock({ (success, error) -> Void in // Nothing now }) self.showEventsVC() } else { // Could not find user with sessionToken // SUPER FAIL! println("SUPER FAIL!") } }) } else { // Could not find user email var user = User() user.username = email user.password = "1" user.name = name user.imageUrl = image user.aboutMe = aboutMe ParseClient.setUpUserWithCompletion(user, completion: { (user, error) -> () in if error == nil { // User signed up/logged in // Set up some views.. self.showEventsVC() } else { // User failed to sign up and log in println("Failed to sign up and log in user") println(error) } }) } } } func handleGoogleLogin(notification: NSNotification) { loginToParseWithUserInfo(notification.userInfo!) } func showEventsVC() { let scence = "MenuViewController" let vc = storyboard.instantiateViewControllerWithIdentifier(scence) as! UIViewController window?.rootViewController = vc } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { println("redirect to url: \(url)") return GPPURLHandler.handleURL(url, sourceApplication: sourceApplication, annotation: annotation) } }
apache-2.0
criticalmaps/criticalmaps-ios
CriticalMapsKit/Tests/TwitterFeedFeatureTests/TwitterFeedViewStateTests.swift
1
951
import Foundation import SharedModels import TwitterFeedFeature import XCTest final class TwitterFeedViewStateTests: XCTestCase { func test_setShouldDisplayPlaceholder() { var feedState = TwitterFeedFeature.State(tweets: []) feedState.twitterFeedIsLoading = true let viewState = TwitterFeedView.TwitterFeedViewState(feedState) XCTAssertTrue(viewState.displayPlaceholder) } func test_setShouldDisplayPlaceholder2() { var feedState = TwitterFeedFeature.State( tweets: .init(uniqueElements: [ .init( id: "1", text: "", createdAt: .distantFuture, user: .init( name: "TwitterBiker", screenName: "🐥", profileImageUrl: "" ) ) ]) ) feedState.twitterFeedIsLoading = false let viewState = TwitterFeedView.TwitterFeedViewState(feedState) XCTAssertFalse(viewState.displayPlaceholder) } }
mit
ShenghaiWang/FolioReaderKit
Source/EPUBCore/FRSpine.swift
3
973
// // FRSpine.swift // FolioReaderKit // // Created by Heberti Almeida on 06/05/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit struct Spine { var linear: Bool! var resource: FRResource! init(resource: FRResource, linear: Bool = true) { self.resource = resource self.linear = linear } } class FRSpine: NSObject { var pageProgressionDirection: String? var spineReferences = [Spine]() var isRtl: Bool { if let pageProgressionDirection = pageProgressionDirection , pageProgressionDirection == "rtl" { return true } return false } func nextChapter(_ href: String) -> FRResource? { var found = false; for item in spineReferences { if(found){ return item.resource } if(item.resource.href == href) { found = true } } return nil } }
bsd-3-clause
bannzai/xcp
xcp/XCP/XCProject.swift
1
11595
// // // XCProject.swift // xcp // // Created by kingkong999yhirose on 2016/09/20. // Copyright © 2016年 kingkong999yhirose. All rights reserved. // import Foundation open class XCProject { public typealias JSON = [String: Any] public typealias KeyAndValue = [(key: String, value: Any)] open let projectName: String open let fullJson: JSON open let allPBX = AllPBX() open let project: PBX.Project open let pbxUrl: URL open fileprivate(set) var environments: [String: String] = [:] public init(for pbxUrl: URL) throws { guard let propertyList = try? Data(contentsOf: pbxUrl) else { throw XCProjectError.notExistsProjectFile } var format: PropertyListSerialization.PropertyListFormat = PropertyListSerialization.PropertyListFormat.binary let properties = try PropertyListSerialization.propertyList(from: propertyList, options: PropertyListSerialization.MutabilityOptions(), format: &format) guard let json = properties as? JSON else { throw XCProjectError.wrongFormatFile } func generateObjects(with objectsJson: [String: JSON], allPBX: AllPBX) -> [PBX.Object] { return objectsJson .flatMap { (hashId, objectDictionary) in guard let isa = objectDictionary["isa"] as? String else { fatalError( assertionMessage(description: "not exists isa key: \(hashId), value: \(objectDictionary)", "you should check for project.pbxproj that is correct." ) ) } let pbxType = ObjectType.type(with: isa) let pbxObject = pbxType.init( id: hashId, dictionary: objectDictionary, isa: isa, allPBX: allPBX ) allPBX.dictionary[hashId] = pbxObject return pbxObject } } func generateProject(with objectsJson: [String: JSON], allPBX: AllPBX) -> PBX.Project { guard let id = json["rootObject"] as? String, let projectJson = objectsJson[id] else { fatalError( assertionMessage(description: "unexpected for json: \(json)", "and objectsJson: \(objectsJson)" ) ) } return PBX.Project( id: id, dictionary: projectJson, isa: ObjectType.PBXProject.rawValue, allPBX: allPBX ) } self.pbxUrl = pbxUrl guard let projectName = pbxUrl.pathComponents[pbxUrl.pathComponents.count - 2].components(separatedBy: ".").first else { fatalError("No Xcode project found, please specify one") } self.projectName = projectName fullJson = json let objectsJson = json["objects"] as! [String: JSON] generateObjects(with: objectsJson, allPBX: allPBX) project = generateProject(with: objectsJson, allPBX: allPBX) allPBX.createFullFilePaths(with: project) } // MARK: - enviroment open func append(with enviroment: [String: String]) { environments += enviroment } open func isExists(for environment: Environment) -> Bool { return environments[environment.rawValue] != nil } fileprivate func environment(for key: String) -> Environment { guard let value = environments[key], let environment = Environment(rawValue: value) else { fatalError( assertionMessage(description: "unknown key: \(key)", "process environments: \(environments)" ) ) } return environment } fileprivate func url(from environment: Environment) -> URL { guard let path = environments[environment.rawValue] else { fatalError(assertionMessage(description: "can not cast environment: \(environment)")) } return URL(fileURLWithPath: path) } open func path(from component: PathComponent) -> URL { switch component { case .simple(let fullPath): return URL(fileURLWithPath: fullPath) case .environmentPath(let environtment, let relativePath): let _url = url(from: environtment) .appendingPathComponent(relativePath) return _url } } } extension XCProject { private func generateHashId() -> String { let all = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".characters.map { String($0) } var result: String = "" for _ in 0..<24 { result += all[Int(arc4random_uniform(UInt32(all.count)))] } return result } public func appendFilePath( with projectRootPath: String, filePath: String, targetName: String ) { let pathComponents = filePath.components(separatedBy: "/").filter { !$0.isEmpty } let groupPathNames = Array(pathComponents.dropLast()) guard let fileName = pathComponents.last else { fatalError(assertionMessage(description: "unexpected get file name for append")) } let fileRefId = generateHashId() let fileRef: PBX.FileReference do { // file ref let isa = ObjectType.PBXFileReference.rawValue let json: XCProject.JSON = [ "isa": isa, "fileEncoding": 4, "lastKnownFileType": LastKnownFileType(fileName: fileName).value, "path": fileName, "sourceTree": "<group>" ] fileRef = PBX.FileReference( id: fileRefId, dictionary: json, isa: isa, allPBX: allPBX ) allPBX.dictionary[fileRefId] = fileRef } do { // groups allPBX.createFullFilePaths(with: project) let groupEachPaths = allPBX .dictionary .values .flatMap { $0 as? PBX.Group } .flatMap { group -> (PBX.Group, String) in let path = (projectRootPath + group.fullPath) .components(separatedBy: "/") .filter { !$0.isEmpty } .joined(separator: "/") return (group, path) } func appendGroupIfNeeded(with childId: String, groupPathNames: [String]) { if groupPathNames.isEmpty { return } let groupPath = groupPathNames.joined(separator: "/") let alreadyExistsGroup = groupEachPaths .filter { (group, path) -> Bool in return path == groupPath } .first if let group = alreadyExistsGroup?.0 { let reference: PBX.Reference = allPBX.dictionary[childId] as! PBX.Reference group.children.append(reference) return } else { guard let pathName = groupPathNames.last else { fatalError("unexpected not exists last value") } let isa = ObjectType.PBXGroup.rawValue let json: XCProject.JSON = [ "isa": isa, "children": [ childId ], "path": pathName, "sourceTree": "<group>" ] let uuid = generateHashId() let group = PBX.Group( id: uuid, dictionary: json, isa: isa, allPBX: allPBX ) allPBX.dictionary[uuid] = group appendGroupIfNeeded(with: uuid, groupPathNames: Array(groupPathNames.dropLast())) } } appendGroupIfNeeded(with: fileRefId, groupPathNames: groupPathNames) } let buildFileId = generateHashId() func buildFile() -> PBX.BuildFile { // build file let isa = ObjectType.PBXBuildFile.rawValue let json: XCProject.JSON = [ "isa": isa, "fileRef": fileRefId, ] let buildFile = PBX.BuildFile( id: buildFileId, dictionary: json, isa: isa, allPBX: allPBX ) allPBX.dictionary[buildFileId] = buildFile return buildFile } let buildedFile = buildFile() let sourceBuildPhaseId = generateHashId() func sourceBuildPhase() { // source build phase guard let target = allPBX .dictionary .values .flatMap ({ $0 as? PBX.NativeTarget }) .filter ({ $0.name == targetName }) .first else { fatalError(assertionMessage(description: "Unexpected target name \(targetName)")) } let sourcesBuildPhase = target.buildPhases.flatMap { $0 as? PBX.SourcesBuildPhase }.first guard sourcesBuildPhase == nil else { // already exists sourcesBuildPhase?.files.append(buildedFile) return } let isa = ObjectType.PBXSourcesBuildPhase.rawValue let json: XCProject.JSON = [ "isa": isa, "buildActionMask": Int32.max, "files": [ buildFileId ], "runOnlyForDeploymentPostprocessing": 0 ] allPBX.dictionary[sourceBuildPhaseId] = PBX.SourcesBuildPhase( id: sourceBuildPhaseId, dictionary: json, isa: isa, allPBX: allPBX ) } sourceBuildPhase() } } extension XCProject { func write() throws { let serialization = XCPSerialization(project: self) let writeContent = try serialization.generateWriteContent() func w(with code: String, fileURL: URL) throws { try code.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8) } let writeUrl = pbxUrl try w(with: writeContent, fileURL: writeUrl) } }
mit
yrchen/edx-app-ios
Source/ProfileImageView.swift
1
2611
// // ProfileImageView.swift // edX // // Created by Michael Katz on 9/17/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit @IBDesignable class ProfileImageView: UIImageView { var borderWidth: CGFloat = 1.0 var borderColor: UIColor? private func setup() { var borderStyle = OEXStyles.sharedStyles().profileImageViewBorder(borderWidth) if borderColor != nil { borderStyle = BorderStyle(cornerRadius: borderStyle.cornerRadius, width: borderStyle.width, color: borderColor) } applyBorderStyle(borderStyle) backgroundColor = OEXStyles.sharedStyles().profileImageBorderColor() } convenience init() { self.init(frame: CGRectZero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init (frame: CGRect) { super.init(frame: frame) let bundle = NSBundle(forClass: self.dynamicType) image = UIImage(named: "avatarPlaceholder", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) setup() } override func layoutSubviews() { super.layoutSubviews() setup() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() let bundle = NSBundle(forClass: self.dynamicType) image = UIImage(named: "avatarPlaceholder", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) } func blurimate() -> Removable { let blur = UIBlurEffect(style: .Light) let blurView = UIVisualEffectView(effect: blur) let vib = UIVibrancyEffect(forBlurEffect: blur) let vibView = UIVisualEffectView(effect: vib) let spinner = SpinnerView(size: .Medium, color: .White) vibView.contentView.addSubview(spinner) spinner.snp_makeConstraints {make in make.center.equalTo(spinner.superview!) } spinner.startAnimating() insertSubview(blurView, atIndex: 0) blurView.contentView.addSubview(vibView) vibView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(vibView.superview!) } blurView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self) } return BlockRemovable() { UIView.animateWithDuration(0.4, animations: { spinner.stopAnimating() }) { _ in blurView.removeFromSuperview() } } } }
apache-2.0
janslow/qlab-from-csv
QLab From CSV/QLabFromCsv/cues/Cue.swift
1
329
// // cue.swift // QLab From CSV // // Created by Jay Anslow on 20/12/2014. // Copyright (c) 2014 Jay Anslow. All rights reserved. // import Foundation @objc public protocol Cue { var cueNumber : String? { get } var cueName : String { get } var description : String { get } var preWait : Float { get set } }
mit
rdm0423/Hydrate
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift
3
95620
// // IQKeyboardManager.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-15 Iftekhar Qurashi. // // 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 CoreGraphics import UIKit ///--------------------- /// MARK: IQToolbar tags ///--------------------- /** Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html */ public class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate { /** Default tag for toolbar with Done button -1002. */ private static let kIQDoneButtonToolbarTag = -1002 /** Default tag for toolbar with Previous/Next buttons -1005. */ private static let kIQPreviousNextButtonToolbarTag = -1005 ///--------------------------- /// MARK: UIKeyboard handling ///--------------------------- /** Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method). */ public var enable = false { didSet { //If not enable, enable it. if enable == true && oldValue == false { //If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard. if _kbShowNotification != nil { keyboardWillShow(_kbShowNotification) } _IQShowLog("enabled") } else if enable == false && oldValue == true { //If not disable, desable it. keyboardWillHide(nil) _IQShowLog("disabled") } } } /** To set keyboard distance from textField. can't be less than zero. Default is 10.0. */ public var keyboardDistanceFromTextField: CGFloat { set { _privateKeyboardDistanceFromTextField = max(0, newValue) _IQShowLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)") } get { return _privateKeyboardDistanceFromTextField } } /** Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES. */ public var preventShowingBottomBlankSpace = true /** Returns the default singleton instance. */ public class func sharedManager() -> IQKeyboardManager { struct Static { //Singleton instance. Initializing keyboard manger. static let kbManager = IQKeyboardManager() } /** @return Returns the default singleton instance. */ return Static.kbManager } ///------------------------- /// MARK: IQToolbar handling ///------------------------- /** Automatic add the IQToolbar functionality. Default is YES. */ public var enableAutoToolbar = true { didSet { enableAutoToolbar ?addToolbarIfRequired():removeToolbarIfRequired() let enableToolbar = enableAutoToolbar ? "Yes" : "NO" _IQShowLog("enableAutoToolbar: \(enableToolbar)") } } /** AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews. */ public var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.BySubviews /** If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO. */ public var shouldToolbarUsesTextFieldTintColor = false /** If YES, then it add the textField's placeholder text on IQToolbar. Default is YES. */ public var shouldShowTextFieldPlaceholder = true /** Placeholder Font. Default is nil. */ public var placeholderFont: UIFont? ///-------------------------- /// MARK: UITextView handling ///-------------------------- /** Adjust textView's frame when it is too big in height. Default is NO. */ public var canAdjustTextView = false /** Adjust textView's contentInset to fix a bug. for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string Default is YES. */ public var shouldFixTextViewClip = true ///--------------------------------------- /// MARK: UIKeyboard appearance overriding ///--------------------------------------- /** Override the keyboardAppearance for all textField/textView. Default is NO. */ public var overrideKeyboardAppearance = false /** If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property. */ public var keyboardAppearance = UIKeyboardAppearance.Default ///----------------------------------------------------------- /// MARK: UITextField/UITextView Next/Previous/Resign handling ///----------------------------------------------------------- /** Resigns Keyboard on touching outside of UITextField/View. Default is NO. */ public var shouldResignOnTouchOutside = false { didSet { _tapGesture.enabled = shouldResignOnTouchOutside let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO" _IQShowLog("shouldResignOnTouchOutside: \(shouldResign)") } } /** Resigns currently first responder field. */ public func resignFirstResponder()-> Bool { if let textFieldRetain = _textFieldView { //Resigning first responder let isResignFirstResponder = textFieldRetain.resignFirstResponder() // If it refuses then becoming it as first responder again. (Bug ID: #96) if isResignFirstResponder == false { //If it refuses to resign then becoming it first responder again for getting notifications callback. textFieldRetain.becomeFirstResponder() _IQShowLog("Refuses to resign first responder: \(_textFieldView?._IQDescription())") } return isResignFirstResponder } return false } /** Returns YES if can navigate to previous responder textField/textView, otherwise NO. */ public var canGoPrevious: Bool { get { //Getting all responder view's. if let textFields = responderViews() { if let textFieldRetain = _textFieldView { //Getting index of current textField. if let index = textFields.indexOf(textFieldRetain) { //If it is not first textField. then it's previous object canBecomeFirstResponder. if index > 0 { return true } } } } return false } } /** Returns YES if can navigate to next responder textField/textView, otherwise NO. */ public var canGoNext: Bool { get { //Getting all responder view's. if let textFields = responderViews() { if let textFieldRetain = _textFieldView { //Getting index of current textField. if let index = textFields.indexOf(textFieldRetain) { //If it is not first textField. then it's previous object canBecomeFirstResponder. if index < textFields.count-1 { return true } } } } return false } } /** Navigate to previous responder textField/textView. */ public func goPrevious()-> Bool { //Getting all responder view's. if let textFieldRetain = _textFieldView { if let textFields = responderViews() { //Getting index of current textField. if let index = textFields.indexOf(textFieldRetain) { //If it is not first textField. then it's previous object becomeFirstResponder. if index > 0 { let nextTextField = textFields[index-1] let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if isAcceptAsFirstResponder == false { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() _IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())") } return isAcceptAsFirstResponder } } } } return false } /** Navigate to next responder textField/textView. */ public func goNext()-> Bool { //Getting all responder view's. if let textFieldRetain = _textFieldView { if let textFields = responderViews() { //Getting index of current textField. if let index = textFields.indexOf(textFieldRetain) { //If it is not last textField. then it's next object becomeFirstResponder. if index < textFields.count-1 { let nextTextField = textFields[index+1] let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if isAcceptAsFirstResponder == false { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() _IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())") } return isAcceptAsFirstResponder } } } } return false } /** previousAction. */ internal func previousAction (segmentedControl : AnyObject?) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.currentDevice().playInputClick() } if canGoPrevious == true { if let textFieldRetain = _textFieldView { let isAcceptAsFirstResponder = goPrevious() if isAcceptAsFirstResponder && textFieldRetain.previousInvocation.target != nil && textFieldRetain.previousInvocation.selector != nil { UIApplication.sharedApplication().sendAction(textFieldRetain.previousInvocation.selector!, to: textFieldRetain.previousInvocation.target, from: textFieldRetain, forEvent: UIEvent()) } } } } /** nextAction. */ internal func nextAction (segmentedControl : AnyObject?) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.currentDevice().playInputClick() } if canGoNext == true { if let textFieldRetain = _textFieldView { let isAcceptAsFirstResponder = goNext() if isAcceptAsFirstResponder && textFieldRetain.nextInvocation.target != nil && textFieldRetain.nextInvocation.selector != nil { UIApplication.sharedApplication().sendAction(textFieldRetain.nextInvocation.selector!, to: textFieldRetain.nextInvocation.target, from: textFieldRetain, forEvent: UIEvent()) } } } } /** doneAction. Resigning current textField. */ internal func doneAction (barButton : IQBarButtonItem?) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.currentDevice().playInputClick() } if let textFieldRetain = _textFieldView { //Resign textFieldView. let isResignedFirstResponder = resignFirstResponder() if isResignedFirstResponder && textFieldRetain.doneInvocation.target != nil && textFieldRetain.doneInvocation.selector != nil{ UIApplication.sharedApplication().sendAction(textFieldRetain.doneInvocation.selector!, to: textFieldRetain.doneInvocation.target, from: textFieldRetain, forEvent: UIEvent()) } } } /** Resigning on tap gesture. (Enhancement ID: #14)*/ internal func tapRecognized(gesture: UITapGestureRecognizer) { if gesture.state == UIGestureRecognizerState.Ended { //Resigning currently responder textField. resignFirstResponder() } } /** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */ public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } /** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */ public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { // Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145) return (touch.view is UIControl || touch.view is UINavigationBar) ? false : true } ///---------------------------- /// MARK: UIScrollView handling ///---------------------------- /** Restore scrollViewContentOffset when resigning from scrollView. Default is NO. */ public var shouldRestoreScrollViewContentOffset = false ///----------------------- /// MARK: UISound handling ///----------------------- /** If YES, then it plays inputClick sound on next/previous/done click. */ public var shouldPlayInputClicks = false ///--------------------------- /// MARK: UIAnimation handling ///--------------------------- /** If YES, then uses keyboard default animation curve style to move view, otherwise uses UIViewAnimationOptionCurveEaseInOut animation style. Default is YES. @warning Sometimes strange animations may be produced if uses default curve style animation in iOS 7 and changing the textFields very frequently. */ public var shouldAdoptDefaultKeyboardAnimation = true /** If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view. */ public var layoutIfNeededOnUpdate = false ///------------------------------------ /// MARK: Class Level disabling methods ///------------------------------------ /** Disable adjusting view in disabledClass @param disabledClass Class in which library should not adjust view to show textField. */ public func disableInViewControllerClass(disabledClass : AnyClass) { _disabledClasses.insert(NSStringFromClass(disabledClass)) } /** Re-enable adjusting textField in disabledClass @param disabledClass Class in which library should re-enable adjust view to show textField. */ public func removeDisableInViewControllerClass(disabledClass : AnyClass) { _disabledClasses.remove(NSStringFromClass(disabledClass)) } /** Returns YES if ViewController class is disabled for library, otherwise returns NO. @param disabledClass Class which is to check for it's disability. */ public func isDisableInViewControllerClass(disabledClass : AnyClass) -> Bool { return _disabledClasses.contains(NSStringFromClass(disabledClass)) } /** Disable automatic toolbar creation in in toolbarDisabledClass @param toolbarDisabledClass Class in which library should not add toolbar over textField. */ public func disableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) { _disabledToolbarClasses.insert(NSStringFromClass(toolbarDisabledClass)) } /** Re-enable automatic toolbar creation in in toolbarDisabledClass @param toolbarDisabledClass Class in which library should re-enable automatic toolbar creation over textField. */ public func removeDisableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) { _disabledToolbarClasses.remove(NSStringFromClass(toolbarDisabledClass)) } /** Returns YES if toolbar is disabled in ViewController class, otherwise returns NO. @param toolbarDisabledClass Class which is to check for toolbar disability. */ public func isDisableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) -> Bool { return _disabledToolbarClasses.contains(NSStringFromClass(toolbarDisabledClass)) } /** Consider provided customView class as superView of all inner textField for calculating next/previous button logic. @param toolbarPreviousNextConsideredClass Custom UIView subclass Class in which library should consider all inner textField as siblings and add next/previous accordingly. */ public func considerToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) { _toolbarPreviousNextConsideredClass.insert(NSStringFromClass(toolbarPreviousNextConsideredClass)) } /** Remove Consideration for provided customView class as superView of all inner textField for calculating next/previous button logic. @param toolbarPreviousNextConsideredClass Custom UIView subclass Class in which library should remove consideration for all inner textField as superView. */ public func removeConsiderToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) { _toolbarPreviousNextConsideredClass.remove(NSStringFromClass(toolbarPreviousNextConsideredClass)) } /** Returns YES if inner hierarchy is considered for previous/next in class, otherwise returns NO. @param toolbarPreviousNextConsideredClass Class which is to check for previous next consideration */ public func isConsiderToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) -> Bool { return _toolbarPreviousNextConsideredClass.contains(NSStringFromClass(toolbarPreviousNextConsideredClass)) } /**************************************************************************************/ ///------------------------ /// MARK: Private variables ///------------------------ /*******************************************/ /** To save UITextField/UITextView object voa textField/textView notifications. */ private weak var _textFieldView: UIView? /** used with canAdjustTextView boolean. */ private var _textFieldViewIntialFrame = CGRectZero /** To save rootViewController.view.frame. */ private var _topViewBeginRect = CGRectZero /** To save rootViewController */ private weak var _rootViewController: UIViewController? /** To save topBottomLayoutConstraint original constant */ private var _layoutGuideConstraintInitialConstant: CGFloat = 0.25 /*******************************************/ /** Variable to save lastScrollView that was scrolled. */ private weak var _lastScrollView: UIScrollView? /** LastScrollView's initial contentOffset. */ private var _startingContentOffset = CGPointZero /** LastScrollView's initial scrollIndicatorInsets. */ private var _startingScrollIndicatorInsets = UIEdgeInsetsZero /** LastScrollView's initial contentInsets. */ private var _startingContentInsets = UIEdgeInsetsZero /*******************************************/ /** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */ private var _kbShowNotification: NSNotification? /** To save keyboard size. */ private var _kbSize = CGSizeZero /** To save keyboard animation duration. */ private var _animationDuration = 0.25 /** To mimic the keyboard animation */ private var _animationCurve = UIViewAnimationOptions.CurveEaseOut /*******************************************/ /** TapGesture to resign keyboard on view's touch. */ private var _tapGesture: UITapGestureRecognizer! /*******************************************/ /** Default toolbar tintColor to be used within the project. Default is black. */ private var _defaultToolbarTintColor = UIColor.blackColor() /*******************************************/ /** Set of restricted classes for library */ private var _disabledClasses = Set<String>() /** Set of restricted classes for adding toolbar */ private var _disabledToolbarClasses = Set<String>() /** Set of permitted classes to add all inner textField as siblings */ private var _toolbarPreviousNextConsideredClass = Set<String>() /*******************************************/ private struct flags { /** used with canAdjustTextView to detect a textFieldView frame is changes or not. (Bug ID: #92)*/ var isTextFieldViewFrameChanged = false /** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */ var isKeyboardShowing = false } /** Private flags to use within the project */ private var _keyboardManagerFlags = flags(isTextFieldViewFrameChanged: false, isKeyboardShowing: false) /** To use with keyboardDistanceFromTextField. */ private var _privateKeyboardDistanceFromTextField: CGFloat = 10.0 /**************************************************************************************/ ///-------------------------------------- /// MARK: Initialization/Deinitialization ///-------------------------------------- /* Singleton Object Initialization. */ override init() { super.init() // Registering for keyboard notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHide:", name: UIKeyboardDidHideNotification, object: nil) // Registering for textField notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextFieldTextDidBeginEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextFieldTextDidEndEditingNotification, object: nil) // Registering for textView notification. NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextViewTextDidBeginEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextViewTextDidEndEditingNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidChange:", name: UITextViewTextDidChangeNotification, object: nil) // Registering for orientation changes notification NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeStatusBarOrientation:", name: UIApplicationWillChangeStatusBarOrientationNotification, object: nil) //Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14) _tapGesture = UITapGestureRecognizer(target: self, action: "tapRecognized:") _tapGesture.delegate = self _tapGesture.enabled = shouldResignOnTouchOutside disableInViewControllerClass(UITableViewController) considerToolbarPreviousNextInViewClass(UITableView) considerToolbarPreviousNextInViewClass(UICollectionView) } /** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */ /** It doesn't work on Swift 1.2 */ // override class func load() { // super.load() // // //Enabling IQKeyboardManager. // IQKeyboardManager.sharedManager().enable = true // } deinit { // Disable the keyboard manager. enable = false //Removing notification observers on dealloc. NSNotificationCenter.defaultCenter().removeObserver(self) } /** Getting keyWindow. */ private func keyWindow() -> UIWindow? { if let keyWindow = _textFieldView?.window { return keyWindow } else { struct Static { /** @abstract Save keyWindow object for reuse. @discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */ static var keyWindow : UIWindow? } /* (Bug ID: #23, #25, #73) */ let originalKeyWindow = UIApplication.sharedApplication().keyWindow //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow. if originalKeyWindow != nil && (Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) { Static.keyWindow = originalKeyWindow } //Return KeyWindow return Static.keyWindow } } ///----------------------- /// MARK: Helper Functions ///----------------------- /* Helper function to manipulate RootViewController's frame with animation. */ private func setRootViewFrame(var frame: CGRect) { // Getting topMost ViewController. var controller = _textFieldView?.topMostController() if controller == nil { controller = keyWindow()?.topMostController() } if let unwrappedController = controller { //frame size needs to be adjusted on iOS8 due to orientation structure changes. if #available(iOS 8.0, *) { frame.size = unwrappedController.view.frame.size } //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in // Setting it's new frame unwrappedController.view.frame = frame self._IQShowLog("Set \(controller?._IQDescription()) frame to : \(frame)") //Animating content if needed (Bug ID: #204) if self.layoutIfNeededOnUpdate == true { //Animating content (Bug ID: #160) unwrappedController.view.setNeedsLayout() unwrappedController.view.layoutIfNeeded() } }) { (animated:Bool) -> Void in} } else { // If can't get rootViewController then printing warning to user. _IQShowLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager") } } /* Adjusting RootViewController's frame according to interface orientation. */ private func adjustFrame() { // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) if _textFieldView == nil { return } let textFieldView = _textFieldView! _IQShowLog("****** \(__FUNCTION__) %@ started ******") // Boolean to know keyboard is showing/hiding _keyboardManagerFlags.isKeyboardShowing = true // Getting KeyWindow object. let optionalWindow = keyWindow() // Getting RootViewController. (Bug ID: #1, #4) var optionalRootController = _textFieldView?.topMostController() if optionalRootController == nil { optionalRootController = keyWindow()?.topMostController() } // Converting Rectangle according to window bounds. let optionalTextFieldViewRect = textFieldView.superview?.convertRect(textFieldView.frame, toView: optionalWindow) if optionalRootController == nil || optionalWindow == nil || optionalTextFieldViewRect == nil { return } let rootController = optionalRootController! let window = optionalWindow! let textFieldViewRect = optionalTextFieldViewRect! //If it's iOS8 then we should do calculations according to portrait orientations. // (Bug ID: #64, #66) let interfaceOrientation : UIInterfaceOrientation if #available(iOS 8.0, *) { interfaceOrientation = UIInterfaceOrientation.Portrait } else { interfaceOrientation = rootController.interfaceOrientation } // Getting RootViewRect. var rootViewRect = rootController.view.frame //Getting statusBarFrame var topLayoutGuide : CGFloat = 0 //Maintain keyboardDistanceFromTextField let newKeyboardDistanceFromTextField = (textFieldView.keyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : textFieldView.keyboardDistanceFromTextField var kbSize = _kbSize let statusBarFrame = UIApplication.sharedApplication().statusBarFrame // (Bug ID: #250) var layoutGuidePosition = IQLayoutGuidePosition.None if let viewController = textFieldView.viewController() { if let constraint = viewController.IQLayoutGuideConstraint { var layoutGuide : UILayoutSupport? if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } if let itemLayoutGuide : UILayoutSupport = layoutGuide { if (itemLayoutGuide === viewController.topLayoutGuide) //If topLayoutGuide constraint { layoutGuidePosition = .Top } else if (itemLayoutGuide === viewController.bottomLayoutGuide) //If bottomLayoutGuice constraint { layoutGuidePosition = .Bottom } } } } switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight: topLayoutGuide = CGRectGetWidth(statusBarFrame) kbSize.width += newKeyboardDistanceFromTextField case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown: topLayoutGuide = CGRectGetHeight(statusBarFrame) kbSize.height += newKeyboardDistanceFromTextField default: break } var move : CGFloat = 0.0 // Move positive = textField is hidden. // Move negative = textField is showing. // Checking if there is bottomLayoutGuide attached (Bug ID: #250) if layoutGuidePosition == .Bottom { // Calculating move position. switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: move = CGRectGetMaxX(textFieldViewRect)-(CGRectGetWidth(window.frame)-kbSize.width) case UIInterfaceOrientation.LandscapeRight: move = kbSize.width-CGRectGetMinX(textFieldViewRect) case UIInterfaceOrientation.Portrait: move = CGRectGetMaxY(textFieldViewRect)-(CGRectGetHeight(window.frame)-kbSize.height) case UIInterfaceOrientation.PortraitUpsideDown: move = kbSize.height-CGRectGetMinY(textFieldViewRect) default: break } } else { // Calculating move position. Common for both normal and special cases. switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: move = min(CGRectGetMinX(textFieldViewRect)-(topLayoutGuide+5), CGRectGetMaxX(textFieldViewRect)-(CGRectGetWidth(window.frame)-kbSize.width)) case UIInterfaceOrientation.LandscapeRight: move = min(CGRectGetWidth(window.frame)-CGRectGetMaxX(textFieldViewRect)-(topLayoutGuide+5), kbSize.width-CGRectGetMinX(textFieldViewRect)) case UIInterfaceOrientation.Portrait: move = min(CGRectGetMinY(textFieldViewRect)-(topLayoutGuide+5), CGRectGetMaxY(textFieldViewRect)-(CGRectGetHeight(window.frame)-kbSize.height)) case UIInterfaceOrientation.PortraitUpsideDown: move = min(CGRectGetHeight(window.frame)-CGRectGetMaxY(textFieldViewRect)-(topLayoutGuide+5), kbSize.height-CGRectGetMinY(textFieldViewRect)) default: break } } _IQShowLog("Need to move: \(move)") // Getting it's superScrollView. // (Enhancement ID: #21, #24) let superScrollView = textFieldView.superviewOfClassType(UIScrollView) as? UIScrollView //If there was a lastScrollView. // (Bug ID: #34) if let lastScrollView = _lastScrollView { //If we can't find current superScrollView, then setting lastScrollView to it's original form. if superScrollView == nil { _IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)") UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets }) { (animated:Bool) -> Void in } if shouldRestoreScrollViewContentOffset == true { lastScrollView.setContentOffset(_startingContentOffset, animated: true) } _startingContentInsets = UIEdgeInsetsZero _startingScrollIndicatorInsets = UIEdgeInsetsZero _startingContentOffset = CGPointZero _lastScrollView = nil } else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView. _IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)") UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets }) { (animated:Bool) -> Void in } if shouldRestoreScrollViewContentOffset == true { lastScrollView.setContentOffset(_startingContentOffset, animated: true) } _lastScrollView = superScrollView _startingContentInsets = superScrollView!.contentInset _startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets _startingContentOffset = superScrollView!.contentOffset _IQShowLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)") } //Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead } else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView. _lastScrollView = unwrappedSuperScrollView _startingContentInsets = unwrappedSuperScrollView.contentInset _startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets _startingContentOffset = unwrappedSuperScrollView.contentOffset _IQShowLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)") } // Special case for ScrollView. // If we found lastScrollView then setting it's contentOffset to show textField. if let lastScrollView = _lastScrollView { //Saving var lastView = textFieldView var superScrollView = _lastScrollView while let scrollView = superScrollView { //Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object. if move > 0 ? (move > (-scrollView.contentOffset.y - scrollView.contentInset.top)) : scrollView.contentOffset.y>0 { //Getting lastViewRect. if let lastViewRect = lastView.superview?.convertRect(lastView.frame, toView: scrollView) { //Calculating the expected Y offset from move and scrollView's contentOffset. var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move) //Rearranging the expected Y offset according to the view. shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69) //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //[superScrollView superviewOfClassType:[UIScrollView class]] == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.) //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92) if textFieldView is UITextView == true && scrollView.superviewOfClassType(UIScrollView) == nil && shouldOffsetY >= 0 { var maintainTopLayout : CGFloat = 0 if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame { maintainTopLayout = CGRectGetMaxY(navigationBarFrame) } maintainTopLayout += 10.0 //For good UI // Converting Rectangle according to window bounds. if let currentTextFieldViewRect = textFieldView.superview?.convertRect(textFieldView.frame, toView: window) { var expectedFixDistance = shouldOffsetY //Calculating expected fix distance which needs to be managed from navigation bar switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: expectedFixDistance = CGRectGetMinX(currentTextFieldViewRect) - maintainTopLayout case UIInterfaceOrientation.LandscapeRight: expectedFixDistance = (CGRectGetWidth(window.frame)-CGRectGetMaxX(currentTextFieldViewRect)) - maintainTopLayout case UIInterfaceOrientation.Portrait: expectedFixDistance = CGRectGetMinY(currentTextFieldViewRect) - maintainTopLayout case UIInterfaceOrientation.PortraitUpsideDown: expectedFixDistance = (CGRectGetHeight(window.frame)-CGRectGetMaxY(currentTextFieldViewRect)) - maintainTopLayout default: break } //Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance) //Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic. move = 0 } else { //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. move -= (shouldOffsetY-scrollView.contentOffset.y) } } else { //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. move -= (shouldOffsetY-scrollView.contentOffset.y) } //Getting problem while using `setContentOffset:animated:`, So I used animation API. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in self._IQShowLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset") self._IQShowLog("Remaining Move: \(move)") scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, shouldOffsetY) }) { (animated:Bool) -> Void in } } // Getting next lastView & superScrollView. lastView = scrollView superScrollView = lastView.superviewOfClassType(UIScrollView) as? UIScrollView } else { break } } //Updating contentInset if let lastScrollViewRect = lastScrollView.superview?.convertRect(lastScrollView.frame, toView: window) { var bottom : CGFloat = 0.0 switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: bottom = kbSize.width-(CGRectGetWidth(window.frame)-CGRectGetMaxX(lastScrollViewRect)) case UIInterfaceOrientation.LandscapeRight: bottom = kbSize.width-CGRectGetMinX(lastScrollViewRect) case UIInterfaceOrientation.Portrait: bottom = kbSize.height-(CGRectGetHeight(window.frame)-CGRectGetMaxY(lastScrollViewRect)) case UIInterfaceOrientation.PortraitUpsideDown: bottom = kbSize.height-CGRectGetMinY(lastScrollViewRect) default: break } // Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view. var movedInsets = lastScrollView.contentInset movedInsets.bottom = max(_startingContentInsets.bottom, bottom) _IQShowLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)") //Getting problem while using `setContentOffset:animated:`, So I used animation API. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = movedInsets var newInset = lastScrollView.scrollIndicatorInsets newInset.bottom = movedInsets.bottom - 10 lastScrollView.scrollIndicatorInsets = newInset }) { (animated:Bool) -> Void in } //Maintaining contentSize if lastScrollView.contentSize.height < lastScrollView.frame.size.height { var contentSize = lastScrollView.contentSize contentSize.height = lastScrollView.frame.size.height lastScrollView.contentSize = contentSize } _IQShowLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)") } } //Going ahead. No else if. if layoutGuidePosition == .Top { let constraint = textFieldView.viewController()!.IQLayoutGuideConstraint! let constant = min(_layoutGuideConstraintInitialConstant, constraint.constant-move) UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in constraint.constant = constant self._rootViewController?.view.setNeedsLayout() self._rootViewController?.view.layoutIfNeeded() }, completion: { (finished) -> Void in }) } else if layoutGuidePosition == .Bottom { let constraint = textFieldView.viewController()!.IQLayoutGuideConstraint! let constant = max(_layoutGuideConstraintInitialConstant, constraint.constant+move) UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in constraint.constant = constant self._rootViewController?.view.setNeedsLayout() self._rootViewController?.view.layoutIfNeeded() }, completion: { (finished) -> Void in }) } else { //Special case for UITextView(Readjusting the move variable when textView hight is too big to fit on screen) //_canAdjustTextView If we have permission to adjust the textView, then let's do it on behalf of user (Enhancement ID: #15) //_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView. //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //_isTextFieldViewFrameChanged If frame is not change by library in past (Bug ID: #92) if canAdjustTextView == true && _lastScrollView == nil && textFieldView is UITextView == true && _keyboardManagerFlags.isTextFieldViewFrameChanged == false { var textViewHeight = CGRectGetHeight(textFieldView.frame) switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight: textViewHeight = min(textViewHeight, (CGRectGetWidth(window.frame)-kbSize.width-(topLayoutGuide+5))) case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown: textViewHeight = min(textViewHeight, (CGRectGetHeight(window.frame)-kbSize.height-(topLayoutGuide+5))) default: break } UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in self._IQShowLog("\(textFieldView._IQDescription()) Old Frame : \(textFieldView.frame)") var textFieldViewRect = textFieldView.frame textFieldViewRect.size.height = textViewHeight textFieldView.frame = textFieldViewRect self._keyboardManagerFlags.isTextFieldViewFrameChanged = true self._IQShowLog("\(textFieldView._IQDescription()) New Frame : \(textFieldView.frame)") }, completion: { (finished) -> Void in }) } // Special case for iPad modalPresentationStyle. if rootController.modalPresentationStyle == UIModalPresentationStyle.FormSheet || rootController.modalPresentationStyle == UIModalPresentationStyle.PageSheet { _IQShowLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)") // +Positive or zero. if move >= 0 { // We should only manipulate y. rootViewRect.origin.y -= move // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if preventShowingBottomBlankSpace == true { var minimumY: CGFloat = 0 switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft, UIInterfaceOrientation.LandscapeRight: minimumY = CGRectGetWidth(window.frame)-rootViewRect.size.height-topLayoutGuide-(kbSize.width-newKeyboardDistanceFromTextField) case UIInterfaceOrientation.Portrait, UIInterfaceOrientation.PortraitUpsideDown: minimumY = (CGRectGetHeight(window.frame)-rootViewRect.size.height-topLayoutGuide)/2-(kbSize.height-newKeyboardDistanceFromTextField) default: break } rootViewRect.origin.y = max(CGRectGetMinY(rootViewRect), minimumY) } _IQShowLog("Moving Upward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) } else { // -Negative // Calculating disturbed distance. Pull Request #3 let disturbDistance = CGRectGetMinY(rootViewRect)-CGRectGetMinY(_topViewBeginRect) // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if disturbDistance < 0 { // We should only manipulate y. rootViewRect.origin.y -= max(move, disturbDistance) _IQShowLog("Moving Downward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) } } } else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case) // +Positive or zero. if move >= 0 { switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: rootViewRect.origin.x -= move case UIInterfaceOrientation.LandscapeRight: rootViewRect.origin.x += move case UIInterfaceOrientation.Portrait: rootViewRect.origin.y -= move case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.origin.y += move default: break } // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if preventShowingBottomBlankSpace == true { switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: rootViewRect.origin.x = max(rootViewRect.origin.x, min(0, -kbSize.width+newKeyboardDistanceFromTextField)) case UIInterfaceOrientation.LandscapeRight: rootViewRect.origin.x = min(rootViewRect.origin.x, +kbSize.width-newKeyboardDistanceFromTextField) case UIInterfaceOrientation.Portrait: rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -kbSize.height+newKeyboardDistanceFromTextField)) case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.origin.y = min(rootViewRect.origin.y, +kbSize.height-newKeyboardDistanceFromTextField) default: break } } _IQShowLog("Moving Upward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) } else { // -Negative var disturbDistance : CGFloat = 0 switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: disturbDistance = CGRectGetMinX(rootViewRect)-CGRectGetMinX(_topViewBeginRect) case UIInterfaceOrientation.LandscapeRight: disturbDistance = CGRectGetMinX(_topViewBeginRect)-CGRectGetMinX(rootViewRect) case UIInterfaceOrientation.Portrait: disturbDistance = CGRectGetMinY(rootViewRect)-CGRectGetMinY(_topViewBeginRect) case UIInterfaceOrientation.PortraitUpsideDown: disturbDistance = CGRectGetMinY(_topViewBeginRect)-CGRectGetMinY(rootViewRect) default: break } // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if disturbDistance < 0 { switch interfaceOrientation { case UIInterfaceOrientation.LandscapeLeft: rootViewRect.origin.x -= max(move, disturbDistance) case UIInterfaceOrientation.LandscapeRight: rootViewRect.origin.x += max(move, disturbDistance) case UIInterfaceOrientation.Portrait: rootViewRect.origin.y -= max(move, disturbDistance) case UIInterfaceOrientation.PortraitUpsideDown: rootViewRect.origin.y += max(move, disturbDistance) default: break } _IQShowLog("Moving Downward") // Setting adjusted rootViewRect // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) } } } } _IQShowLog("****** \(__FUNCTION__) ended ******") } ///------------------------------- /// MARK: UIKeyboard Notifications ///------------------------------- /* UIKeyboardWillShowNotification. */ internal func keyboardWillShow(notification : NSNotification?) -> Void { _kbShowNotification = notification if enable == false { return } _IQShowLog("****** \(__FUNCTION__) started ******") //Due to orientation callback we need to resave it's original frame. // (Bug ID: #46) //Added _isTextFieldViewFrameChanged check. Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed. (Bug ID: #92) if _keyboardManagerFlags.isTextFieldViewFrameChanged == false && _textFieldView != nil { if let textFieldView = _textFieldView { _textFieldViewIntialFrame = textFieldView.frame _IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)") } } // (Bug ID: #5) if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == true { // keyboard is not showing(At the beginning only). We should save rootViewRect. _rootViewController = _textFieldView?.topMostController() if _rootViewController == nil { _rootViewController = keyWindow()?.topMostController() } if let unwrappedRootController = _rootViewController { _topViewBeginRect = unwrappedRootController.view.frame _IQShowLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)") } else { _topViewBeginRect = CGRectZero } } let oldKBSize = _kbSize if let info = notification?.userInfo { if shouldAdoptDefaultKeyboardAnimation { // Getting keyboard animation. if let curve = info[UIKeyboardAnimationCurveUserInfoKey]?.unsignedLongValue { _animationCurve = UIViewAnimationOptions(rawValue: curve) } } else { _animationCurve = UIViewAnimationOptions.CurveEaseOut } // Getting keyboard animation duration if let duration = info[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue { //Saving animation duration if duration != 0.0 { _animationDuration = duration } } // Getting UIKeyboardSize. if let kbFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue { _kbSize = kbFrame.size _IQShowLog("UIKeyboard Size : \(_kbSize)") } } // Getting topMost ViewController. var topMostController = _textFieldView?.topMostController() if topMostController == nil { topMostController = keyWindow()?.topMostController() } //If last restored keyboard size is different(any orientation accure), then refresh. otherwise not. if CGSizeEqualToSize(_kbSize, oldKBSize) == false { //If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false { //Getting textField viewController if let textFieldViewController = _textFieldView?.viewController() { var shouldIgnore = false for disabledClassString in _disabledClasses { if let disabledClass = NSClassFromString(disabledClassString) { //If viewController is kind of disabled viewController class, then ignoring to adjust view. if textFieldViewController.isKindOfClass(disabledClass) { shouldIgnore = true break } } } //If shouldn't ignore. if shouldIgnore == false { // keyboard is already showing. adjust frame. adjustFrame() } } } } _IQShowLog("****** \(__FUNCTION__) ended ******") } /* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */ internal func keyboardWillHide(notification : NSNotification?) -> Void { //If it's not a fake notification generated by [self setEnable:NO]. if notification != nil { _kbShowNotification = nil } //If not enabled then do nothing. if enable == false { return } _IQShowLog("****** \(__FUNCTION__) started ******") //Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56) // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) // if (_textFieldView == nil) return // Boolean to know keyboard is showing/hiding _keyboardManagerFlags.isKeyboardShowing = false let info : [NSObject : AnyObject]? = notification?.userInfo // Getting keyboard animation duration if let duration = info?[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue { if duration != 0 { // Setitng keyboard animation duration _animationDuration = duration } } //Restoring the contentOffset of the lastScrollView if let lastScrollView = _lastScrollView { UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets if self.shouldRestoreScrollViewContentOffset == true { lastScrollView.contentOffset = self._startingContentOffset } self._IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)") // TODO: restore scrollView state // This is temporary solution. Have to implement the save and restore scrollView state var superScrollView = lastScrollView while let scrollView = superScrollView.superviewOfClassType(UIScrollView) as? UIScrollView { let contentSize = CGSizeMake(max(scrollView.contentSize.width, CGRectGetWidth(scrollView.frame)), max(scrollView.contentSize.height, CGRectGetHeight(scrollView.frame))) let minimumY = contentSize.height - CGRectGetHeight(scrollView.frame) if minimumY < scrollView.contentOffset.y { scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, minimumY) self._IQShowLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)") } superScrollView = scrollView } }) { (finished) -> Void in } } // Setting rootViewController frame to it's original position. // (Bug ID: #18) if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == false { if let rootViewController = _rootViewController { //frame size needs to be adjusted on iOS8 due to orientation API changes. if #available(iOS 8.0, *) { _topViewBeginRect.size = rootViewController.view.frame.size } //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in var hasDoneTweakLayoutGuide = false if let viewController = self._textFieldView?.viewController() { if let constraint = viewController.IQLayoutGuideConstraint { var layoutGuide : UILayoutSupport? if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } if let itemLayoutGuide : UILayoutSupport = layoutGuide { if (itemLayoutGuide === viewController.topLayoutGuide || itemLayoutGuide === viewController.bottomLayoutGuide) { constraint.constant = self._layoutGuideConstraintInitialConstant rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() hasDoneTweakLayoutGuide = true } } } } if hasDoneTweakLayoutGuide == false { self._IQShowLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)") // Setting it's new frame rootViewController.view.frame = self._topViewBeginRect //Animating content if needed (Bug ID: #204) if self.layoutIfNeededOnUpdate == true { //Animating content (Bug ID: #160) rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() } } }) { (finished) -> Void in } _rootViewController = nil } } //Reset all values _lastScrollView = nil _kbSize = CGSizeZero _startingContentInsets = UIEdgeInsetsZero _startingScrollIndicatorInsets = UIEdgeInsetsZero _startingContentOffset = CGPointZero // topViewBeginRect = CGRectZero //Commented due to #82 _IQShowLog("****** \(__FUNCTION__) ended ******") } internal func keyboardDidHide(notification:NSNotification) { _IQShowLog("****** \(__FUNCTION__) started ******") _topViewBeginRect = CGRectZero _IQShowLog("****** \(__FUNCTION__) ended ******") } ///------------------------------------------- /// MARK: UITextField/UITextView Notifications ///------------------------------------------- /** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */ internal func textFieldViewDidBeginEditing(notification:NSNotification) { _IQShowLog("****** \(__FUNCTION__) started ******") // Getting object _textFieldView = notification.object as? UIView if overrideKeyboardAppearance == true { if let textFieldView = _textFieldView as? UITextField { //If keyboard appearance is not like the provided appearance if textFieldView.keyboardAppearance != keyboardAppearance { //Setting textField keyboard appearance and reloading inputViews. textFieldView.keyboardAppearance = keyboardAppearance textFieldView.reloadInputViews() } } else if let textFieldView = _textFieldView as? UITextView { //If keyboard appearance is not like the provided appearance if textFieldView.keyboardAppearance != keyboardAppearance { //Setting textField keyboard appearance and reloading inputViews. textFieldView.keyboardAppearance = keyboardAppearance textFieldView.reloadInputViews() } } } // Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed. //Added _isTextFieldViewFrameChanged check. (Bug ID: #92) if _keyboardManagerFlags.isTextFieldViewFrameChanged == false { if let textFieldView = _textFieldView { _textFieldViewIntialFrame = textFieldView.frame _IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)") } } //If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required. if enableAutoToolbar == true { _IQShowLog("adding UIToolbars if required") //UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it. if _textFieldView is UITextView == true && _textFieldView?.inputAccessoryView == nil { UIView.animateWithDuration(0.00001, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.addToolbarIfRequired() }, completion: { (finished) -> Void in //RestoringTextView before reloading inputViews if (self._keyboardManagerFlags.isTextFieldViewFrameChanged) { self._keyboardManagerFlags.isTextFieldViewFrameChanged = false if let textFieldView = self._textFieldView { textFieldView.frame = self._textFieldViewIntialFrame } } //On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews. self._textFieldView?.reloadInputViews() }) } else { //Adding toolbar addToolbarIfRequired() } } if enable == false { _IQShowLog("****** \(__FUNCTION__) ended ******") return } _textFieldView?.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14) if _keyboardManagerFlags.isKeyboardShowing == false { // (Bug ID: #5) // keyboard is not showing(At the beginning only). We should save rootViewRect. if let constant = _textFieldView?.viewController()?.IQLayoutGuideConstraint?.constant { _layoutGuideConstraintInitialConstant = constant } _rootViewController = _textFieldView?.topMostController() if _rootViewController == nil { _rootViewController = keyWindow()?.topMostController() } if let rootViewController = _rootViewController { _topViewBeginRect = rootViewController.view.frame _IQShowLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)") } } //If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76) //See notes:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false { //Getting textField viewController if let textFieldViewController = _textFieldView?.viewController() { var shouldIgnore = false for disabledClassString in _disabledClasses { if let disabledClass = NSClassFromString(disabledClassString) { //If viewController is kind of disabled viewController class, then ignoring to adjust view. if textFieldViewController.isKindOfClass(disabledClass) { shouldIgnore = true break } } } //If shouldn't ignore. if shouldIgnore == false { // keyboard is already showing. adjust frame. adjustFrame() } } } _IQShowLog("****** \(__FUNCTION__) ended ******") } /** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */ internal func textFieldViewDidEndEditing(notification:NSNotification) { _IQShowLog("****** \(__FUNCTION__) started ******") //Removing gesture recognizer (Enhancement ID: #14) _textFieldView?.window?.removeGestureRecognizer(_tapGesture) // We check if there's a change in original frame or not. if _keyboardManagerFlags.isTextFieldViewFrameChanged == true { UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in self._keyboardManagerFlags.isTextFieldViewFrameChanged = false self._IQShowLog("Restoring \(self._textFieldView?._IQDescription()) frame to : \(self._textFieldViewIntialFrame)") self._textFieldView?.frame = self._textFieldViewIntialFrame }, completion: { (finished) -> Void in }) } //Setting object to nil _textFieldView = nil _IQShowLog("****** \(__FUNCTION__) ended ******") } /** UITextViewTextDidChangeNotificationBug, fix for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string */ internal func textFieldViewDidChange(notification:NSNotification) { // (Bug ID: #18) if shouldFixTextViewClip { let textView = notification.object as! UITextView let line = textView.caretRectForPosition((textView.selectedTextRange?.start)!) let overflow = CGRectGetMaxY(line) - (textView.contentOffset.y + CGRectGetHeight(textView.bounds) - textView.contentInset.bottom - textView.contentInset.top) //Added overflow conditions (Bug ID: 95) if overflow > 0.0 && overflow < CGFloat(FLT_MAX) { // We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it) // Scroll caret to visible area var offset = textView.contentOffset offset.y += overflow + 7 // leave 7 pixels margin // Cannot animate with setContentOffset:animated: or caret will not appear UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in textView.contentOffset = offset }, completion: { (finished) -> Void in }) } } } ///------------------------------------------ /// MARK: Interface Orientation Notifications ///------------------------------------------ /** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/ internal func willChangeStatusBarOrientation(notification:NSNotification) { _IQShowLog("****** \(__FUNCTION__) started ******") //If textFieldViewInitialRect is saved then restore it.(UITextView case @canAdjustTextView) if _keyboardManagerFlags.isTextFieldViewFrameChanged == true { if let textFieldView = _textFieldView { //Due to orientation callback we need to set it's original position. UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in self._keyboardManagerFlags.isTextFieldViewFrameChanged = false self._IQShowLog("Restoring \(textFieldView._IQDescription()) frame to : \(self._textFieldViewIntialFrame)") //Setting textField to it's initial frame textFieldView.frame = self._textFieldViewIntialFrame }, completion: { (finished) -> Void in }) } } _IQShowLog("****** \(__FUNCTION__) ended ******") } ///------------------ /// MARK: AutoToolbar ///------------------ /** Get all UITextField/UITextView siblings of textFieldView. */ private func responderViews()-> [UIView]? { var superConsideredView : UIView? //If find any consider responderView in it's upper hierarchy then will get deepResponderView. for disabledClassString in _toolbarPreviousNextConsideredClass { if let disabledClass = NSClassFromString(disabledClassString) { superConsideredView = _textFieldView?.superviewOfClassType(disabledClass) if superConsideredView != nil { break } } } //If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22) if superConsideredView != nil { return superConsideredView?.deepResponderViews() } else { //Otherwise fetching all the siblings if let textFields = _textFieldView?.responderSiblings() { //Sorting textFields according to behaviour switch toolbarManageBehaviour { //If autoToolbar behaviour is bySubviews, then returning it. case IQAutoToolbarManageBehaviour.BySubviews: return textFields //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.ByTag: return textFields.sortedArrayByTag() //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.ByPosition: return textFields.sortedArrayByPosition() } } else { return nil } } } /** Add toolbar if it is required to add on textFields and it's siblings. */ private func addToolbarIfRequired() { if let textFieldViewController = _textFieldView?.viewController() { for disabledClassString in _disabledToolbarClasses { if let disabledClass = NSClassFromString(disabledClassString) { if textFieldViewController.isKindOfClass(disabledClass) { removeToolbarIfRequired() return } } } } // Getting all the sibling textFields. if let siblings = responderViews() { // If only one object is found, then adding only Done button. if siblings.count == 1 { let textField = siblings[0] //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar). //setInputAccessoryView: check (Bug ID: #307) if textField.respondsToSelector(Selector("setInputAccessoryView:")) && (textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addDoneOnKeyboardWithTarget(self, action: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder) textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78) } if textField.inputAccessoryView is IQToolbar && textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag { let toolbar = textField.inputAccessoryView as! IQToolbar // Setting toolbar to keyboard. if let _textField = textField as? UITextField { //Bar style according to keyboard appearance switch _textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black toolbar.tintColor = UIColor.whiteColor() default: toolbar.barStyle = UIBarStyle.Default toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textField.tintColor : _defaultToolbarTintColor } } else if let _textView = textField as? UITextView { //Bar style according to keyboard appearance switch _textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black toolbar.tintColor = UIColor.whiteColor() default: toolbar.barStyle = UIBarStyle.Default toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textView.tintColor : _defaultToolbarTintColor } } //Setting toolbar title font. // (Enhancement ID: #30) if shouldShowTextFieldPlaceholder == true && textField.shouldHideTitle == false { //Updating placeholder font to toolbar. //(Bug ID: #148) if let _textField = textField as? UITextField { if toolbar.title == nil || toolbar.title != _textField.placeholder { toolbar.title = _textField.placeholder } } else if let _textView = textField as? IQTextView { if toolbar.title == nil || toolbar.title != _textView.placeholder { toolbar.title = _textView.placeholder } } else { toolbar.title = nil } //Setting toolbar title font. // (Enhancement ID: #30) if placeholderFont != nil { toolbar.titleFont = placeholderFont } } else { toolbar.title = nil } } } else if siblings.count != 0 { // If more than 1 textField is found. then adding previous/next/done buttons on it. for textField in siblings { //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Done toolbar). //setInputAccessoryView: check (Bug ID: #307) if textField.respondsToSelector(Selector("setInputAccessoryView:")) && (textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag) { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: "previousAction:", nextAction: "nextAction:", doneAction: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder) textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78) } if textField.inputAccessoryView is IQToolbar && textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag { let toolbar = textField.inputAccessoryView as! IQToolbar // Setting toolbar to keyboard. if let _textField = textField as? UITextField { //Bar style according to keyboard appearance switch _textField.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black toolbar.tintColor = UIColor.whiteColor() default: toolbar.barStyle = UIBarStyle.Default toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textField.tintColor : _defaultToolbarTintColor } } else if let _textView = textField as? UITextView { //Bar style according to keyboard appearance switch _textView.keyboardAppearance { case UIKeyboardAppearance.Dark: toolbar.barStyle = UIBarStyle.Black toolbar.tintColor = UIColor.whiteColor() default: toolbar.barStyle = UIBarStyle.Default toolbar.tintColor = shouldToolbarUsesTextFieldTintColor ? _textView.tintColor : _defaultToolbarTintColor } } //Setting toolbar title font. // (Enhancement ID: #30) if shouldShowTextFieldPlaceholder == true && textField.shouldHideTitle == false { //Updating placeholder font to toolbar. //(Bug ID: #148) if let _textField = textField as? UITextField { if toolbar.title == nil || toolbar.title != _textField.placeholder { toolbar.title = _textField.placeholder } } else if let _textView = textField as? IQTextView { if toolbar.title == nil || toolbar.title != _textView.placeholder { toolbar.title = _textView.placeholder } } else { toolbar.title = nil } //Setting toolbar title font. // (Enhancement ID: #30) if placeholderFont != nil { toolbar.titleFont = placeholderFont } } else { toolbar.title = nil } //In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56) // If firstTextField, then previous should not be enabled. if siblings[0] == textField { textField.setEnablePrevious(false, isNextEnabled: true) } else if siblings.last == textField { // If lastTextField then next should not be enaled. textField.setEnablePrevious(true, isNextEnabled: false) } else { textField.setEnablePrevious(true, isNextEnabled: true) } } } } } } /** Remove any toolbar if it is IQToolbar. */ private func removeToolbarIfRequired() { // (Bug ID: #18) // Getting all the sibling textFields. if let siblings = responderViews() { for view in siblings { if let toolbar = view.inputAccessoryView as? IQToolbar { //setInputAccessoryView: check (Bug ID: #307) if view.respondsToSelector(Selector("setInputAccessoryView:")) && (toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) { if let textField = view as? UITextField { textField.inputAccessoryView = nil } else if let textView = view as? UITextView { textView.inputAccessoryView = nil } } } } } } private func _IQShowLog(logString: String) { #if IQKEYBOARDMANAGER_DEBUG println("IQKeyboardManager: " + logString) #endif } }
mit
JGiola/swift
test/Distributed/Inputs/FakeCodableForDistributedTests.swift
9
13904
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Swift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// /// Fake encoder intended to serialize into a string representation easy to /// assert on. public final class FakeEncoder { public func encode<T: Encodable>(_ value: T) throws -> String { let stringsEncoding = StringsEncoding() try value.encode(to: stringsEncoding) return dotStringsFormat(from: stringsEncoding.data.strings) } private func dotStringsFormat(from strings: [String: String]) -> String { let dotStrings = strings.map { k, v -> String in if k.isEmpty { return "\(v);" } else { return "\(k): \(v);" } } return dotStrings.joined(separator: " ") } } fileprivate struct StringsEncoding: Encoder { fileprivate final class Storage { private(set) var strings: [String: String] = [:] func encode(key codingKey: [CodingKey], value: String) { let key = codingKey.map { $0.stringValue } .joined(separator: ".") strings[key] = value } } fileprivate var data: Storage init(to encoded: Storage = Storage()) { self.data = encoded } var codingPath: [CodingKey] = [] let userInfo: [CodingUserInfoKey: Any] = [:] func container<Key: CodingKey>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> { var container = StringsKeyedEncoding<Key>(to: data) container.codingPath = codingPath return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { var container = StringsUnkeyedEncoding(to: data) container.codingPath = codingPath return container } func singleValueContainer() -> SingleValueEncodingContainer { var container = StringsSingleValueEncoding(to: data) container.codingPath = codingPath return container } } fileprivate struct StringsKeyedEncoding<Key: CodingKey>: KeyedEncodingContainerProtocol { private let data: StringsEncoding.Storage init(to data: StringsEncoding.Storage) { self.data = data } var codingPath: [CodingKey] = [] mutating func encodeNil(forKey key: Key) throws { data.encode(key: codingPath + [key], value: "nil") } mutating func encode(_ value: Bool, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: String, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value) } mutating func encode(_ value: Double, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Float, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int8, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int16, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int32, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: Int64, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt8, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt16, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt32, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode(_ value: UInt64, forKey key: Key) throws { data.encode(key: codingPath + [key], value: value.description) } mutating func encode<T: Encodable>(_ value: T, forKey key: Key) throws { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath.append(key) try value.encode(to: stringsEncoding) } mutating func nestedContainer<NestedKey: CodingKey>( keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { var container = StringsKeyedEncoding<NestedKey>(to: data) container.codingPath = codingPath + [key] return KeyedEncodingContainer(container) } mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { var container = StringsUnkeyedEncoding(to: data) container.codingPath = codingPath + [key] return container } mutating func superEncoder() -> Encoder { let superKey = Key(stringValue: "super")! return superEncoder(forKey: superKey) } mutating func superEncoder(forKey key: Key) -> Encoder { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath = codingPath + [key] return stringsEncoding } } fileprivate struct StringsUnkeyedEncoding: UnkeyedEncodingContainer { private let data: StringsEncoding.Storage init(to data: StringsEncoding.Storage) { self.data = data } var codingPath: [CodingKey] = [] private(set) var count: Int = 0 private mutating func nextIndexedKey() -> CodingKey { let nextCodingKey = IndexedCodingKey(intValue: count)! count += 1 return nextCodingKey } private struct IndexedCodingKey: CodingKey { let intValue: Int? let stringValue: String init?(intValue: Int) { self.intValue = intValue self.stringValue = intValue.description } init?(stringValue: String) { return nil } } mutating func encodeNil() throws { data.encode(key: codingPath + [nextIndexedKey()], value: "nil") } mutating func encode(_ value: Bool) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: String) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value) } mutating func encode(_ value: Double) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Float) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int8) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int16) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int32) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: Int64) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt8) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt16) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt32) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode(_ value: UInt64) throws { data.encode(key: codingPath + [nextIndexedKey()], value: value.description) } mutating func encode<T: Encodable>(_ value: T) throws { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath = codingPath + [nextIndexedKey()] try value.encode(to: stringsEncoding) } mutating func nestedContainer<NestedKey: CodingKey>( keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { var container = StringsKeyedEncoding<NestedKey>(to: data) container.codingPath = codingPath + [nextIndexedKey()] return KeyedEncodingContainer(container) } mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { var container = StringsUnkeyedEncoding(to: data) container.codingPath = codingPath + [nextIndexedKey()] return container } mutating func superEncoder() -> Encoder { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath.append(nextIndexedKey()) return stringsEncoding } } fileprivate struct StringsSingleValueEncoding: SingleValueEncodingContainer { private let data: StringsEncoding.Storage init(to data: StringsEncoding.Storage) { self.data = data } var codingPath: [CodingKey] = [] mutating func encodeNil() throws { data.encode(key: codingPath, value: "nil") } mutating func encode(_ value: Bool) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: String) throws { data.encode(key: codingPath, value: value) } mutating func encode(_ value: Double) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Float) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int8) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int16) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int32) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: Int64) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt8) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt16) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt32) throws { data.encode(key: codingPath, value: value.description) } mutating func encode(_ value: UInt64) throws { data.encode(key: codingPath, value: value.description) } mutating func encode<T: Encodable>(_ value: T) throws { var stringsEncoding = StringsEncoding(to: data) stringsEncoding.codingPath = codingPath try value.encode(to: stringsEncoding) } } public final class FakeDecoder: Decoder { public var codingPath: [CodingKey] = [] public var userInfo: [CodingUserInfoKey: Any] = [:] var string: String = "" public func decode<T>(_ string: String, as type: T.Type) throws -> T where T: Decodable { self.string = string return try type.init(from: self) } public func container<Key>( keyedBy type: Key.Type ) throws -> KeyedDecodingContainer<Key> { fatalError("\(#function) not implemented") } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { fatalError("\(#function) not implemented") } public func singleValueContainer() throws -> SingleValueDecodingContainer { return FakeSingleValueDecodingContainer(string: self.string) } } public final class FakeSingleValueDecodingContainer: SingleValueDecodingContainer { public var codingPath: [CodingKey] { [] } let string: String init(string: String) { self.string = string } public func decodeNil() -> Bool { fatalError("\(#function) not implemented") } public func decode(_ type: Bool.Type) throws -> Bool { fatalError("\(#function) not implemented") } public func decode(_ type: String.Type) throws -> String { String(self.string.split(separator: ";").first!) } public func decode(_ type: Double.Type) throws -> Double { fatalError("\(#function) not implemented") } public func decode(_ type: Float.Type) throws -> Float { fatalError("\(#function) not implemented") } public func decode(_ type: Int.Type) throws -> Int { fatalError("\(#function) not implemented") } public func decode(_ type: Int8.Type) throws -> Int8 { fatalError("\(#function) not implemented") } public func decode(_ type: Int16.Type) throws -> Int16 { fatalError("\(#function) not implemented") } public func decode(_ type: Int32.Type) throws -> Int32 { fatalError("\(#function) not implemented") } public func decode(_ type: Int64.Type) throws -> Int64 { fatalError("\(#function) not implemented") } public func decode(_ type: UInt.Type) throws -> UInt { fatalError("\(#function) not implemented") } public func decode(_ type: UInt8.Type) throws -> UInt8 { fatalError("\(#function) not implemented") } public func decode(_ type: UInt16.Type) throws -> UInt16 { fatalError("\(#function) not implemented") } public func decode(_ type: UInt32.Type) throws -> UInt32 { fatalError("\(#function) not implemented") } public func decode(_ type: UInt64.Type) throws -> UInt64 { fatalError("\(#function) not implemented") } public func decode<T>(_ type: T.Type) throws -> T where T : Decodable { fatalError("\(#function) not implemented") } }
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/02202-swift-boundgenerictype-get.swift
11
511
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse protocol A : Boolean, U.b : AnyObject) -> () { } [1] func a<l : b { } protocol b { typealias e: e { } let b : Boolean)
apache-2.0
s-aska/Justaway-for-iOS
Justaway/TabSettings.swift
1
2129
// // TabSettings.swift // Justaway // // Created by Shinichiro Aska on 10/19/15. // Copyright © 2015 Shinichiro Aska. All rights reserved. // import Foundation import EventBox import KeyClip class Tab { struct Constants { static let type = "type" static let userID = "user_id" static let arguments = "arguments" } enum `Type`: String { case HomeTimline case UserTimline case Mentions case Notifications case Favorites case Searches case Lists case Messages } let type: Type let userID: String let arguments: NSDictionary init(type: Type, userID: String, arguments: NSDictionary) { self.type = type self.userID = userID self.arguments = arguments } init(_ dictionary: NSDictionary) { self.type = Type(rawValue: (dictionary[Constants.type] as? String) ?? "")! self.userID = (dictionary[Constants.userID] as? String) ?? "" self.arguments = (dictionary[Constants.arguments] as? NSDictionary) ?? NSDictionary() } init(userID: String, keyword: String) { self.type = .Searches self.userID = userID self.arguments = ["keyword": keyword] } init(userID: String, user: TwitterUser) { self.type = .UserTimline self.userID = userID self.arguments = ["user": user.dictionaryValue] } init(userID: String, list: TwitterList) { self.type = .Lists self.userID = userID self.arguments = ["list": list.dictionaryValue] } var keyword: String { return self.arguments["keyword"] as? String ?? "-" } var user: TwitterUser { return TwitterUser(self.arguments["user"] as? [String: AnyObject] ?? [:]) } var list: TwitterList { return TwitterList(self.arguments["list"] as? [String: AnyObject] ?? [:]) } var dictionaryValue: NSDictionary { return [ Constants.type : type.rawValue, Constants.userID : userID, Constants.arguments : arguments ] } }
mit
kstaring/swift
test/attr/ApplicationMain/attr_NSApplicationMain_not_NSApplicationDelegate.swift
24
284
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -parse-as-library -verify %s // REQUIRES: objc_interop import AppKit @NSApplicationMain // expected-error{{'NSApplicationMain' class must conform to the 'NSApplicationDelegate' protocol}} class MyNonDelegate { }
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/01283-swift-modulefile-getdecl.swift
11
613
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class e { var _ = d() { class A { class func a() -> Self { } } func b<T>(t: AnyObject.Type) -> T! { } } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { } protocol e { } protocol i : d { func d
apache-2.0
LemonRuss/TableComponents
TableComponents/Classes/Common/UIColor+Helper.swift
1
686
// // UIColor+Helper.swift // EFS // // Created by Artur Guseynov on 20.06.16. // Copyright © 2016 Sberbank. All rights reserved. // import UIKit extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(hex: Int) { self.init(red: (hex >> 16) & 0xff, green: (hex >> 8) & 0xff, blue: hex & 0xff) } }
mit
victorchee/CollectionView
BookCollectionView/BookCollectionView/Book.swift
2
833
// // Book.swift // BookCollectionView // // Created by qihaijun on 11/30/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit class Book { var dict: NSDictionary? convenience init(dict: NSDictionary) { self.init() self.dict = dict } func coverImage() -> UIImage? { guard let cover = dict?["cover"] as? String else { return nil } return UIImage(named: cover) } func pageImage(_ index: Int) -> UIImage? { guard let pages = dict?["pages"] as? [String] else { return nil } return UIImage(named: pages[index]) } func numberOfPages() -> Int { guard let pages = dict?["pages"] as? [String] else { return 0 } return pages.count } }
mit
justindarc/firefox-ios
Client/Frontend/Settings/AppSettingsOptions.swift
1
49234
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Account import SwiftKeychainWrapper import LocalAuthentication // This file contains all of the settings available in the main settings screen of the app. private var ShowDebugSettings: Bool = false private var DebugSettingsClickCount: Int = 0 // For great debugging! class HiddenSetting: Setting { unowned let settings: SettingsTableViewController init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var hidden: Bool { return !ShowDebugSettings } } // Sync setting for connecting a Firefox Account. Shown when we don't have an account. class ConnectSetting: WithoutAccountSetting { override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: Strings.FxASignInToSync, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var accessibilityIdentifier: String? { return "SignInToSync" } override func onClick(_ navigationController: UINavigationController?) { let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"]) let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams) viewController.delegate = self navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.imageView?.image = UIImage.templateImageNamed("FxA-Default") cell.imageView?.tintColor = UIColor.theme.tableView.disabledRowText cell.imageView?.layer.cornerRadius = (cell.imageView?.frame.size.width)! / 2 cell.imageView?.layer.masksToBounds = true } } class SyncNowSetting: WithAccountSetting { let imageView = UIImageView(frame: CGRect(width: 30, height: 30)) let syncIconWrapper = UIImage.createWithColor(CGSize(width: 30, height: 30), color: UIColor.clear) let syncBlueIcon = UIImage(named: "FxA-Sync-Blue")?.createScaled(CGSize(width: 20, height: 20)) let syncIcon: UIImage? = { let image = UIImage(named: "FxA-Sync")?.createScaled(CGSize(width: 20, height: 20)) return ThemeManager.instance.currentName == .dark ? image?.tinted(withColor: .white) : image }() // Animation used to rotate the Sync icon 360 degrees while syncing is in progress. let continuousRotateAnimation = CABasicAnimation(keyPath: "transform.rotation") override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(stopRotateSyncIcon), name: .ProfileDidFinishSyncing, object: nil) } fileprivate lazy var timestampFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() fileprivate var syncNowTitle: NSAttributedString { if !DeviceInfo.hasConnectivity() { return NSAttributedString( string: Strings.FxANoInternetConnection, attributes: [ NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultMediumFont ] ) } return NSAttributedString( string: Strings.FxASyncNow, attributes: [ NSAttributedString.Key.foregroundColor: self.enabled ? UIColor.theme.tableView.syncText : UIColor.theme.tableView.headerTextLight, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFont ] ) } fileprivate let syncingTitle = NSAttributedString(string: Strings.SyncingMessageWithEllipsis, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: DynamicFontHelper.defaultHelper.DefaultStandardFontSize, weight: UIFont.Weight.regular)]) func startRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.add(self.continuousRotateAnimation, forKey: "rotateKey") } } @objc func stopRotateSyncIcon() { DispatchQueue.main.async { self.imageView.layer.removeAllAnimations() } } override var accessoryType: UITableViewCell.AccessoryType { return .none } override var image: UIImage? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncIcon } switch syncStatus { case .inProgress: return syncBlueIcon default: return syncIcon } } override var title: NSAttributedString? { guard let syncStatus = profile.syncManager.syncDisplayState else { return syncNowTitle } switch syncStatus { case .bad(let message): guard let message = message else { return syncNowTitle } return NSAttributedString(string: message, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.errorText, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .warning(let message): return NSAttributedString(string: message, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.warningText, NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFont]) case .inProgress: return syncingTitle default: return syncNowTitle } } override var status: NSAttributedString? { guard let timestamp = profile.syncManager.lastSyncFinishTime else { return nil } let formattedLabel = timestampFormatter.string(from: Date.fromTimestamp(timestamp)) let attributedString = NSMutableAttributedString(string: formattedLabel) let attributes = [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)] let range = NSRange(location: 0, length: attributedString.length) attributedString.setAttributes(attributes, range: range) return attributedString } override var hidden: Bool { return !enabled } override var enabled: Bool { if !DeviceInfo.hasConnectivity() { return false } return profile.hasSyncableAccount() } fileprivate lazy var troubleshootButton: UIButton = { let troubleshootButton = UIButton(type: .roundedRect) troubleshootButton.setTitle(Strings.FirefoxSyncTroubleshootTitle, for: .normal) troubleshootButton.addTarget(self, action: #selector(self.troubleshoot), for: .touchUpInside) troubleshootButton.tintColor = UIColor.theme.tableView.rowActionAccessory troubleshootButton.titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultSmallFont troubleshootButton.sizeToFit() return troubleshootButton }() fileprivate lazy var warningIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "AmberCaution")) imageView.sizeToFit() return imageView }() fileprivate lazy var errorIcon: UIImageView = { let imageView = UIImageView(image: UIImage(named: "RedCaution")) imageView.sizeToFit() return imageView }() fileprivate let syncSUMOURL = SupportUtils.URLForTopic("sync-status-ios") @objc fileprivate func troubleshoot() { let viewController = SettingsContentViewController() viewController.url = syncSUMOURL settings.navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { cell.textLabel?.attributedText = title cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .bad(let message): if let _ = message { // add the red warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(errorIcon, toCell: cell) } else { cell.detailTextLabel?.attributedText = status cell.accessoryView = nil } case .warning(_): // add the amber warning symbol // add a link to the MANA page cell.detailTextLabel?.attributedText = nil cell.accessoryView = troubleshootButton addIcon(warningIcon, toCell: cell) case .good: cell.detailTextLabel?.attributedText = status fallthrough default: cell.accessoryView = nil } } else { cell.accessoryView = nil } cell.accessoryType = accessoryType cell.isUserInteractionEnabled = !profile.syncManager.isSyncing && DeviceInfo.hasConnectivity() // Animation that loops continously until stopped continuousRotateAnimation.fromValue = 0.0 continuousRotateAnimation.toValue = CGFloat(Double.pi) continuousRotateAnimation.isRemovedOnCompletion = true continuousRotateAnimation.duration = 0.5 continuousRotateAnimation.repeatCount = .infinity // To ensure sync icon is aligned properly with user's avatar, an image is created with proper // dimensions and color, then the scaled sync icon is added as a subview. imageView.contentMode = .center imageView.image = image cell.imageView?.subviews.forEach({ $0.removeFromSuperview() }) cell.imageView?.image = syncIconWrapper cell.imageView?.addSubview(imageView) if let syncStatus = profile.syncManager.syncDisplayState { switch syncStatus { case .inProgress: self.startRotateSyncIcon() default: self.stopRotateSyncIcon() } } } fileprivate func addIcon(_ image: UIImageView, toCell cell: UITableViewCell) { cell.contentView.addSubview(image) cell.textLabel?.snp.updateConstraints { make in make.leading.equalTo(image.snp.trailing).offset(5) make.trailing.lessThanOrEqualTo(cell.contentView) make.centerY.equalTo(cell.contentView) } image.snp.makeConstraints { make in make.leading.equalTo(cell.contentView).offset(17) make.top.equalTo(cell.textLabel!).offset(2) } } override func onClick(_ navigationController: UINavigationController?) { if !DeviceInfo.hasConnectivity() { return } NotificationCenter.default.post(name: .UserInitiatedSyncManually, object: nil) profile.syncManager.syncEverything(why: .syncNow) } } // Sync setting that shows the current Firefox Account status. class AccountStatusSetting: WithAccountSetting { override init(settings: SettingsTableViewController) { super.init(settings: settings) NotificationCenter.default.addObserver(self, selector: #selector(updateAccount), name: .FirefoxAccountProfileChanged, object: nil) } @objc func updateAccount(notification: Notification) { DispatchQueue.main.async { self.settings.tableView.reloadData() } } override var image: UIImage? { if let image = profile.getAccount()?.fxaProfile?.avatar.image { return image.createScaled(CGSize(width: 30, height: 30)) } let image = UIImage(named: "placeholder-avatar") return image?.createScaled(CGSize(width: 30, height: 30)) } override var accessoryType: UITableViewCell.AccessoryType { if let account = profile.getAccount() { switch account.actionNeeded { case .needsVerification: // We link to the resend verification email page. return .disclosureIndicator case .needsPassword: // We link to the re-enter password page. return .disclosureIndicator case .none: // We link to FxA web /settings. return .disclosureIndicator case .needsUpgrade: // In future, we'll want to link to an upgrade page. return .none } } return .disclosureIndicator } override var title: NSAttributedString? { if let account = profile.getAccount() { if let displayName = account.fxaProfile?.displayName { return NSAttributedString(string: displayName, attributes: [NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText]) } if let email = account.fxaProfile?.email { return NSAttributedString(string: email, attributes: [NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText]) } return NSAttributedString(string: account.email, attributes: [NSAttributedString.Key.font: DynamicFontHelper.defaultHelper.DefaultStandardFontBold, NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.syncText]) } return nil } override var status: NSAttributedString? { if let account = profile.getAccount() { var string: String switch account.actionNeeded { case .none: return nil case .needsVerification: string = Strings.FxAAccountVerifyEmail break case .needsPassword: string = Strings.FxAAccountVerifyPassword break case .needsUpgrade: string = Strings.FxAAccountUpgradeFirefox break } let orange = UIColor.theme.tableView.warningText let range = NSRange(location: 0, length: string.count) let attrs = [NSAttributedString.Key.foregroundColor: orange] let res = NSMutableAttributedString(string: string) res.setAttributes(attrs, range: range) return res } return nil } override func onClick(_ navigationController: UINavigationController?) { let fxaParams = FxALaunchParams(query: ["entrypoint": "preferences"]) let viewController = FxAContentViewController(profile: profile, fxaOptions: fxaParams) viewController.delegate = self if let account = profile.getAccount() { switch account.actionNeeded { case .none: let viewController = SyncContentSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) return case .needsVerification: var cs = URLComponents(url: account.configuration.settingsURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) if let url = cs?.url { viewController.url = url } case .needsPassword: var cs = URLComponents(url: account.configuration.forceAuthURL, resolvingAgainstBaseURL: false) cs?.queryItems?.append(URLQueryItem(name: "email", value: account.email)) if let url = cs?.url { viewController.url = url } case .needsUpgrade: // In future, we'll want to link to an upgrade page. return } } navigationController?.pushViewController(viewController, animated: true) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if let imageView = cell.imageView { imageView.subviews.forEach({ $0.removeFromSuperview() }) imageView.frame = CGRect(width: 30, height: 30) imageView.layer.cornerRadius = (imageView.frame.height) / 2 imageView.layer.masksToBounds = true imageView.image = image } } } // For great debugging! class RequirePasswordDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsPassword { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require password", comment: "Debug option"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeSeparated() settings.tableView.reloadData() } } // For great debugging! class RequireUpgradeDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let account = profile.getAccount(), account.actionNeeded != FxAActionNeeded.needsUpgrade { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: require upgrade", comment: "Debug option"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.makeDoghouse() settings.tableView.reloadData() } } // For great debugging! class ForgetSyncAuthStateDebugSetting: WithAccountSetting { override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return false } return true } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: forget Sync auth state", comment: "Debug option"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { profile.getAccount()?.syncAuthState.invalidate() settings.tableView.reloadData() } } class DeleteExportedDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: delete exported databases", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let fileManager = FileManager.default do { let files = try fileManager.contentsOfDirectory(atPath: documentsPath) for file in files { if file.hasPrefix("browser.") || file.hasPrefix("logins.") { try fileManager.removeItemInDirectory(documentsPath, named: file) } } } catch { print("Couldn't delete exported data: \(error).") } } } class ExportBrowserDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy databases to app container", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] do { let log = Logger.syncLogger try self.settings.profile.files.copyMatching(fromRelativeDirectory: "", toAbsoluteDirectory: documentsPath) { file in log.debug("Matcher: \(file)") return file.hasPrefix("browser.") || file.hasPrefix("logins.") || file.hasPrefix("metadata.") } } catch { print("Couldn't export browser data: \(error).") } } } class ExportLogDataSetting: HiddenSetting { override var title: NSAttributedString? { // Not localized for now. return NSAttributedString(string: "Debug: copy log files to app container", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Logger.copyPreviousLogsToDocuments() } } /* FeatureSwitchSetting is a boolean switch for features that are enabled via a FeatureSwitch. These are usually features behind a partial release and not features released to the entire population. */ class FeatureSwitchSetting: BoolSetting { let featureSwitch: FeatureSwitch let prefs: Prefs init(prefs: Prefs, featureSwitch: FeatureSwitch, with title: NSAttributedString) { self.featureSwitch = featureSwitch self.prefs = prefs super.init(prefs: prefs, defaultValue: featureSwitch.isMember(prefs), attributedTitleText: title) } override var hidden: Bool { return !ShowDebugSettings } override func displayBool(_ control: UISwitch) { control.isOn = featureSwitch.isMember(prefs) } override func writeBool(_ control: UISwitch) { self.featureSwitch.setMembership(control.isOn, for: self.prefs) } } class ForceCrashSetting: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: Force Crash", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { Sentry.shared.crash() } } class SlowTheDatabase: HiddenSetting { override var title: NSAttributedString? { return NSAttributedString(string: "Debug: simulate slow database operations", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onClick(_ navigationController: UINavigationController?) { debugSimulateSlowDBOperations = !debugSimulateSlowDBOperations } } class SentryIDSetting: HiddenSetting { let deviceAppHash = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)?.string(forKey: "SentryDeviceAppHash") ?? "0000000000000000000000000000000000000000" override var title: NSAttributedString? { return NSAttributedString(string: "Debug: \(deviceAppHash)", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 10)]) } override func onClick(_ navigationController: UINavigationController?) { copyAppDeviceIDAndPresentAlert(by: navigationController) } func copyAppDeviceIDAndPresentAlert(by navigationController: UINavigationController?) { let alertTitle = Strings.SettingsCopyAppVersionAlertTitle let alert = AlertController(title: alertTitle, message: nil, preferredStyle: .alert) getSelectedCell(by: navigationController)?.setSelected(false, animated: true) UIPasteboard.general.string = deviceAppHash navigationController?.topViewController?.present(alert, animated: true) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { alert.dismiss(animated: true) } } } func getSelectedCell(by navigationController: UINavigationController?) -> UITableViewCell? { let controller = navigationController?.topViewController let tableView = (controller as? AppSettingsTableViewController)?.tableView guard let indexPath = tableView?.indexPathForSelectedRow else { return nil } return tableView?.cellForRow(at: indexPath) } } // Show the current version of Firefox class VersionSetting: Setting { unowned let settings: SettingsTableViewController override var accessibilityIdentifier: String? { return "FxVersion" } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override var title: NSAttributedString? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String return NSAttributedString(string: String(format: NSLocalizedString("Version %@ (%@)", comment: "Version number of Firefox shown in settings"), appVersion, buildNumber), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) } override func onClick(_ navigationController: UINavigationController?) { DebugSettingsClickCount += 1 if DebugSettingsClickCount >= 5 { DebugSettingsClickCount = 0 ShowDebugSettings = !ShowDebugSettings settings.tableView.reloadData() } } override func onLongPress(_ navigationController: UINavigationController?) { copyAppVersionAndPresentAlert(by: navigationController) } func copyAppVersionAndPresentAlert(by navigationController: UINavigationController?) { let alertTitle = Strings.SettingsCopyAppVersionAlertTitle let alert = AlertController(title: alertTitle, message: nil, preferredStyle: .alert) getSelectedCell(by: navigationController)?.setSelected(false, animated: true) UIPasteboard.general.string = self.title?.string navigationController?.topViewController?.present(alert, animated: true) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { alert.dismiss(animated: true) } } } func getSelectedCell(by navigationController: UINavigationController?) -> UITableViewCell? { let controller = navigationController?.topViewController let tableView = (controller as? AppSettingsTableViewController)?.tableView guard let indexPath = tableView?.indexPathForSelectedRow else { return nil } return tableView?.cellForRow(at: indexPath) } } // Opens the license page in a new tab class LicenseAndAcknowledgementsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Licenses", comment: "Settings item that opens a tab containing the licenses. See http://mzl.la/1NSAWCG"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "\(InternalURL.baseUrl)/\(AboutLicenseHandler.path)") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens about:rights page in the content view controller class YourRightsSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Your Rights", comment: "Your Rights settings section title"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/about/legal/terms/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the on-boarding screen again class ShowIntroductionSetting: Setting { let profile: Profile override var accessibilityIdentifier: String? { return "ShowTour" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Show Tour", comment: "Show the on-boarding screen again from the settings"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true, completion: { if let appDelegate = UIApplication.shared.delegate as? AppDelegate { appDelegate.browserViewController.presentIntroViewController(true) } }) } } class SendFeedbackSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Send Feedback", comment: "Menu item in settings used to open input.mozilla.org where people can submit feedback"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String return URL(string: "https://input.mozilla.org/feedback/fxios/\(appVersion)") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class SendAnonymousUsageDataSetting: BoolSetting { init(prefs: Prefs, delegate: SettingsDelegate?) { let statusText = NSMutableAttributedString() statusText.append(NSAttributedString(string: Strings.SendUsageSettingMessage, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight])) statusText.append(NSAttributedString(string: " ")) statusText.append(NSAttributedString(string: Strings.SendUsageSettingLink, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.general.highlightBlue])) super.init( prefs: prefs, prefKey: AppConstants.PrefSendUsageData, defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.SendUsageSettingTitle), attributedStatusText: statusText, settingDidChange: { AdjustIntegration.setEnabled($0) LeanPlumClient.shared.set(attributes: [LPAttributeKey.telemetryOptIn: $0]) LeanPlumClient.shared.set(enabled: $0) } ) } override var url: URL? { return SupportUtils.URLForTopic("adjust") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } // Opens the SUMO page in a new tab class OpenSupportPageSetting: Setting { init(delegate: SettingsDelegate?) { super.init(title: NSAttributedString(string: NSLocalizedString("Help", comment: "Show the SUMO support page from the Support section in the settings. see http://mzl.la/1dmM8tZ"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true) { if let url = URL(string: "https://support.mozilla.org/products/ios") { self.delegate?.settingsOpenURLInNewTab(url) } } } } // Opens the search settings pane class SearchSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: profile.searchEngines.defaultEngine.shortName) } override var accessibilityIdentifier: String? { return "Search" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: NSLocalizedString("Search", comment: "Open search section of settings"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class LoginsSetting: Setting { let profile: Profile var tabManager: TabManager! weak var navigationController: UINavigationController? weak var settings: AppSettingsTableViewController? override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Logins" } init(settings: SettingsTableViewController, delegate: SettingsDelegate?) { self.profile = settings.profile self.tabManager = settings.tabManager self.navigationController = settings.navigationController self.settings = settings as? AppSettingsTableViewController super.init(title: NSAttributedString(string: Strings.LoginsAndPasswordsTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { deselectRow() guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let navController = navigationController else { return } LoginListViewController.create(authenticateInNavigationController: navController, profile: profile, settingsDelegate: appDelegate.browserViewController).uponQueue(.main) { loginsVC in guard let loginsVC = loginsVC else { return } LeanPlumClient.shared.track(event: .openedLogins) navController.pushViewController(loginsVC, animated: true) } } } class TouchIDPasscodeSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "TouchIDPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.profile = settings.profile self.tabManager = settings.tabManager let localAuthContext = LAContext() let title: String if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { if localAuthContext.biometryType == .faceID { title = AuthenticationStrings.faceIDPasscodeSetting } else { title = AuthenticationStrings.touchIDPasscodeSetting } } else { title = AuthenticationStrings.passcode } super.init(title: NSAttributedString(string: title, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AuthenticationSettingsViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class ContentBlockerSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "TrackingProtection" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager super.init(title: NSAttributedString(string: Strings.SettingsTrackingProtectionSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ContentBlockerSettingViewController(prefs: profile.prefs) viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class ClearPrivateDataSetting: Setting { let profile: Profile var tabManager: TabManager! override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "ClearPrivateData" } init(settings: SettingsTableViewController) { self.profile = settings.profile self.tabManager = settings.tabManager let clearTitle = Strings.SettingsDataManagementSectionName super.init(title: NSAttributedString(string: clearTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager navigationController?.pushViewController(viewController, animated: true) } } class PrivacyPolicySetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Privacy Policy", comment: "Show Firefox Browser Privacy Policy page from the Privacy section in the settings. See https://www.mozilla.org/privacy/firefox/"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var url: URL? { return URL(string: "https://www.mozilla.org/privacy/firefox/") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) } } class ChinaSyncServiceSetting: WithoutAccountSetting { override var accessoryType: UITableViewCell.AccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } let prefKey = "useChinaSyncService" override var title: NSAttributedString? { return NSAttributedString(string: "本地同步服务", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var status: NSAttributedString? { return NSAttributedString(string: "禁用后使用全球服务同步数据", attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitchThemed() control.onTintColor = UIColor.theme.tableView.controlTint control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? BrowserProfile.isChinaEdition cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) } } class StageSyncServiceDebugSetting: WithoutAccountSetting { override var accessoryType: UITableViewCell.AccessoryType { return .none } var prefs: Prefs { return settings.profile.prefs } var prefKey: String = "useStageSyncService" override var accessibilityIdentifier: String? { return "DebugStageSync" } override var hidden: Bool { if !ShowDebugSettings { return true } if let _ = profile.getAccount() { return true } return false } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Debug: use stage servers", comment: "Debug option"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override var status: NSAttributedString? { let configurationURL = profile.accountConfiguration.authEndpointURL return NSAttributedString(string: configurationURL.absoluteString, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextLight]) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitchThemed() control.onTintColor = UIColor.theme.tableView.controlTint control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged) control.isOn = prefs.boolForKey(prefKey) ?? false cell.accessoryView = control cell.selectionStyle = .none } @objc func switchValueChanged(_ toggle: UISwitch) { prefs.setObject(toggle.isOn, forKey: prefKey) settings.tableView.reloadData() } } class NewTabPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "NewTab" } override var status: NSAttributedString { return NSAttributedString(string: NewTabAccessors.getNewTabPage(self.profile.prefs).settingTitle) } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsNewTabSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = NewTabContentSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class HomeSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "Home" } override var status: NSAttributedString { return NSAttributedString(string: NewTabAccessors.getHomePage(self.profile.prefs).settingTitle) } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.AppMenuOpenHomePageTitleString, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = HomePageSettingViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } @available(iOS 12.0, *) class SiriPageSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "SiriSettings" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsSiriSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = SiriSettingsViewController(prefs: profile.prefs) viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } } class OpenWithSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "OpenWith.Setting" } override var status: NSAttributedString { guard let provider = self.profile.prefs.stringForKey(PrefsKeys.KeyMailToOption), provider != "mailto:" else { return NSAttributedString(string: "") } if let path = Bundle.main.path(forResource: "MailSchemes", ofType: "plist"), let dictRoot = NSArray(contentsOfFile: path) { let mailProvider = dictRoot.compactMap({$0 as? NSDictionary }).first { (dict) -> Bool in return (dict["scheme"] as? String) == provider } return NSAttributedString(string: (mailProvider?["name"] as? String) ?? "") } return NSAttributedString(string: "") } override var style: UITableViewCell.CellStyle { return .value1 } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsOpenWithSectionName, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = OpenWithSettingsViewController(prefs: profile.prefs) navigationController?.pushViewController(viewController, animated: true) } } class AdvancedAccountSetting: HiddenSetting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var accessibilityIdentifier: String? { return "AdvancedAccount.Setting" } override var title: NSAttributedString? { return NSAttributedString(string: Strings.SettingsAdvancedAccountTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText]) } override init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(settings: settings) } override func onClick(_ navigationController: UINavigationController?) { let viewController = AdvancedAccountSettingViewController() viewController.profile = profile navigationController?.pushViewController(viewController, animated: true) } override var hidden: Bool { return !ShowDebugSettings || profile.hasAccount() } } class ThemeSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var accessibilityIdentifier: String? { return "DisplayThemeOption" } override var status: NSAttributedString { if ThemeManager.instance.automaticBrightnessIsOn { return NSAttributedString(string: Strings.DisplayThemeAutomaticStatusLabel) } return NSAttributedString(string: "") } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingsDisplayThemeTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.pushViewController(ThemeSettingsController(), animated: true) } } class TranslationSetting: Setting { let profile: Profile override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var accessibilityIdentifier: String? { return "TranslationOption" } init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: Strings.SettingTranslateSnackBarTitle, attributes: [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.rowText])) } override func onClick(_ navigationController: UINavigationController?) { navigationController?.pushViewController(TranslationSettingsController(profile), animated: true) } }
mpl-2.0
practicalswift/swift
test/multifile/multiconformanceimpls/main.swift
5
1097
// RUN: %empty-directory(%t) // // RUN: %target-build-swift-dylib(%t/%target-library-name(A)) %S/Inputs/A.swift -emit-module -emit-module-path %t/A.swiftmodule -module-name A // RUN: %target-codesign %t/%target-library-name(A) // // RUN: %target-build-swift-dylib(%t/%target-library-name(B)) %S/Inputs/B.swift -emit-module -emit-module-path %t/B.swiftmodule -module-name B -I%t -L%t -lA // RUN: %target-codesign %t/%target-library-name(B) // // RUN: %target-build-swift-dylib(%t/%target-library-name(C)) %S/Inputs/C.swift -emit-module -emit-module-path %t/C.swiftmodule -module-name C -I%t -L%t -lA // RUN: %target-codesign %t/%target-library-name(C) // // RUN: %target-build-swift %s -I %t -o %t/main.out -L %t %target-rpath(%t) -lA -lB -lC // RUN: %target-codesign %t/main.out // // RUN: %target-run %t/main.out %t/%target-library-name(A) %t/%target-library-name(B) %t/%target-library-name(C) | %FileCheck %s // REQUIRES: executable_test import A import B import C func runTheTest() { setAnyWithImplFromB() // CHECK: check returned not Container<Impl> in C checkAnyInC() } runTheTest()
apache-2.0
apple/swift-docc-symbolkit
Tests/SymbolKitTests/SymbolGraph/ModuleTests.swift
1
3048
/* This source file is part of the Swift.org open source project Copyright (c) 2022 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 Swift project authors */ import XCTest import SymbolKit extension SymbolGraph.Module { func roundTripDecode() throws -> Self { let encoder = JSONEncoder() let encoded = try encoder.encode(self) let decoder = JSONDecoder() return try decoder.decode(SymbolGraph.Module.self, from: encoded) } } class ModuleTests: XCTestCase { static let os = SymbolGraph.OperatingSystem(name: "macOS", minimumVersion: .init(major: 10, minor: 9, patch: 0)) static let platform = SymbolGraph.Platform(architecture: "arm64", vendor: "Apple", operatingSystem: os) func testFullRoundTripCoding() throws { let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform, bystanders: ["A"], isVirtual: true) let decodedModule = try module.roundTripDecode() XCTAssertEqual(module, decodedModule) } func testOptionalBystanders() throws { do { // bystanders = nil let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform) let decodedModule = try module.roundTripDecode() XCTAssertNil(decodedModule.bystanders) } do { // bystanders = ["A"] let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform, bystanders: ["A"]) let decodedModule = try module.roundTripDecode() XCTAssertEqual(["A"], decodedModule.bystanders) } } func testOptionalIsVirtual() throws { do { // isVirtual = false let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform) let decodedModule = try module.roundTripDecode() XCTAssertFalse(decodedModule.isVirtual) } do { // isVirtual = true let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform, isVirtual: true) let decodedModule = try module.roundTripDecode() XCTAssertTrue(decodedModule.isVirtual) } } func testOptionalVersion() throws { do { // version = nil let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform) let decodedModule = try module.roundTripDecode() XCTAssertNil(decodedModule.version) } do { // version = 1.0.0 let version = SymbolGraph.SemanticVersion(major: 1, minor: 0, patch: 0) let module = SymbolGraph.Module(name: "Test", platform: ModuleTests.platform, version: version) let decodedModule = try module.roundTripDecode() XCTAssertEqual(version, decodedModule.version) } } }
apache-2.0
STShenZhaoliang/iOS-GuidesAndSampleCode
精通Swift设计模式/Chapter 15/Composite/Composite/main.swift
1
438
let doorWindow = CompositePart(name: "DoorWindow", parts: Part(name: "Window", price: 100.50), Part(name: "Window Switch", price: 12)); let door = CompositePart(name: "Door", parts: doorWindow, Part(name: "Door Loom", price: 80), Part(name: "Door Handles", price: 43.40)); let hood = Part(name: "Hood", price: 320); let order = CustomerOrder(customer: "Bob", parts: [hood, door, doorWindow]); order.printDetails();
mit
huangboju/Moots
UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/AppDelegate.swift
2
1761
// // AppDelegate.swift // SwiftNetworkImages // // Created by Arseniy Kuznetsov on 30/4/16. // Copyright © 2016 Arseniy Kuznetsov. All rights reserved. // import UIKit /// The App Delegate @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds).configure { $0.backgroundColor = .white $0.rootViewController = configureTopViewController() $0.makeKeyAndVisible() } return true } } extension AppDelegate { /// Configures top level view controller and its dependencies func configureTopViewController() -> UIViewController { // Images info loader let imagesInfoLoader = ImagesInfoLoader() // Network image service let imageService = NSURLSessionNetworkImageService() var imageFetcher = ImageFetcher() imageFetcher.inject(imageService) // Images info data source var imagesDataSource = ImagesDataSource() imagesDataSource.inject((imagesInfoLoader, imageFetcher)) // Delegate / Data Source for the collection view let dataSourceDelegate = SampleImagesDataSourceDelegate() // Top-level view controller let viewController = SampleImagesViewController() dataSourceDelegate.inject((imagesDataSource, viewController)) viewController.inject(dataSourceDelegate) return viewController } }
mit
mightydeveloper/swift
validation-test/compiler_crashers_fixed/26144-swift-printingdiagnosticconsumer-handlediagnostic.swift
13
228
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {(({{deinit{{
apache-2.0
mightydeveloper/swift
validation-test/compiler_crashers/27570-checkenumrawvalues.swift
8
275
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func u{struct c<T, U{class d?enum S<e{ enum B<T> :d
apache-2.0
mightydeveloper/swift
validation-test/compiler_crashers/25481-swift-modulefile-getimportedmodules.swift
9
257
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func a{typealias B=t func b<T:T.a
apache-2.0
embryoconcepts/TIY-Assignments
06 -- SHIELD Tracker/SHIELD Hero Tracker/SHIELD Hero Tracker/Hero.swift
1
457
// // Hero.swift // SHIELD Hero Tracker // // Created by Jennifer Hamilton on 10/12/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation class Hero { var name: String var homeworld: String var powers: String init(dictionary: NSDictionary) { name = dictionary["name"] as! String homeworld = dictionary["homeworld"] as! String powers = dictionary["powers"] as! String } }
cc0-1.0
mmrmmlrr/ExamMaster
Pods/ModelsTreeKit/JetPack/UIKit+Signal/UISwitch+Signal.swift
1
422
// // UISwitch+Signal.swift // ModelsTreeKit // // Created by aleksey on 06.03.16. // Copyright © 2016 aleksey chernish. All rights reserved. // import UIKit extension UISwitch { public var onSignal: Observable<Bool> { get { let observable = Observable<Bool>(on) signalForControlEvents(.ValueChanged).map { ($0 as! UISwitch).on }.bindTo(observable) return observable } } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/12704-swift-inflightdiagnostic.swift
11
240
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func < { for { if true { class b { class case , { { { { { { } { { : A.
mit
maxim-pervushin/HyperHabit
HyperHabit/HyperHabit/Views/Button.swift
1
212
// // Created by Maxim Pervushin on 04/02/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import UIKit @IBDesignable class Button: UIButton { } @IBDesignable class ClearButton: UIButton { }
mit
Karumi/BothamNetworking
BothamNetworkingTests/NSHTTPClientTests.swift
1
5495
// // NSHTTPClientTests.swift // BothamNetworking // // Created by Pedro Vicente Gomez on 20/11/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation import XCTest import Nocilla import Nimble @testable import BothamNetworking class NSHTTPClientTests: NocillaTestCase { private let anyUrl = "http://www.any.com" private let anyStatusCode = 201 private let anyBody = "{HttpResponseBody = true}" private let anyNSError = NSError(domain: "DomainError", code: 123, userInfo: nil) func testSendsGetRequestToAnyPath() { stubRequest("GET", anyUrl) let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.GET, url: anyUrl) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(beSuccess()) } func testSendsPostRequestToAnyPath() { stubRequest("POST", anyUrl) let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.POST, url: anyUrl) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(beSuccess()) } func testSendsPutRequestToAnyPath() { stubRequest("PUT", anyUrl) let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.PUT, url: anyUrl) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(beSuccess()) } func testSendsDeleteRequestToAnyPath() { stubRequest("DELETE", anyUrl) let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.DELETE, url: anyUrl) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(beSuccess()) } func testSendsHeadRequestToAnyPath() { stubRequest("HEAD", anyUrl) let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.HEAD, url: anyUrl) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(beSuccess()) } func testReceivesHttpStatusCodeInTheHttpResponse() { stubRequest("GET", anyUrl).andReturn(anyStatusCode) let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.GET, url: anyUrl) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(beSuccess()) } func testPropagatesErrorsInTheFuture() { stubRequest("GET", anyUrl).andFailWithError(anyNSError) let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.GET, url: anyUrl) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(failWithError(.httpClientError(error: anyNSError))) } func testSendsParamsConfiguredInTheHttpRequest() { stubRequest("GET", anyUrl + "?key=value") let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.GET, url: anyUrl, params: ["key": "value"]) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(beSuccess()) } func testSendsBodyConfiguredInTheHttpRequest() { stubRequest("POST", anyUrl) .withBody("{\"key\":\"value\"}" as NSString) let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.POST, url: anyUrl, body: ["key": "value" as AnyObject]) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(beSuccess()) } func testReturnsNSConnectionErrorsAsABothamAPIClientNetworkError() { stubRequest("GET", anyUrl).andFailWithError(NSError.anyConnectionError()) let httpClient = NSHTTPClient() let request = givenOneHttpRequest(.GET, url: anyUrl) var response: Result<HTTPResponse, BothamAPIClientError>? httpClient.send(request) { result in response = result } expect(response).toEventually(failWithError(.networkError)) } private func givenOneHttpRequest(_ httpMethod: HTTPMethod, url: String, params: [String: String]? = nil, headers: [String: String]? = nil, body: [String: AnyObject]? = nil) -> HTTPRequest { var headers = headers headers += ["Content-Type": "application/json"] return HTTPRequest(url: url, parameters: params, headers: headers, httpMethod: httpMethod, body: body) } } extension NSError { static func anyConnectionError() -> NSError { return NSError(domain: NSURLErrorDomain, code: NSURLErrorNetworkConnectionLost, userInfo: nil) } }
apache-2.0
u10int/Kinetic
Example/Tests/Tests.swift
1
65
// https://github.com/Quick/Quick import Nimble import Kinetic
mit
regini/inSquare
inSquareAppIOS/inSquareAppIOS/FavoriteSquareViewController.swift
1
7399
// // FavoriteSquareViewController.swift // inSquare // // Created by Alessandro Steri on 02/03/16. // Copyright © 2016 Alessandro Steri. All rights reserved. // import UIKit import GoogleMaps import Alamofire class FavoriteSquareViewController: UIViewController, UITableViewDelegate { var favouriteSquare = JSON(data: NSData()) { didSet { self.tableView.reloadData() } } //values to pass by cell chatButton tap, updated when the button is tapped var squareId:String = String() var squareName:String = String() var squareLatitude:Double = Double() var squareLongitude:Double = Double() @IBOutlet var tableView: UITableView! @IBOutlet var tabBar: UITabBarItem! @IBAction func unwindToFav(segue: UIStoryboardSegue) { } override func viewDidLoad() { super.viewDidLoad() //UIApplication.sharedApplication().statusBarStyle = .Default // let tabBarHeight = self.tabBarController!.tabBar.frame.height // con.constant = viewSquare.frame.height request(.GET, "\(serverMainUrl)/favouritesquares/\(serverId)").validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { // print("FAVOURITESQUARES \(value)") self.favouriteSquare = JSON(value) // print("FAVOURITESQUARES2 \(self.favouriteSquare[0]["_source"])") self.tableView.reloadData() } case .Failure(let error): print(error) } }//ENDREQUEST }//END VDL func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return favouriteSquare.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //let cell = FavouriteCellTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "favCell") let cell = self.tableView.dequeueReusableCellWithIdentifier("favCell", forIndexPath: indexPath) as! FavouriteCellTableViewCell // print("qwerty \(self.favouriteSquare[indexPath.row]["_source"]["lastMessageDate"])") cell.squareName.text = self.favouriteSquare[indexPath.row]["_source"]["name"].string let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let date = dateFormatter.dateFromString("\(self.favouriteSquare[indexPath.row]["_source"]["lastMessageDate"].string!)") // print(date) let newDateFormatter = NSDateFormatter() newDateFormatter.locale = NSLocale.currentLocale() newDateFormatter.dateFormat = "hh:mm (dd-MMM)" var convertedDate = newDateFormatter.stringFromDate(date!) cell.squareActive.text = "Active: \(convertedDate)" //cell.goInSquare(cell) cell.tapped = { [unowned self] (selectedCell) -> Void in let path = tableView.indexPathForRowAtPoint(selectedCell.center)! let selectedSquare = self.favouriteSquare[path.row] // print("the selected item is \(selectedSquare)") self.squareId = selectedSquare["_id"].string! self.squareName = selectedSquare["_source"]["name"].string! let coordinates = selectedSquare["_source"]["geo_loc"].string!.componentsSeparatedByString(",") let latitude = (coordinates[0] as NSString).doubleValue let longitude = (coordinates[1] as NSString).doubleValue self.squareLatitude = latitude self.squareLongitude = longitude self.performSegueWithIdentifier("chatFromFav", sender: self) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let indexPath = tableView.indexPathForSelectedRow let currentCell = tableView.cellForRowAtIndexPath(indexPath!)! as! FavouriteCellTableViewCell let selectedSquare = self.favouriteSquare[indexPath!.row] //let path = tableView.indexPathForRowAtPoint(selectedCell.center)! print("the selected item is \(selectedSquare)") self.squareId = selectedSquare["_id"].string! self.squareName = selectedSquare["_source"]["name"].string! let coordinates = selectedSquare["_source"]["geo_loc"].string!.componentsSeparatedByString(",") let latitude = (coordinates[0] as NSString).doubleValue let longitude = (coordinates[1] as NSString).doubleValue self.squareLatitude = latitude self.squareLongitude = longitude self.performSegueWithIdentifier("chatFromFav", sender: self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //inutile? //updateFavouriteSquares() //viewDidLoad() request(.GET, "\(serverMainUrl)/favouritesquares/\(serverId)").validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { // print("FAVOURITESQUARES \(value)") self.favouriteSquare = JSON(value) // print("FAVOURITESQUARES2 \(self.favouriteSquare[0]["_source"])") self.tableView.reloadData() } case .Failure(let error): print(error) } }//ENDREQUEST } // override func viewDidAppear(animated: Bool) { // super.viewDidAppear(animated) // // //inutile? // tableView.reloadData() // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }//END DRMW override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if (segue.identifier == "chatFromFav") { //Checking identifier is crucial as there might be multiple // segues attached to same view print("chatFromFav") print(squareId) print(squareName) print(squareLatitude) print(squareLongitude) //var detailVC = segue!.destinationViewController as! SquareMessViewController //var detailVC = segue!.destinationViewController as! NavigationToJSQViewController // let detailVC = detailNC.topViewController as! inSquareViewController let navVC = segue.destinationViewController as! UINavigationController let detailVC = navVC.viewControllers.first as! SquareMessViewController detailVC.viewControllerNavigatedFrom = segue.sourceViewController detailVC.squareName = self.squareName detailVC.squareId = self.squareId detailVC.squareLatitude = self.squareLatitude detailVC.squareLongitude = self.squareLongitude } } }// END VC
mit
ted005/OS-X-Menu
EasyCalendar/EasyCalendarTests/EasyCalendarTests.swift
1
908
// // EasyCalendarTests.swift // EasyCalendarTests // // Created by Robbie on 15/5/6. // Copyright (c) 2015年 Ted Wei. All rights reserved. // import Cocoa import XCTest class EasyCalendarTests: 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
test/DebugInfo/mangling.swift
11
1925
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // Type: // Swift.Dictionary<Swift.Int64, Swift.String> func markUsed<T>(_ t: T) {} // Variable: // mangling.myDict : Swift.Dictionary<Swift.Int64, Swift.String> // CHECK: !DIGlobalVariable(name: "myDict", // CHECK-SAME: linkageName: "$s8mangling6myDictSDys5Int64VSSGvp", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[DT:[0-9]+]] // CHECK: ![[DT]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Dictionary" var myDict = Dictionary<Int64, String>() myDict[12] = "Hello!" // mangling.myTuple1 : (Name : Swift.String, Id : Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple1", // CHECK-SAME: linkageName: "$s8mangling8myTuple1SS4Name_s5Int64V2Idtvp", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT1:[0-9]+]] // CHECK: ![[TT1]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSS4Name_s5Int64V2IdtD" var myTuple1 : (Name: String, Id: Int64) = ("A", 1) // mangling.myTuple2 : (Swift.String, Id : Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple2", // CHECK-SAME: linkageName: "$s8mangling8myTuple2SS_s5Int64V2Idtvp", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT2:[0-9]+]] // CHECK: ![[TT2]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSS_s5Int64V2IdtD" var myTuple2 : ( String, Id: Int64) = ("B", 2) // mangling.myTuple3 : (Swift.String, Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple3", // CHECK-SAME: linkageName: "$s8mangling8myTuple3SS_s5Int64Vtvp", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT3:[0-9]+]] // CHECK: ![[TT3]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSS_s5Int64VtD" var myTuple3 : ( String, Int64) = ("C", 3) markUsed(myTuple1.Id) markUsed(myTuple2.Id) markUsed({ $0.1 }(myTuple3))
apache-2.0
austinzheng/swift
validation-test/compiler_crashers_fixed/26876-swift-inflightdiagnostic.swift
65
486
// 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 // RUN: not %target-swift-frontend %s -typecheck struct S<T where g:T{struct A{ func b{}var _={ """"[ struct{}f typealias{protocol A){b{
apache-2.0
ishkawa/DIKit
Tests/DIGenKitTests/Example/ABCDTests.swift
1
2084
// // Tests.swift // dikitgenTests // // Created by Yosuke Ishikawa on 2017/09/16. // import XCTest import DIGenKit import DIKit struct A: Injectable { struct Dependency {} init(dependency: Dependency) {} } struct B: Injectable { struct Dependency { let ba: A } init(dependency: Dependency) {} } struct C: FactoryMethodInjectable { struct Dependency { let ca: A let cd: D } static func makeInstance(dependency: C.Dependency) -> C { return C() } } struct D {} class E: PropertyInjectable { struct Dependency { let ea: A let ec: C let eb: B } var dependency: Dependency! } protocol ABCDResolver: DIKit.Resolver { func provideD() -> D } final class ABCDTests: XCTestCase { func test() throws { let generator = try CodeGenerator(path: #file) let contents = try generator.generate().trimmingCharacters(in: .whitespacesAndNewlines) XCTAssertEqual(contents, """ // // Resolver.swift // Generated by dikitgen. // import DIGenKit import DIKit import XCTest extension ABCDResolver { func injectToE(_ e: E) -> Void { let a = resolveA() let c = resolveC() let b = resolveB() e.dependency = E.Dependency(ea: a, ec: c, eb: b) } func resolveA() -> A { return A(dependency: .init()) } func resolveB() -> B { let a = resolveA() return B(dependency: .init(ba: a)) } func resolveC() -> C { let a = resolveA() let d = resolveD() return C.makeInstance(dependency: .init(ca: a, cd: d)) } func resolveD() -> D { return provideD() } } """) } }
mit
Rawrcoon/Twinkle
Twinkle/Twinkle/AppDelegate.swift
3
1852
// // AppDelegate.swift // // Created by patrick piemonte on 2/20/15. // // The MIT License (MIT) // // Copyright (c) 2015-present patrick piemonte (http://patrickpiemonte.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // MARK: UIApplicationDelegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow(frame:UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor(red: 26/255, green: 205/255, blue: 146/255, alpha: 1) self.window!.rootViewController = ViewController() self.window!.makeKeyAndVisible() return true } }
mit
cnbin/MarkdownTextView
MarkdownTextView/MarkdownHeaderHighlighter.swift
1
1286
// // MarkdownHeaderHighlighter.swift // MarkdownTextView // // Created by Indragie on 4/29/15. // Copyright (c) 2015 Indragie Karunaratne. All rights reserved. // import UIKit /** * Highlights atx-style Markdown headers. */ public final class MarkdownHeaderHighlighter: HighlighterType { // From markdown.pl v1.0.1 <http://daringfireball.net/projects/markdown/> private static let HeaderRegex = regexFromPattern("^(\\#{1,6})[ \t]*(?:.+?)[ \t]*\\#*\n+") private let attributes: MarkdownAttributes.HeaderAttributes /** Creates a new instance of the receiver. :param: attributes Attributes to apply to Markdown headers. :returns: An initialized instance of the receiver. */ public init(attributes: MarkdownAttributes.HeaderAttributes) { self.attributes = attributes } // MARK: HighlighterType public func highlightAttributedString(attributedString: NSMutableAttributedString) { enumerateMatches(self.dynamicType.HeaderRegex, attributedString.string) { let level = $0.rangeAtIndex(1).length if let attributes = self.attributes.attributesForHeaderLevel(level) { attributedString.addAttributes(attributes, range: $0.range) } } } }
mit
avito-tech/Marshroute
Marshroute/Sources/Utilities/PrintUtiliites/MarshroutePrintPlugin.swift
1
376
public protocol MarshroutePrintPlugin: AnyObject { func print(_ item: Any, separator: String, terminator: String) } public final class DefaultMarshroutePrintPlugin: MarshroutePrintPlugin { public init() {} public func print(_ item: Any, separator: String, terminator: String) { Swift.print(item, separator: separator, terminator: terminator) } }
mit
aslanyanhaik/Quick-Chat
QuickChat/Services/AudioService.swift
1
1450
// MIT License // Copyright (c) 2019 Haik Aslanyan // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import AudioToolbox class AudioService { func playSound() { var soundID: SystemSoundID = 0 let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "newMessage", ofType: "wav")!) AudioServicesCreateSystemSoundID(soundURL, &soundID) AudioServicesPlaySystemSound(soundID) } }
mit
PureSwift/Bluetooth
Sources/BluetoothGATT/GATTAnalog.swift
1
1243
// // GATTAnalog.swift // Bluetooth // // Created by Carlos Duclos on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /** Analog The Analog characteristic is used to read or write the value of one of the IO Module’s analog signals. - SeeAlso: [Analog](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.analog.xml) */ @frozen public struct GATTAnalog: GATTCharacteristic, Equatable, Hashable { internal static let length = MemoryLayout<UInt16>.size public static var uuid: BluetoothUUID { return .analog} public var analog: UInt16 public init(analog: UInt16) { self.analog = analog } public init?(data: Data) { guard data.count == type(of: self).length else { return nil } self.init(analog: UInt16(littleEndian: UInt16(bytes: (data[0], data[1])))) } public var data: Data { let bytes = analog.littleEndian.bytes return Data([bytes.0, bytes.1]) } } extension GATTAnalog: CustomStringConvertible { public var description: String { return analog.description } }
mit
tardieu/swift
validation-test/compiler_crashers_fixed/25420-swift-expr-walk.swift
65
454
// 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 // RUN: not %target-swift-frontend %s -typecheck func a} class a class B:a{ struct d{ class A{{ }let l=0
apache-2.0
auth0/Lock.swift
Lock/Style.swift
1
6686
// Style.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit /** * Define Auth0 Lock style and allows to customise it. */ public struct Style { /// Title used in Header public var title = "Auth0".i18n(key: "com.auth0.lock.header.default_title", comment: "Header Title") /// Primary color of Lock used in the principal components like the Primary Button public var primaryColor = UIColor.a0_orange /// Lock background color public var backgroundColor = UIColor.white /// Lock background image public var backgroundImage: UIImage? /// Lock disabled component color public var disabledColor = UIColor(red: 0.8902, green: 0.898, blue: 0.9059, alpha: 1.0) /// Lock disabled component text color public var disabledTextColor = UIColor(red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0) // #929495 /// Primary button tint color public var buttonTintColor = UIColor.white /// Header background color. By default it has no color but a blur public var headerColor: UIColor? /// Blur effect style used. It can be any value defined in `UIBlurEffectStyle` public var headerBlur: A0BlurEffectStyle = .light /// Header close button image public var headerCloseIcon: UIImage? = UIImage(named: "ic_close", in: bundleForLock()) /// Header back button image public var headerBackIcon: UIImage? = UIImage(named: "ic_back", in: bundleForLock()) /// Header title color public var titleColor = UIColor.black /// Hide header title (show only logo). By default is false public var hideTitle = false { didSet { hideButtonTitle = false } } /// Main body text color public var textColor = UIColor.black /// Hide primary button title (show only icon). By default is false public var hideButtonTitle = false /// Header logo image public var logo: UIImage? = UIImage(named: "ic_auth0", in: bundleForLock()) /// OAuth2 custom connection styles by mapping a connection name with an `AuthStyle` public var oauth2: [String: AuthStyle] = [:] /// Social seperator label public var seperatorTextColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.54) /// Input field text color public var inputTextColor = UIColor.black /// Input field placeholder text color public var inputPlaceholderTextColor = UIColor(red: 0.780, green: 0.780, blue: 0.804, alpha: 1.00) // #C7C7CD /// Input field border color default public var inputBorderColor = UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0) /// Input field border color invalid public var inputBorderColorError = UIColor.red /// Input field background color public var inputBackgroundColor = UIColor.white /// Input field icon background color public var inputIconBackgroundColor = UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0) /// Input field icon color public var inputIconColor = UIColor(red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0) // #929495 /// Password rule text color default public var ruleTextColor = UIColor(red: 0.016, green: 0.016, blue: 0.016, alpha: 1.0) /// Password rule text color valid public var ruleTextColorSuccess = UIColor(red: 0.502, green: 0.820, blue: 0.208, alpha: 1.0) /// Password rule text color invalid public var ruleTextColorError = UIColor(red: 0.745, green: 0.271, blue: 0.153, alpha: 1.0) /// Secondary button color public var secondaryButtonColor = UIColor.black /// Terms of Use and Privacy Policy button color public var termsButtonColor = UIColor(red: 0.9333, green: 0.9333, blue: 0.9333, alpha: 1.0) /// Terms of Use and Privacy Policy button title color public var termsButtonTitleColor = UIColor.black /// Database login Tab Text Color public var tabTextColor = UIColor(red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0) // #929495 /// Database login selected Tab Text Color public var selectedTabTextColor = UIColor.black /// Database login Tab Tint Color public var tabTintColor = UIColor.black /// Lock Controller Status bar update animation public var statusBarUpdateAnimation: UIStatusBarAnimation = .none /// Lock Controller Status bar hidden public var statusBarHidden = false /// Lock Controller Status bar style public var statusBarStyle: UIStatusBarStyle = .default /// Passwordless search bar style public var searchBarStyle: A0SearchBarStyle = .default /// iPad Modal Presentation Style public var modalPopup = true var headerMask: UIImage? { let image = self.logo if Style.Auth0.logo == image { return image?.withRenderingMode(.alwaysTemplate) } return image } func primaryButtonColor(forState state: A0ControlState) -> UIColor { if state.contains(.highlighted) { return self.primaryColor.a0_darker(0.20) } if state.contains(.disabled) { return self.disabledColor } return self.primaryColor } func primaryButtonTintColor(forState state: A0ControlState) -> UIColor { if state.contains(.disabled) { return self.disabledTextColor } return self.buttonTintColor } static let Auth0 = Style() } protocol Stylable { func apply(style: Style) }
mit
sweetmans/SMInstagramPhotoPicker
SMInstagramPhotoPicker/Classes/SMPhotoPickerLibraryView+CollectionViewDelegate.swift
2
3627
// // SMPhotoPickerLibraryView+CollectionViewDelegate.swift // SMInstagramPhotosPicker // // Created by MacBook Pro on 2017/4/18. // Copyright © 2017年 Sweetman, Inc. All rights reserved. // import Foundation import UIKit import Photos extension SMPhotoPickerLibraryView { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SMPhotoPickerImageCell", for: indexPath) as! SMPhotoPickerImageCell let asset = self.images[(indexPath as NSIndexPath).item] PHImageManager.default().requestImage(for: asset, targetSize: cellSize, contentMode: .aspectFill, options: nil) { (image, info) in cell.image = image } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images == nil ? 0 : images.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { let width = (collectionView.frame.width - 3) / 4.00 //print("Cell Width", width, collectionView.frame.width) return CGSize(width: width, height: width) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let asset = images[(indexPath as NSIndexPath).row] currentAsset = asset isOnDownloadingImage = true let targetSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) //print(asset.sourceType) if currentImageRequestID != nil { //print("cancel loading image from icloud. ID:\(self.currentImageRequestID!)") PHImageManager.default().cancelImageRequest(self.currentImageRequestID!) } progressView.isHidden = true let op = PHImageRequestOptions() op.isNetworkAccessAllowed = true op.progressHandler = {(progress, err, pointer, info) in DispatchQueue.main.async { if self.progressView.isHidden { self.progressView.isHidden = false } self.progressView.progress = CGFloat(progress) if progress == 1.0 { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.3, execute: { self.progressView.progress = 0.0 self.progressView.isHidden = true }) } } //print(progress) } DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { self.currentImageRequestID = PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: op) { (image, info) in if let isInCloud = info?[PHImageResultIsInCloudKey] as? Bool { self.isOnDownloadingImage = isInCloud } if image != nil { //self.isOnDownloadingImage = false DispatchQueue.main.async { self.setupFirstLoadingImageAttrabute(image: image!) } } } } } }
mit
EZ-NET/ESSwim
Sources/Function/Collection.swift
1
3245
// // Collection.swift // ESSwim // // Created by Tomohiro Kumagai on H27/04/24. // // extension CollectionType { /** Returns the first index where `predicate` become true in `domain` or `nil` if `value` is not found. */ public func indexOf(predicate:(Generator.Element) -> Bool) -> Index? { let predicateWithIndex = { index in predicate(self[index]) ? Optional(index) : nil } return self.indices.traverse(predicateWithIndex) } /// Make indexes of `domain` by distances. public func indexesOf(distances:[Index.Distance]) -> [Index] { let start = self.startIndex let indexes = distances.map { advance(start, $0, self)! } return indexes } /// Get filtered Array by exclude the `indexes`. public func filter(excludeIndexes indexes:[Index]) -> [Generator.Element] { var result = Array<Generator.Element>() for index in self.indices { if !indexes.contains(index) { result.append(self[index]) } } return result } } extension CollectionType where Index.Distance : IntegerType { // Make indexes of `domain` to meet `predicate`. public func indexesOf(@noescape predicate:(Generator.Element) -> Bool) -> [Index] { typealias Distance = Index.Distance var distances = Array<Distance>() for element in self.enumerate() { if predicate(element.1) { let index = Distance(element.0.toIntMax()) distances.append(index) } } return self.indexesOf(distances) } } extension CollectionType where Generator.Element : Equatable { /// Get elements that same element appeared more than once. public func elementsAppearedDupplicately() -> [Generator.Element] { typealias Element = Generator.Element typealias Elements = [Element] var _exists = Elements() var _dupplicated = Elements() let appendToResults:(Element) -> Void = { if !_dupplicated.contains($0) { _dupplicated.append($0) } } let isElementDupplicated:(Element)->Bool = { if _exists.contains($0) { return true } else { _exists.append($0) return false } } for element in self { if isElementDupplicated(element) { appendToResults(element) } } return _dupplicated } /// Get an Array that has distinct elements. /// If same element found, leaved the first element only. public func distinct() -> [Generator.Element] { typealias Element = Generator.Element typealias Elements = [Element] var results = Elements() for element in self { if !results.contains(element) { results.append(element) } } return results } } extension RangeReplaceableCollectionType where Index.Distance : SignedIntegerType { /// Remove elements at `indexes` from `domain`. public mutating func remove(indexes:[Index]) { let comparator:(Index, Index) -> Bool = { compareIndex($0, $1).isAscending } for index in indexes.distinct().sort(comparator).reverse() { self.removeAtIndex(index) } } } extension CollectionType where Generator.Element : ExistenceDeterminationable { public func existingElements() -> [Generator.Element] { return self.filter { $0.isExists } } }
mit
tianbinbin/DouYuShow
DouYuShow/DouYuShow/Classes/Main/View/PageTitleView.swift
1
6099
// // PageTitleView.swift // DouYuShow // // Created by 田彬彬 on 2017/5/30. // Copyright © 2017年 田彬彬. All rights reserved. // import UIKit private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85) // 灰色 private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0) // 橘色 //协议代理 protocol PageTitleViewDelegate:class{ // selectindex index selectindex 作为外部参数 index 作为内部参数 func pageTitle(titleView:PageTitleView,selectindex index:Int) } class PageTitleView: UIView { // mark: 定义属性 fileprivate var titles : [String] fileprivate var currentIndex:Int = 0 weak var delegate : PageTitleViewDelegate? // mark: 懒加载属性 fileprivate lazy var titlelabels:[UILabel] = [UILabel]() fileprivate lazy var scrollView:UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.isPagingEnabled = false scrollView.bounces = false return scrollView }() // 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) //1.设置UI界面 SetUPUI() } // 重写 init 构造函数一定要实现这个方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView { fileprivate func SetUPUI(){ // 1.添加scrollView addSubview(scrollView) scrollView.frame = bounds // 2.添加label SetUpTitleLabels() // 3.设置底线和滚动的滑块 SetUpBootomlineAndScrollLine() } private func SetUpTitleLabels(){ let labelW:CGFloat = frame.width/CGFloat(titles.count) let labelH:CGFloat = frame.height - kScrollLineH let labelY:CGFloat = 0 for (index,title) in titles.enumerated() { // 1.创建lb let label = UILabel() label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 16) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2 ) label.textAlignment = .center let labelX:CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) scrollView.addSubview(label) titlelabels.append(label) // 2.给lb添加手势 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titltLabelClick(_:))) label.addGestureRecognizer(tapGes) } } private func SetUpBootomlineAndScrollLine(){ //1.添加底线 let bootomLine = UIView() bootomLine.backgroundColor = UIColor.lightGray let lineH:CGFloat = 0.5 bootomLine.frame = CGRect(x: 0, y: frame.height-lineH, width: frame.width, height: lineH) addSubview(bootomLine) //2.添加滚动的线 //2.1 获取第一个lable guard let firstlabel = titlelabels.first else { return } firstlabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) //2.2 设置ScrollLine的属性 scrollView.addSubview(ScrollLine) ScrollLine.frame = CGRect(x: firstlabel.frame.origin.x, y: frame.height-kScrollLineH, width: firstlabel.frame.width, height: kScrollLineH) } } extension PageTitleView{ @objc fileprivate func titltLabelClick(_ tapGes:UITapGestureRecognizer){ //1. 获取当前label 的 下标值 guard let currentlb = tapGes.view as? UILabel else { return } //2. 获取之前的lb let olderLabel = titlelabels[currentIndex] //3. 保存最新lb的下标值 currentIndex = currentlb.tag //4. 切换文字的颜色 currentlb.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) olderLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2 ) //5. 滚动条的位置发生改变 let scrollLinePosition = CGFloat(currentlb.tag) * ScrollLine.frame.width UIView.animate(withDuration: 0.25) { self.ScrollLine.frame.origin.x = scrollLinePosition } //6.通知代理 delegate?.pageTitle(titleView: self, selectindex: currentIndex) } } // 对外暴漏的方法 extension PageTitleView{ func SetTitleViewProgress(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.颜色渐变( 复杂 ) let colorDelta = (kSelectColor.0-kNormalColor.0,kSelectColor.1-kNormalColor.1,kSelectColor.2-kNormalColor.2) sourcelabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.0 * progress, b: kSelectColor.2 - colorDelta.0 * progress) targetlabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.0 * progress, b: kNormalColor.2 - colorDelta.0 * progress) currentIndex = targetIndex } }
mit
mono0926/MonoGenerator
Package.swift
1
204
import PackageDescription let package = Package( name: "MonoGenerator", dependencies: [ .Package(url: "git@github.com:kylef/Commander.git", majorVersion: 0), ] )
mit
panyam/SwiftHTTP
Sources/Utils/Crypto.swift
2
879
// // Crypto.swift // SwiftHTTP // // Created by Sriram Panyam on 12/27/15. // Copyright © 2015 Sriram Panyam. All rights reserved. // import Foundation import CommonCrypto extension String { func SHA1Bytes() -> NSData { let data = self.dataUsingEncoding(NSUTF8StringEncoding)! var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) CC_SHA1(data.bytes, CC_LONG(data.length), &digest) return NSData(bytes: digest, length: Int(CC_SHA1_DIGEST_LENGTH)) } func SHA1() -> String { let data = self.dataUsingEncoding(NSUTF8StringEncoding)! var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) CC_SHA1(data.bytes, CC_LONG(data.length), &digest) let hexBytes = digest.map { String(format: "%02hhx", $0) } return hexBytes.joinWithSeparator("") } }
apache-2.0
jedlewison/MockURLSession
TestApp/NetworkModel.swift
2
1522
// // NetworkModel.swift // Interceptor // // Created by Jed Lewison on 2/12/16. // Copyright © 2016 Magic App Factory. All rights reserved. // import Foundation import Alamofire class SillyNetworkModel { var requestResult: String? var error: ErrorType? func startAlamofire(url: NSURL) { Alamofire.request(NSURLRequest(URL: url)).responseString { (response) -> Void in print("*******************************", __FUNCTION__) switch response.result { case .Failure(let error): self.error = error case .Success(let value): self.requestResult = value } } } func startURLRequest(url: NSURL) { let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(NSURLRequest(URL: url)) { responses in if let data = responses.0 { self.requestResult = String(data: data, encoding: NSUTF8StringEncoding) } self.error = responses.2 } dataTask.resume() } func startURL(url: NSURL) { let dataTask = NSURLSession.sharedSession().dataTaskWithURL(url) { responses in if let data = responses.0 { self.requestResult = String(data: data, encoding: NSUTF8StringEncoding) } self.error = responses.2 } dataTask.resume() } }
mit
zmeyc/GRDB.swift
Tests/GRDBTests/DatabaseCursorTests.swift
1
2927
import XCTest #if USING_SQLCIPHER import GRDBCipher #elseif USING_CUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif class DatabaseCursorTests: GRDBTestCase { func testNextReturnsNilAfterExhaustion() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { let cursor = try Int.fetchCursor(db, "SELECT 1 WHERE 0") XCTAssert(try cursor.next() == nil) // end XCTAssert(try cursor.next() == nil) // past the end } do { let cursor = try Int.fetchCursor(db, "SELECT 1") XCTAssertEqual(try cursor.next()!, 1) XCTAssert(try cursor.next() == nil) // end XCTAssert(try cursor.next() == nil) // past the end } do { let cursor = try Int.fetchCursor(db, "SELECT 1 UNION ALL SELECT 2") XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssert(try cursor.next() == nil) // end XCTAssert(try cursor.next() == nil) // past the end } } } func testStepError() throws { let dbQueue = try makeDatabaseQueue() let customError = NSError(domain: "Custom", code: 0xDEAD) dbQueue.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError }) try dbQueue.inDatabase { db in let cursor = try Int.fetchCursor(db, "SELECT throw()") do { _ = try cursor.next() XCTFail() } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.message, "\(customError)") XCTAssertEqual(error.sql!, "SELECT throw()") XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT throw()`: \(customError)") } } } func testStepDatabaseError() throws { let dbQueue = try makeDatabaseQueue() let customError = DatabaseError(resultCode: ResultCode(rawValue: 0xDEAD), message: "custom error") dbQueue.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError }) try dbQueue.inDatabase { db in let cursor = try Int.fetchCursor(db, "SELECT throw()") do { _ = try cursor.next() XCTFail() } catch let error as DatabaseError { XCTAssertEqual(error.extendedResultCode.rawValue, 0xDEAD) XCTAssertEqual(error.message, "custom error") XCTAssertEqual(error.sql!, "SELECT throw()") XCTAssertEqual(error.description, "SQLite error 57005 with statement `SELECT throw()`: custom error") } } } }
mit
iphone4peru/ejercicios_videos_youtube
IntegracionCoreData/IntegracionCoreData/AppDelegate.swift
1
2165
// // AppDelegate.swift // IntegracionCoreData // // Created by Christian Quicano on 9/12/15. // Copyright (c) 2015 iphone4peru.com. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
gpl-2.0
apple/swift
test/attr/attr_backDeploy_evolution.swift
2
8126
// // At a high level, this test is designed to verify that use of declarations // annotated with @_backDeploy behave as expected when running a client binary // on an older OS that does not have the back deployed APIs. The // BackDeployHelper framework has a number of APIs that are available in the // OSes identified by the "BackDeploy 1.0" availability macro and are back // deployed before OSes identified "BackDeploy 2.0". Verification is performed // the following way: // // 1. Build the helper framework with both BackDeploy 1.0 defined to an // OS version before Swift ABI stability and 2.0 defined to an OS version // after Swift ABI stability. Note that stradling ABI stability is not // a necessary requirement of this test; it's just convenient to use OS // versions that correspond to existing lit substitutions. // 2. Build the client executable with a deployment target set to the same // OS version as BackDeploy 2.0. // 3. Run the client executable, verifying that the copies of the functions in // the framework are used (verified by runtime logic using #dsohandle). // 4. Build a new copy of the helper framework, this time with BackDeploy 2.0 // set to a distant future OS version. // 5. Build a new copy of the client executable using the new framework and // the deployment target set to the same OS version as BackDeploy 1.0. // 6. Run the new executable, verifying with #dsohandle that client copies of // the APIs are used. // 7. Re-build the framework in place, this time stripping the definitions of // the back deployed APIs entirely. // 8. Re-run the unmodified executable, with the same expectations as in (6). // However, this time we're also verifying that the executable can run even // without the original API symbols present in the linked dylib. // // REQUIRES: executable_test // REQUIRES: OS=macosx // The deployment targets and availability versions hardcoded into this test // aren't compatible with the environment of the back deployment CI bots. // UNSUPPORTED: back_deployment_runtime // Remote test execution does not support dynamically loaded libraries. // UNSUPPORTED: remote_run // ---- (0) Prepare SDK // RUN: %empty-directory(%t) // RUN: %empty-directory(%t/SDK_ABI) // RUN: %empty-directory(%t/SDK_BD) // ---- (1) Build framework with BackDeploy 2.0 in the past // RUN: mkdir -p %t/SDK_ABI/Frameworks/BackDeployHelper.framework/Modules/BackDeployHelper.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK_ABI/Frameworks/BackDeployHelper.framework/BackDeployHelper) \ // RUN: -emit-module-path %t/SDK_ABI/Frameworks/BackDeployHelper.framework/Modules/BackDeployHelper.swiftmodule/%module-target-triple.swiftmodule \ // RUN: -module-name BackDeployHelper -emit-module %S/Inputs/BackDeployHelper.swift \ // RUN: -target %target-cpu-apple-macosx10.15 \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 1.0:macOS 10.14.3' \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 2.0:macOS 10.15' \ // RUN: -Xlinker -install_name -Xlinker @rpath/BackDeployHelper.framework/BackDeployHelper \ // RUN: -enable-library-evolution // ---- (2) Build executable // RUN: %target-build-swift -emit-executable %s -g -o %t/test_ABI \ // RUN: -target %target-cpu-apple-macosx10.14.3 \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 1.0:macOS 10.14.3' \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 2.0:macOS 10.15' \ // RUN: -F %t/SDK_ABI/Frameworks/ -framework BackDeployHelper \ // RUN: %target-rpath(@executable_path/SDK_ABI/Frameworks) // ---- (3) Run executable // RUN: %target-codesign %t/test_ABI // RUN: %target-run %t/test_ABI | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-ABI %s // ---- (4) Build framework with BackDeploy 2.0 in the future // RUN: mkdir -p %t/SDK_BD/Frameworks/BackDeployHelper.framework/Modules/BackDeployHelper.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK_BD/Frameworks/BackDeployHelper.framework/BackDeployHelper) \ // RUN: -emit-module-path %t/SDK_BD/Frameworks/BackDeployHelper.framework/Modules/BackDeployHelper.swiftmodule/%module-target-triple.swiftmodule \ // RUN: -module-name BackDeployHelper -emit-module %S/Inputs/BackDeployHelper.swift \ // RUN: -target %target-cpu-apple-macosx10.15 \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 1.0:macOS 10.14.3' \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 2.0:macOS 999.0' \ // RUN: -Xlinker -install_name -Xlinker @rpath/BackDeployHelper.framework/BackDeployHelper \ // RUN: -enable-library-evolution // ---- (5) Build executable // RUN: %target-build-swift -emit-executable %s -g -o %t/test_BD \ // RUN: -target %target-cpu-apple-macosx10.14.3 \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 1.0:macOS 10.14.3' \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 2.0:macOS 999.0' \ // RUN: -F %t/SDK_BD/Frameworks/ -framework BackDeployHelper \ // RUN: %target-rpath(@executable_path/SDK_BD/Frameworks) // ---- (6) Run executable // RUN: %target-codesign %t/test_BD // RUN: %target-run %t/test_BD | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-BD %s // ---- (7) Re-build framework with the back deployed APIs stripped // RUN: %empty-directory(%t/SDK_BD) // RUN: mkdir -p %t/SDK_BD/Frameworks/BackDeployHelper.framework/Modules/BackDeployHelper.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK_BD/Frameworks/BackDeployHelper.framework/BackDeployHelper) \ // RUN: -emit-module-path %t/SDK_BD/Frameworks/BackDeployHelper.framework/Modules/BackDeployHelper.swiftmodule/%module-target-triple.swiftmodule \ // RUN: -module-name BackDeployHelper -emit-module %S/Inputs/BackDeployHelper.swift \ // RUN: -target %target-cpu-apple-macosx10.15 \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 1.0:macOS 10.14.3' \ // RUN: -Xfrontend -define-availability \ // RUN: -Xfrontend 'BackDeploy 2.0:macOS 999.0' \ // RUN: -Xlinker -install_name -Xlinker @rpath/BackDeployHelper.framework/BackDeployHelper \ // RUN: -enable-library-evolution -DSTRIP_V2_APIS // ---- (8) Re-run executable // RUN: %target-codesign %t/test_BD // RUN: %target-run %t/test_BD | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-BD %s import BackDeployHelper // CHECK: client: check testPrint(handle: #dsohandle, "check") // CHECK: library: check testPrint(handle: libraryHandle(), "check") if isV2OrLater() { precondition(!v2APIsAreStripped()) } // CHECK-ABI: library: trivial // CHECK-BD: client: trivial trivial() precondition(try! pleaseThrow(false)) do { _ = try pleaseThrow(true) fatalError("Should have thrown") } catch { precondition(error as? BadError == BadError.bad) } do { let empty = IntArray.empty precondition(empty.values == []) var array = IntArray([5]) // CHECK-ABI: library: [5] // CHECK-BD: client: [5] array.print() array.append(42) genericAppend(&array, 3) let countable = array.toCountable() precondition(existentialCount(countable) == 3) array[1] += 1 precondition(array[1] == 43) // CHECK-ABI: library: [5, 43, 3] // CHECK-BD: client: [5, 43, 3] array.print() // CHECK-ABI: library: [5, 43, 3] // CHECK-BD: client: [5, 43, 3] print(array.rawValues.print()) } do { let empty = ReferenceIntArray.empty precondition(empty.values == []) var array = ReferenceIntArray([7]) // CHECK-ABI: library: [7] // CHECK-BD: client: [7] array.print() do { let copy = array.copy() precondition(array !== copy) precondition(copy.values == [7]) } array.append(39) genericAppend(&array, 1) let countable = array.toCountable() precondition(existentialCount(countable) == 3) array[1] += 1 precondition(array[1] == 40) // CHECK-ABI: library: [7, 40, 1] // CHECK-BD: client: [7, 40, 1] array.print() // CHECK-ABI: library: [7, 40, 1] // CHECK-BD: client: [7, 40, 1] print(array.rawValues.print()) }
apache-2.0
apple/swift
validation-test/compiler_crashers_fixed/28579-unreachable-executed-at-swift-lib-sema-csdiag-cpp-5054.swift
65
431
// 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 // RUN: not %target-swift-frontend %s -emit-ir var f=(let{RangeReplaceableSlice(f
apache-2.0
LawrenceHan/iOS-project-playground
ShotsApp_example/ShotsApp/AppDelegate.swift
1
2103
// // AppDelegate.swift // ShotsApp // // Created by Meng To on 2014-07-29. // Copyright (c) 2014 Meng To. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { return true } func applicationWillResignActive(application: UIApplication!) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication!) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication!) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication!) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication!) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
bravelocation/daysleft
daysleft/Models/DisplayValues.swift
1
1808
// // DisplayValues.swift // DaysLeft // // Created by John Pollard on 26/09/2022. // Copyright © 2022 Brave Location Software. All rights reserved. // import Foundation /// Display values used in the UI of the app struct DisplayValues { /// Number of days left let daysLeft: Int /// Display title let title: String /// Description of days left let description: String /// Are we counting weekdays only? let weekdaysOnly: Bool /// Percenatge of the count done let percentageDone: Double /// Start date let start: Date /// End date let end: Date /// Current percentage left as a string let currentPercentageLeft: String /// Duration title used on the watch let watchDurationTitle: String /// Full title, used in shortchts etc. let fullTitle: String /// Days left description let daysLeftDescription: String /// Initialiser /// - Parameters: /// - appSettings: App settings used in initialisation /// - date: Current date - default is now init(appSettings: AppSettings, date: Date = Date()) { self.daysLeft = appSettings.daysLeft(date) self.title = appSettings.title self.weekdaysOnly = appSettings.weekdaysOnly self.description = appSettings.description(date) self.percentageDone = appSettings.percentageDone(date: date) self.start = appSettings.start self.end = appSettings.end self.currentPercentageLeft = appSettings.currentPercentageLeft(date: date) self.watchDurationTitle = appSettings.watchDurationTitle(date: date) self.fullTitle = appSettings.fullTitle(date: date) self.daysLeftDescription = appSettings.daysLeftDescription(date) } }
mit
taher-mosbah/firefox-ios
UITests/ReadingListTest.swift
3
2290
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit class ReadingListTests: KIFTestCase, UITextFieldDelegate { private var webRoot: String! override func setUp() { webRoot = SimplePageServer.start() } /** * Tests opening reader mode pages from the urlbar and reading list. */ func testReadingList() { // Load a page tester().tapViewWithAccessibilityIdentifier("url") let url1 = "\(webRoot)/readablePage.html" tester().clearTextFromAndThenEnterText("\(url1)\n", intoViewWithAccessibilityLabel: "Address and Search") tester().waitForWebViewElementWithAccessibilityLabel("Readable Page") // Add it to the reading list tester().tapViewWithAccessibilityLabel("Reader View") tester().tapViewWithAccessibilityLabel("Add to Reading List") // Open a new page tester().tapViewWithAccessibilityIdentifier("url") let url2 = "\(webRoot)/numberedPage.html?page=1" tester().clearTextFromAndThenEnterText("\(url2)\n", intoViewWithAccessibilityLabel: "Address and Search") tester().waitForWebViewElementWithAccessibilityLabel("Page 1") // Check that it appears in the reading list home panel tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Reading list") // Tap to open it tester().tapViewWithAccessibilityLabel("Readable page, unread, localhost") tester().waitForWebViewElementWithAccessibilityLabel("Readable page") // Remove it from the reading list tester().tapViewWithAccessibilityLabel("Remove from Reading List") // Check that it no longer appears in the reading list home panel tester().tapViewWithAccessibilityIdentifier("url") tester().tapViewWithAccessibilityLabel("Reading list") tester().waitForAbsenceOfViewWithAccessibilityLabel("Readable page, unread, localhost") tester().tapViewWithAccessibilityLabel("Cancel") } override func tearDown() { BrowserUtils.resetToAboutHome(tester()) } }
mpl-2.0
potatolicious/omnidash
OmnidashTests/OmnidashTests.swift
1
901
// // OmnidashTests.swift // OmnidashTests // // Created by Jerry Wong on 3/14/15. // Copyright (c) 2015 Jerry Wong. All rights reserved. // import Cocoa import XCTest class OmnidashTests: 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
ChenWeiLee/Black-Fu
Black-Fu/Black-Fu/singletonObject.swift
1
299
// // singletonObject.swift // Black-Fu // // Created by Li Chen wei on 2016/1/23. // Copyright © 2016年 TWML. All rights reserved. // import UIKit class singletonObject: NSObject { static let sharedInstance = singletonObject() var productsDic:NSArray = NSArray() }
gpl-2.0
JesusAntonioGil/Design-Patterns-Swift-2
StructuralPatterns/ProxyPattern/ProxyPatternUITests/ProxyPatternUITests.swift
1
1272
// // ProxyPatternUITests.swift // ProxyPatternUITests // // Created by Jesus Antonio Gil on 17/12/15. // Copyright © 2015 Jesus Antonio Gil. All rights reserved. // import XCTest class ProxyPatternUITests: 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
fqhuy/minimind
minimind/core/hyperbolic.swift
4
3409
// Hyperbolic.swift // // Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me) // // 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 Accelerate // MARK: Hyperbolic Sine public func sinh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvsinhf(&results, x, [Int32(x.count)]) return results } public func sinh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvsinh(&results, x, [Int32(x.count)]) return results } // MARK: Hyperbolic Cosine public func cosh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvcoshf(&results, x, [Int32(x.count)]) return results } public func cosh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvcosh(&results, x, [Int32(x.count)]) return results } // MARK: Hyperbolic Tangent public func tanh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvtanhf(&results, x, [Int32(x.count)]) return results } public func tanh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvtanh(&results, x, [Int32(x.count)]) return results } // MARK: Inverse Hyperbolic Sine public func asinh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvasinhf(&results, x, [Int32(x.count)]) return results } public func asinh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvasinh(&results, x, [Int32(x.count)]) return results } // MARK: Inverse Hyperbolic Cosine public func acosh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvacoshf(&results, x, [Int32(x.count)]) return results } public func acosh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvacosh(&results, x, [Int32(x.count)]) return results } // MARK: Inverse Hyperbolic Tangent public func atanh(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvatanhf(&results, x, [Int32(x.count)]) return results } public func atanh(_ x: [Double]) -> [Double] { var results = [Double](repeating: 0.0, count: x.count) vvatanh(&results, x, [Int32(x.count)]) return results }
mit
theMatys/myWatch
myWatch/Source/Core/myWatch.swift
1
7376
// // myWatch.swift // myWatch // // Created by Máté on 2017. 04. 09.. // Copyright © 2017. theMatys. All rights reserved. // import UIKit /// A boolean which indicates whether the application is being launched for the first time. fileprivate var firstLaunch: Bool = false /// The application's main class. class myWatch { //MARK: Instance variables /// A boolean which indicates whether debug mode should be used in the application. var debugMode: Bool = false //MARK: Static variables /// The singleton instance of the `myWatch` class. static let shared: myWatch = myWatch() //MARK: Initializers /// Required for the singleton instance. private init() {} } //MARK: - @UIApplicationMain fileprivate class MWApplicationDelegate: UIResponder, UIApplicationDelegate { //MARK: Instance variables /// The `UIWindow` of the application. /// /// Required for `UIApplicationDelegate`. var window: UIWindow? private var settings: MWSettings = MWSettings.shared //MARK: - Inherited functions from: UIApplicationDelegate internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /*if(firstLaunch) { firstLaunch() }*/ return true } internal func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } internal func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } internal func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } internal func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } internal func applicationWillTerminate(_ application: UIApplication) { MWIO.save(settings, to: MWFileLocations.settingsFile) } //MARK: Instance functions /// Determines whether the application is launched for the first time. /// /// If the application is launched for the first time, it prepares the first launch. /// /// If the application is not launched for the first time, it loads the settings and prepares a regular launch. private func firstLaunch() { //Prepare for the first launch let storyboard: UIStoryboard = UIStoryboard(name: "myWatch", bundle: Bundle(for: type(of: self))) let firstLaunchViewController: UIViewController = storyboard.instantiateViewController(withIdentifier: MWIdentifiers.ControllerIdentifiers.firstLaunchNC) self.window!.rootViewController = firstLaunchViewController } } //MARK: - /// The shared settings of the application. /// /// Written to an own settings file upon termination. /// /// Attempted to be read from the file upon lauch. /// /// The success of the reading process determines whether the application is launched for the first time. /// /// - See: `launchSetup()` in `MWApplicationDelegate`. internal class MWSettings: NSObject, NSCoding { //MARK: Instance variables /// Holds the current device that the application uses to retrieve its data. var device: MWDevice! /// Holds a boolean which determines whether the application should be exporting its data to Apple Health. var exportToAppleHealth: Bool = false //MARK: Static variables /// The (shared) singleton instance of `MWSettings`. static let shared: MWSettings = create() //MARK: - Inherited intializers fomr: NSCoding required internal init?(coder aDecoder: NSCoder) { //Decode properties self.device = aDecoder.decodeObject(forKey: PropertyKey.device) as! MWDevice self.exportToAppleHealth = aDecoder.decodeObject(forKey: PropertyKey.exportToAppleHealth) as! Bool } //MARK: Initializers /// Basic initializer for creating an empty instance for first launch. override private init() { /* No-operation */ } //MARK: Inherited functions from: NSCoding func encode(with aCoder: NSCoder) { //Encode properties aCoder.encode(device, forKey: PropertyKey.device) aCoder.encode(exportToAppleHealth, forKey: PropertyKey.exportToAppleHealth) } //MARK: Static functions /// Either creates an empty settings instance or loads the settings from a saved settings file. /// /// - Returns: An `MWSettings` instance. private static func create() -> MWSettings { //Create a default return value let ret: MWSettings = MWSettings() /*//Attempt to load the settings let loadedSettings: MWSettings? = MWIO.load(from: MWFileLocations.defaultSaveLocation) //Check whether the load was successful loadedSettings ??= { //If it was not, create the myWatch directory and settings file if(!FileManager().fileExists(atPath: MWFileLocations.defaultSaveLocation.path)) { do { try FileManager().createDirectory(atPath: MWFileLocations.defaultSaveLocation.path, withIntermediateDirectories: false, attributes: nil) } catch let error as NSError { MWLError("Unable to create myWatch directory: \(error.localizedDescription)", module: .moduleCore) } } //Set the application to first launch mode firstLaunch = true } >< { //If it was, set the settings to the loaded settings ret = loadedSettings! }*/ return ret } //MARK: - /// The structure which holds the property names used in the files to identify the properties of this object. private struct PropertyKey { //MARK: Prefixes /// The prefix of the property keys. private static let prefix: String = "MWSettings" //MARK: Property keys static let device: String = prefix + "Device" static let exportToAppleHealth: String = prefix + "ExportToAppleHealth" } }
gpl-3.0
jinMaoHuiHui/WhiteBoard
WhiteBoard/WhiteBoard/Canvas/Collection+SafeSubscript.swift
1
363
// // Collection+SafeSubscript.swift // WhiteBoard // // Created by jinmao on 2016/12/19. // Copyright © 2016年 jinmao. All rights reserved. // import Foundation extension Collection where Indices.Iterator.Element == Index { subscript (safe index: Index) -> Generator.Element? { return indices.contains(index) ? self[index] : nil } }
mit
richardpiazza/XCServerCoreData
Sources/Integration.swift
1
5376
import Foundation import CoreData import CodeQuickKit import XCServerAPI public typealias TestResult = (name: String, passed: Bool) /// ## Integration /// An Xcode Server Bot integration (run). /// "An integration is a single run of a bot. Integrations consist of building, analyzing, testing, and archiving the apps (or other software products) defined in your Xcode projects." public class Integration: NSManagedObject { public convenience init?(managedObjectContext: NSManagedObjectContext, identifier: String, bot: Bot? = nil) { self.init(managedObjectContext: managedObjectContext) self.identifier = identifier self.bot = bot self.buildResultSummary = BuildResultSummary(managedObjectContext: managedObjectContext, integration: self) self.assets = IntegrationAssets(managedObjectContext: managedObjectContext) self.issues = IntegrationIssues(managedObjectContext: managedObjectContext) } public func update(withIntegration integration: XCSIntegration) { guard let moc = self.managedObjectContext else { Log.warn("\(#function) failed; MOC is nil") return } self.revision = integration._rev self.number = integration.number as NSNumber? self.shouldClean = integration.shouldClean as NSNumber? self.currentStep = integration.currentStep.rawValue self.result = integration.result.rawValue self.queuedDate = integration.queuedDate self.startedTime = integration.startedTime self.endedTime = integration.endedTime self.duration = integration.duration as NSNumber? self.successStreak = integration.successStreak as NSNumber? if let value = integration.testHierarchy { do { self.testHierachyData = try XCServerCoreData.jsonEncoder.encode(value) } catch { Log.error(error, message: "Failed to serialze Integration.testHierarchy: \(value)") } } // Build Results Summary if let summary = integration.buildResultSummary { self.buildResultSummary?.update(withBuildResultSummary: summary) } // Assets if let assets = integration.assets { self.assets?.update(withIntegrationAssets: assets) } // Tested Devices if let devices = integration.testedDevices { for testedDevice in devices { guard let identifier = testedDevice.identifier else { continue } if let device = moc.device(withIdentifier: identifier) { self.testedDevices?.insert(device) continue } if let device = Device(managedObjectContext: moc, identifier: identifier) { device.update(withDevice: testedDevice) self.testedDevices?.insert(device) } } } // Revision Blueprint if let blueprint = integration.revisionBlueprint { for id in blueprint.repositoryIds { if let repository = moc.repository(withIdentifier: id) { repository.update(withRevisionBlueprint: blueprint, integration: self) continue } if let repository = Repository(managedObjectContext: moc, identifier: id) { repository.update(withRevisionBlueprint: blueprint, integration: self) } } } } public var integrationNumber: Int { guard let value = self.number else { return 0 } return value.intValue } public var integrationStep: IntegrationStep { guard let rawValue = self.currentStep else { return .unknown } guard let enumeration = IntegrationStep(rawValue: rawValue) else { return .unknown } return enumeration } public var integrationResult: IntegrationResult { guard let rawValue = self.result else { return .unknown } guard let enumeration = IntegrationResult(rawValue: rawValue) else { return .unknown } return enumeration } public var testResults: [TestResult] { guard let data = self.testHierachyData else { return [] } let testHierachy: XCSTestHierarchy do { testHierachy = try XCServerCoreData.jsonDecoder.decode(XCSTestHierarchy.self, from: data) } catch { Log.error(error, message: "Failed to deserialized Integration.testHierarchy") return [] } guard testHierachy.suites.count > 0 else { return [] } var results = [TestResult]() for suite in testHierachy.suites { for `class` in suite.classes { for method in `class`.methods { results.append(TestResult(name: method.name.xcServerTestMethodName, passed: !method.hasFailures)) } } } return results } }
mit
wolfmasa/JTenki
JTenki/WeatherDetail.swift
1
494
// // WeatherDetail.swift // JTenki // // Created by ICP223G on 2015/03/30. // Copyright (c) 2015年 ProjectJ. All rights reserved. // import UIKit class WeatherDetail : UIViewController { var label: String = "" var image: UIImage? = nil @IBOutlet weak var myLabel: UILabel! @IBOutlet weak var weatherImage: UIImageView! override func viewDidLoad() { myLabel.text = label if let img = image { weatherImage.image = img } } }
mit
f22x/AntialiasImageX
AntialiasImage/AntialiasImage/File.swift
1
1211
// // File.swift // AntialiasImage // // Created by xinglei on 15/9/10. // Copyright © 2015年 Zplay. All rights reserved. // import Foundation import UIKit extension UIImage { func antialiasImage() ->UIImage { // 边界距离 let border: CGFloat = 1.0 // 比原图小1px的图 let rect: CGRect = CGRectMake(border, border, size.width-2*border, size.height-2*border) // 原图 var img = UIImage() // 创造一个小1px的环境 UIGraphicsBeginImageContext(CGSizeMake(rect.size.width, rect.size.height)) // 但是画的时候是原图的范围 self.drawInRect(CGRectMake(-1, -1, size.width, size.height)) // 构建原图 img = UIGraphicsGetImageFromCurrentImageContext() // 终止画 UIGraphicsEndImageContext() // 依靠原图构建环境 UIGraphicsBeginImageContext(size) // 在原图的基础上画小1px的图 img.drawInRect(rect) // 构建小图 let antialiasImage = UIGraphicsGetImageFromCurrentImageContext() // 构建完关闭 UIGraphicsEndImageContext() // 返回这个小1px的图 return antialiasImage; } }
mit
prolificinteractive/Kumi-iOS
KumiTests/Animation/UIViewAnimationStyleTests.swift
1
980
// // TextStyleTests.swift // Kumi // // Created by Thibault Klein on 4/28/17. // Copyright © 2017 Prolific Interactive. All rights reserved. // import XCTest import Marker @testable import Kumi class UIViewAnimationStyleTests: XCTestCase { var animationStyle: UIViewAnimationStyle! override func setUp() { super.setUp() do { let animationStyleJSON = try JSONHelper.getJSON("UIViewAnimationStyle") animationStyle = UIViewAnimationStyle(json: animationStyleJSON) } catch let error { XCTFail(error.localizedDescription) } } override func tearDown() { animationStyle = nil super.tearDown() } func testCABasicAnimationStyleJSONCreation() { XCTAssertEqual(animationStyle.duration, 0.35) XCTAssertEqual(animationStyle.delay, 0.0) XCTAssertEqual(animationStyle.dampingRatio, 1.0) XCTAssertEqual(animationStyle.velocity, 0.0) } }
mit
mojidabckuu/CRUDRecord
CRUDRecord/Classes/Alamofire/Request.swift
1
13543
// // Request.swift // Pods // // Created by Vlad Gorbenko on 7/27/16. // // import Foundation import Alamofire import ApplicationSupport import ObjectMapper public extension MultipartFormData { func appendBodyPart(value: String, name: String) { if let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { self.appendBodyPart(data: data, name: name) } } func appendBodyPart<T: RawRepresentable>(value: T, name: String) { if let value = value.rawValue as? String { self.appendBodyPart(value, name: name) } } } extension Alamofire.Request { public func debugLog() -> Self { #if DEBUG debugPrint(self) #endif return self } } typealias ModelCompletion = (Response<Record.Type, NSError> -> Void) typealias ModelsCompletion = (Response<Record.Type, NSError> -> Void) extension Alamofire.Request { public static func JSONParseSerializer<Model: Record>(model: Model? = nil, options options: NSJSONReadingOptions = .AllowFragments) -> ResponseSerializer<Model, NSError> { return ResponseSerializer { request, response, data, error in let jsonResponse = JSONResponseSerializer().serializeResponse(request, response, data, error) if CRUD.Configuration.defaultConfiguration.loggingEnabled { print("JSON: \(jsonResponse)") } guard let error = jsonResponse.error else { var model: Model = Model() if var item = jsonResponse.value as? JSONObject { if CRUD.Configuration.defaultConfiguration.traitRoot { let key = Model.resourceName.lowercaseString item = (item[key] as? JSONObject) ?? item } model.attributes = item.pure } return .Success(model) } return .Failure(error) } } public static func JSONParseSerializer<Model: Record>(options options: NSJSONReadingOptions = .AllowFragments) -> ResponseSerializer<[Model], NSError> { return ResponseSerializer { request, response, data, error in let jsonResponse = JSONResponseSerializer().serializeResponse(request, response, data, error) if CRUD.Configuration.defaultConfiguration.loggingEnabled { print("JSON: \(jsonResponse)") } guard let error = jsonResponse.error else { var models: [Model] = [] if let items = jsonResponse.value as? JSONArray { models = items.map({ (json) -> Model in var model = Model() model.attributes = json.pure return model }) } else if var item = jsonResponse.value as? JSONObject { let key = Model.resourceName.pluralized.lowercaseString if let items = (item[key] as? JSONArray) where CRUD.Configuration.defaultConfiguration.traitRoot { models = items.map({ (json) -> Model in var model = Model() model.attributes = json.pure return model }) } } return .Success(models) } return .Failure(error) } } } extension Alamofire.Request { public func parseJSON<Model: Record>(queue queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: Response<[Model], NSError> -> Void) -> Self { if CRUD.Configuration.defaultConfiguration.loggingEnabled { } return self.response(queue: queue, responseSerializer: Alamofire.Request.JSONParseSerializer(options: options), completionHandler: completionHandler) } public func parseJSON<Model: Record>(queue queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (Response<Model, NSError> -> Void)) -> Self { return self.response(queue: queue, responseSerializer: Alamofire.Request.JSONParseSerializer(options: options), completionHandler: completionHandler) } public func parseJSON<Model: Record>(queue queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, model: Model, completionHandler: (Response<Model, NSError> -> Void)) -> Self { return self.response(queue: queue, responseSerializer: Alamofire.Request.JSONParseSerializer(model, options: options), completionHandler: completionHandler) } } extension Alamofire.Request { internal static func newError(code: Error.Code, failureReason: String) -> NSError { let errorDomain = "com.alamofireobjectmapper.error" let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let returnError = NSError(domain: errorDomain, code: code.rawValue, userInfo: userInfo) return returnError } public static func ObjectMapperSerializer<T: Record>(keyPath: String?, mapToObject object: T? = nil, context: MapContext? = nil, mapper: MapOf<T>? = nil) -> ResponseSerializer<T, NSError> { return ResponseSerializer { request, response, data, error in guard error == nil else { if let data = data, let string = String(data: data, encoding: NSUTF8StringEncoding) { var json = JSONParser(string).parse() as? [String: Any] if let errors = json?["errors"] as? [String: Any] where !errors.isEmpty { if let key = errors.keys.first, errorInfo = errors[key] as? [[String: Any]], message = errorInfo.first?["message"] as? String { let info = [NSLocalizedDescriptionKey: message] let error = NSError(domain: "com.json.ahahah", code: 0, userInfo: info) return .Failure(error) } } } return .Failure(error!) } guard let _ = data else { let failureReason = "Data could not be serialized. Input data was nil." let error = newError(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } var OriginalJSONToMap: [String: Any]? if let data = data { if let string = String(data: data, encoding: NSUTF8StringEncoding) { OriginalJSONToMap = JSONParser(string).parse() as? [String: Any] } } CRUDLog.warning("Response: \(response?.statusCode) : \n" + "\(OriginalJSONToMap)") let JSONToMap: Any? if var keyPath = keyPath { if keyPath.isEmpty { keyPath = T.resourceName.pluralized.lowercaseString } JSONToMap = OriginalJSONToMap?[keyPath] } else { let resourceName = T.resourceName JSONToMap = OriginalJSONToMap?[resourceName] ?? OriginalJSONToMap } if let object = object { Mapper<T>(mapper: mapper).map(JSONToMap, toObject: object) return .Success(object) } else if let parsedObject = Mapper<T>(context: context, mapper: mapper).map(JSONToMap){ return .Success(parsedObject) } let failureReason = "ObjectMapper failed to serialize response." let error = newError(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } } /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter keyPath: The key path where object mapping should be performed - parameter object: An object to perform the mapping on to - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper. - returns: The request. */ public func responseObject<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, mapToObject object: T? = nil, mapper: MapOf<T>? = nil, context: MapContext? = nil, completionHandler: Response<T, NSError> -> Void) -> Self { return response(queue: queue, responseSerializer: Alamofire.Request.ObjectMapperSerializer(keyPath, mapToObject: object, context: context), completionHandler: completionHandler) } public static func ObjectMapperArraySerializer<T: Record>(keyPath: String?, context: MapContext? = nil, mapper: MapOf<T>? = nil) -> ResponseSerializer<[T], NSError> { return ResponseSerializer { request, response, data, error in guard error == nil else { if let data = data, let string = String(data: data, encoding: NSUTF8StringEncoding) { var json = JSONParser(string).parse() as? [String: Any] if let errors = json?["errors"] as? [String: Any] where !errors.isEmpty { if let key = errors.keys.first, errorInfo = errors[key] as? [[String: Any]], message = errorInfo.first?["message"] as? String { let info = [NSLocalizedDescriptionKey: message] let error = NSError(domain: "com.json.ahahah", code: 0, userInfo: info) return .Failure(error) } } } return .Failure(error!) } guard let _ = data else { let failureReason = "Data could not be serialized. Input data was nil." let error = newError(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } var OriginalJSONToMap: [[String: Any]] = [] if let data = data { if let string = String(data: data, encoding: NSUTF8StringEncoding) { let json = JSONParser(string).parse() if let object = json as? [String: Any] { if var keyPath = keyPath { if keyPath.isEmpty { keyPath = T.resourceName.pluralized.lowercaseString } OriginalJSONToMap = (object[keyPath] as? [[String: Any]]) ?? [] } else { let resourceName = T.resourceName.pluralized.lowercaseString OriginalJSONToMap = (object[resourceName] as? [[String: Any]]) ?? object as? [[String: Any]] ?? [] } } else { OriginalJSONToMap = (json as? [[String: Any]]) ?? [] } } } CRUDLog.warning("Response: \(response?.statusCode) : \n" + "\(OriginalJSONToMap)") if let parsedObject = Mapper<T>(context: context, mapper: mapper).mapArray(OriginalJSONToMap){ return .Success(parsedObject) } let failureReason = "ObjectMapper failed to serialize response." let error = newError(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } } /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter keyPath: The key path where object mapping should be performed - parameter completionHandler: A closure to be executed once the request has finished and the data has been mapped by ObjectMapper. - returns: The request. */ public func responseArray<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, completionHandler: Response<[T], NSError> -> Void) -> Self { return response(queue: queue, responseSerializer: Request.ObjectMapperArraySerializer(keyPath, context: context), completionHandler: completionHandler) } // Map utils public func map<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, completionHandler: Response<[T], NSError> -> Void) -> Self { return self.responseArray(queue: queue, keyPath: keyPath, context: context, completionHandler: completionHandler) } public func map<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, mapper: MapOf<T>? = nil, completionHandler: Response<T, NSError> -> Void) -> Self { return self.responseObject(queue: queue, keyPath: keyPath, context: context, completionHandler: completionHandler) } public func map<T: Record>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, context: MapContext? = nil, object: T, completionHandler: Response<T, NSError> -> Void) -> Self { return self.responseObject(queue: queue, keyPath: keyPath, mapToObject: object, context: context, completionHandler: completionHandler) } }
mit
orcudy/archive
ios/razzle/map-view/COMapView/COMapView.swift
1
4980
// // MapView.swift // COMapView // // Created by Chris Orcutt on 8/23/15. // Copyright (c) 2015 Chris Orcutt. All rights reserved. // import UIKit import MapKit import AddressBook class COMapView: UIView { @IBOutlet var view: UIView! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var footerView: UIView! @IBOutlet weak var footerLabel: UILabel! // MARK: MapViewProperties var annotation: MKPointAnnotation? var region: MKCoordinateRegion? { didSet { if let region = region { mapView.region = region if let annotation = annotation { annotation.coordinate = region.center } else { annotation = MKPointAnnotation() annotation!.coordinate = region.center mapView.addAnnotation(annotation!) } } } } var latitude: Float? { didSet { if let latitude = latitude { mapView.region.center.latitude = CLLocationDegrees(latitude) region = mapView.region } } } var longitude: Float? { didSet { if let longitude = longitude { mapView.region.center.longitude = CLLocationDegrees(longitude) region = mapView.region } } } var span: Float? { didSet { if let span = span { mapView.region.span = MKCoordinateSpan(latitudeDelta: CLLocationDegrees(span), longitudeDelta: CLLocationDegrees(span)) region = mapView.region } } } //MARK: AddressBookProperties var name: String? var address = [NSObject : AnyObject]() { didSet { var text = "" if let name = name { text += "\(name)" } if let street = street { text += ", \(street)" } if let city = city { text += ", \(city)" } if let state = state { text += ", \(state)" } if let ZIP = ZIP { text += ", \(ZIP)" } if let country = country { text += ", \(country)" } footerLabel.text = text } } var street: String? { didSet { if let street = street { address[kABPersonAddressStreetKey] = street } } } var city: String? { didSet { if let city = city { address[kABPersonAddressCityKey] = city } } } var state: String? { didSet { if let state = state { address[kABPersonAddressStateKey] = state } } } var ZIP: String? { didSet { if let ZIP = ZIP { address[kABPersonAddressZIPKey] = ZIP } } } var country: String? { didSet { if let country = country { address[kABPersonAddressCountryKey] = country } } } //MARK: Initialization func baseInit() { NSBundle.mainBundle().loadNibNamed("COMapView", owner: self, options: nil) mapView.delegate = self self.footerView.layer.cornerRadius = 2 self.footerView.layer.shadowColor = UIColor.grayColor().CGColor self.footerView.layer.shadowOffset = CGSize(width: 1, height: 1) self.footerView.layer.shadowOpacity = 1 self.footerView.layer.shadowRadius = 1 self.footerView.layer.masksToBounds = false self.footerView.alpha = 0.90 self.view.frame = bounds self.addSubview(self.view) } override init(frame: CGRect) { super.init(frame: frame) baseInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) baseInit() } //MARK: MapsApp @IBAction func openMapsApp(sender: AnyObject) { if let latitude = region?.center.latitude, longitude = region?.center.longitude, name = name { let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: address) var mapItem = MKMapItem(placemark: placemark) mapItem.name = name mapItem.openInMapsWithLaunchOptions(nil) } } } //MARK: MKMapViewDelegate extension COMapView: MKMapViewDelegate { func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { var annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "custom") annotationView.image = UIImage(named: "Marker") return annotationView } }
gpl-3.0
natecook1000/swift
validation-test/Reflection/reflect_Int32.swift
1
1863
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Int32 // RUN: %target-codesign %t/reflect_Int32 // Link %target-swift-reflection-test into %t to convince %target-run to copy // it. // RUN: ln -s %target-swift-reflection-test %t/swift-reflection-test // RUN: %target-run %t/swift-reflection-test %t/reflect_Int32 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test // FIXME: Handle different forms of %target-run more robustly // REQUIRES: OS=macosx import SwiftReflectionTest class TestClass { var t: Int32 init(t: Int32) { self.t = t } } var obj = TestClass(t: 123) reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_Int32.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 // CHECK-64: (field name=t offset=16 // CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_Int32.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=12 alignment=4 stride=12 num_extra_inhabitants=0 // CHECK-32: (field name=t offset=8 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
Mobilette/MobiletteFoundation
MBRouterProtocol/MBRouterProtocol/ViewController.swift
1
529
// // ViewController.swift // MBRouterProtocol // // Created by Romain ASNAR on 19/11/15. // Copyright © 2015 Romain ASNAR. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let userRouter = UserRouter.create(["test": 42]) print(userRouter.URLRequest) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
fgengine/quickly
Quickly/Compositions/Standart/QImageTitleDetailComposition.swift
1
5456
// // Quickly // open class QImageTitleDetailComposable : QComposable { public var imageStyle: QImageViewStyleSheet public var imageWidth: CGFloat public var imageSpacing: CGFloat public var titleStyle: QLabelStyleSheet public var titleSpacing: CGFloat public var detailStyle: QLabelStyleSheet public init( edgeInsets: UIEdgeInsets = UIEdgeInsets.zero, imageStyle: QImageViewStyleSheet, imageWidth: CGFloat = 96, imageSpacing: CGFloat = 4, titleStyle: QLabelStyleSheet, titleSpacing: CGFloat = 4, detailStyle: QLabelStyleSheet ) { self.imageStyle = imageStyle self.imageWidth = imageWidth self.imageSpacing = imageSpacing self.titleStyle = titleStyle self.titleSpacing = titleSpacing self.detailStyle = detailStyle super.init(edgeInsets: edgeInsets) } } open class QImageTitleDetailComposition< Composable: QImageTitleDetailComposable > : QComposition< Composable > { public private(set) lazy var imageView: QImageView = { let view = QImageView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var titleView: QLabel = { let view = QLabel(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false view.setContentHuggingPriority( horizontal: UILayoutPriority(rawValue: 252), vertical: UILayoutPriority(rawValue: 252) ) self.contentView.addSubview(view) return view }() public private(set) lazy var detailView: QLabel = { let view = QLabel(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() private var _edgeInsets: UIEdgeInsets? private var _imageSpacing: CGFloat? private var _titleSpacing: CGFloat? private var _imageWidth: CGFloat? private var _constraints: [NSLayoutConstraint] = [] { willSet { self.contentView.removeConstraints(self._constraints) } didSet { self.contentView.addConstraints(self._constraints) } } private var _imageConstraints: [NSLayoutConstraint] = [] { willSet { self.imageView.removeConstraints(self._imageConstraints) } didSet { self.imageView.addConstraints(self._imageConstraints) } } open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize { let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right) let imageSize = composable.imageStyle.size(CGSize(width: composable.imageWidth, height: availableWidth)) let titleTextSize = composable.titleStyle.size(width: availableWidth - (composable.imageWidth + composable.imageSpacing)) let detailTextSize = composable.detailStyle.size(width: availableWidth - (composable.imageWidth + composable.imageSpacing)) return CGSize( width: spec.containerSize.width, height: composable.edgeInsets.top + max(imageSize.height, titleTextSize.height + composable.titleSpacing + detailTextSize.height) + composable.edgeInsets.bottom ) } open override func preLayout(composable: Composable, spec: IQContainerSpec) { if self._edgeInsets != composable.edgeInsets || self._imageSpacing != composable.imageSpacing || self._titleSpacing != composable.titleSpacing { self._edgeInsets = composable.edgeInsets self._imageSpacing = composable.imageSpacing self._titleSpacing = composable.titleSpacing self._constraints = [ self.imageView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.imageView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left), self.imageView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.titleView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing), self.titleView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.titleView.bottomLayout <= self.detailView.topLayout.offset(-composable.titleSpacing), self.detailView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing), self.detailView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.detailView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom) ] } if self._imageWidth != composable.imageWidth { self._imageWidth = composable.imageWidth self._imageConstraints = [ self.imageView.widthLayout == composable.imageWidth ] } } open override func apply(composable: Composable, spec: IQContainerSpec) { self.imageView.apply(composable.imageStyle) self.titleView.apply(composable.titleStyle) self.detailView.apply(composable.detailStyle) } }
mit
wikimedia/wikipedia-ios
Wikipedia/Code/NotificationsCenterView.swift
1
9610
import UIKit final class NotificationsCenterView: SetupView { // MARK: - Nested Types enum EmptyOverlayStrings { static let noUnreadMessages = WMFLocalizedString("notifications-center-empty-no-messages", value: "You have no messages", comment: "Text displayed when no Notifications Center notifications are available.") static let notSubscribed = WMFLocalizedString("notifications-center-empty-not-subscribed", value: "You are not currently subscribed to any Wikipedia Notifications", comment: "Text displayed when user has not subscribed to any Wikipedia notifications.") static let checkingForNotifications = WMFLocalizedString("notifications-center-empty-checking-for-notifications", value: "Checking for notifications...", comment: "Text displayed when Notifications Center is checking for notifications.") } // MARK: - Properties lazy var collectionView: UICollectionView = { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: tableStyleLayout()) collectionView.register(NotificationsCenterCell.self, forCellWithReuseIdentifier: NotificationsCenterCell.reuseIdentifier) collectionView.alwaysBounceVertical = true collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.refreshControl = refreshControl return collectionView }() lazy var refreshControl: UIRefreshControl = { let refreshControl = UIRefreshControl() refreshControl.layer.zPosition = -100 return refreshControl }() private lazy var emptyScrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.isUserInteractionEnabled = false scrollView.showsVerticalScrollIndicator = false scrollView.contentInsetAdjustmentBehavior = .never scrollView.isHidden = true return scrollView }() private lazy var emptyOverlayStack: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.distribution = .equalSpacing stackView.alignment = .center stackView.spacing = 15 return stackView }() private lazy var emptyStateImageView: UIImageView = { let image = UIImage(named: "notifications-center-empty") let imageView = UIImageView(image: image) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFit return imageView }() private lazy var emptyOverlayHeaderLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.wmf_font(.mediumBody, compatibleWithTraitCollection: traitCollection) label.adjustsFontForContentSizeCategory = true label.textAlignment = .center label.numberOfLines = 0 return label }() private lazy var emptyOverlaySubheaderLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection) label.adjustsFontForContentSizeCategory = true label.textAlignment = .center label.numberOfLines = 0 label.isUserInteractionEnabled = true return label }() // MARK: - Lifecycle override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory { emptyOverlayHeaderLabel.font = UIFont.wmf_font(.mediumBody, compatibleWithTraitCollection: traitCollection) emptyOverlaySubheaderLabel.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection) calculatedCellHeight = nil } if previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass { calculatedCellHeight = nil } } override func layoutSubviews() { super.layoutSubviews() // If the stack view content is approaching or greater than the visible view's height, allow scrolling to read all content emptyScrollView.alwaysBounceVertical = emptyOverlayStack.bounds.height > emptyScrollView.bounds.height - 100 } // MARK: - Setup override func setup() { backgroundColor = .white wmf_addSubviewWithConstraintsToEdges(collectionView) wmf_addSubviewWithConstraintsToEdges(emptyScrollView) emptyOverlayStack.addArrangedSubview(emptyStateImageView) emptyOverlayStack.addArrangedSubview(emptyOverlayHeaderLabel) emptyOverlayStack.addArrangedSubview(emptyOverlaySubheaderLabel) emptyScrollView.addSubview(emptyOverlayStack) NSLayoutConstraint.activate([ emptyScrollView.contentLayoutGuide.widthAnchor.constraint(equalTo: emptyScrollView.frameLayoutGuide.widthAnchor), emptyScrollView.contentLayoutGuide.heightAnchor.constraint(greaterThanOrEqualTo: emptyScrollView.frameLayoutGuide.heightAnchor), emptyOverlayStack.centerXAnchor.constraint(equalTo: emptyScrollView.contentLayoutGuide.centerXAnchor), emptyOverlayStack.centerYAnchor.constraint(equalTo: emptyScrollView.contentLayoutGuide.centerYAnchor), emptyOverlayStack.topAnchor.constraint(greaterThanOrEqualTo: emptyScrollView.contentLayoutGuide.topAnchor, constant: 100), emptyOverlayStack.leadingAnchor.constraint(greaterThanOrEqualTo: emptyScrollView.contentLayoutGuide.leadingAnchor, constant: 25), emptyOverlayStack.trailingAnchor.constraint(lessThanOrEqualTo: emptyScrollView.contentLayoutGuide.trailingAnchor, constant: -25), emptyOverlayStack.bottomAnchor.constraint(lessThanOrEqualTo: emptyScrollView.contentLayoutGuide.bottomAnchor, constant: -100), emptyStateImageView.heightAnchor.constraint(equalToConstant: 185), emptyStateImageView.widthAnchor.constraint(equalToConstant: 185), emptyOverlayHeaderLabel.widthAnchor.constraint(equalTo: emptyOverlayStack.widthAnchor, multiplier: 3/4), emptyOverlaySubheaderLabel.widthAnchor.constraint(equalTo: emptyOverlayStack.widthAnchor, multiplier: 4/5) ]) } // MARK: - Public private var subheaderTapGR: UITapGestureRecognizer? func addSubheaderTapGestureRecognizer(target: Any, action: Selector) { let tap = UITapGestureRecognizer(target: target, action: action) self.subheaderTapGR = tap emptyOverlaySubheaderLabel.addGestureRecognizer(tap) } func updateEmptyVisibility(visible: Bool) { emptyScrollView.isHidden = !visible emptyScrollView.isUserInteractionEnabled = visible } func updateEmptyContent(headerText: String = "", subheaderText: String = "", subheaderAttributedString: NSAttributedString?) { emptyOverlayHeaderLabel.text = headerText if let subheaderAttributedString = subheaderAttributedString { emptyOverlaySubheaderLabel.attributedText = subheaderAttributedString subheaderTapGR?.isEnabled = true } else { emptyOverlaySubheaderLabel.text = subheaderText subheaderTapGR?.isEnabled = false } } func updateCalculatedCellHeightIfNeeded() { guard let firstCell = collectionView.visibleCells.first else { return } if self.calculatedCellHeight == nil { let calculatedCellHeight = firstCell.frame.size.height self.calculatedCellHeight = calculatedCellHeight } } // MARK: Private private var calculatedCellHeight: CGFloat? { didSet { if oldValue != calculatedCellHeight { collectionView.setCollectionViewLayout(tableStyleLayout(calculatedCellHeight: calculatedCellHeight), animated: false) } } } private func tableStyleLayout(calculatedCellHeight: CGFloat? = nil) -> UICollectionViewLayout { let heightDimension: NSCollectionLayoutDimension if let calculatedCellHeight = calculatedCellHeight { heightDimension = NSCollectionLayoutDimension.absolute(calculatedCellHeight) } else { heightDimension = NSCollectionLayoutDimension.estimated(150) } let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),heightDimension: heightDimension) let item = NSCollectionLayoutItem(layoutSize: itemSize) let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),heightDimension: heightDimension) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,subitems: [item]) let section = NSCollectionLayoutSection(group: group) let layout = UICollectionViewCompositionalLayout(section: section) return layout } } extension NotificationsCenterView: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground collectionView.backgroundColor = theme.colors.paperBackground refreshControl.tintColor = theme.colors.refreshControlTint emptyOverlayHeaderLabel.textColor = theme.colors.primaryText emptyOverlaySubheaderLabel.textColor = theme.colors.primaryText } }
mit
BBBInc/AlzPrevent-ios
researchline/MemoryDashboardTableViewCell.swift
1
407
// // MemoryDashboardTableViewCell.swift // researchline // // Created by jknam on 2015. 11. 30.. // Copyright © 2015년 bbb. All rights reserved. // import UIKit class MemoryDashboardTableViewCell: DashboardTableViewCell { override func awakeFromNib() { super.name = "Memory" super.titleLabel.text = "Memory" super.awakeFromNib() // Initialization code } }
bsd-3-clause
superk589/DereGuide
DereGuide/Common/CGSSLiveFilter.swift
2
2572
// // CGSSLiveFilter.swift // DereGuide // // Created by zzk on 16/9/5. // Copyright © 2016 zzk. All rights reserved. // import UIKit struct CGSSLiveFilter: CGSSFilter { var liveTypes: CGSSLiveTypes var eventTypes: CGSSLiveEventTypes var difficultyTypes: CGSSLiveDifficultyTypes var searchText: String = "" init(typeMask: UInt, eventMask: UInt, difficultyMask: UInt) { liveTypes = CGSSLiveTypes.init(rawValue: typeMask) eventTypes = CGSSLiveEventTypes.init(rawValue: eventMask) difficultyTypes = CGSSLiveDifficultyTypes.init(rawValue: difficultyMask) } func filter(_ list: [CGSSLive]) -> [CGSSLive] { let result = list.filter { (v: CGSSLive) -> Bool in let r1: Bool = searchText == "" ? true : { let comps = searchText.components(separatedBy: " ") for comp in comps { if comp == "" { continue } let b1 = v.name.lowercased().contains(comp.lowercased()) if b1 { continue } else { return false } } return true }() let r2: Bool = { if liveTypes.contains(v.filterType) && eventTypes.contains(v.eventFilterType) { v.difficultyTypes = difficultyTypes if difficultyTypes == .masterPlus { if v.beatmapCount == 4 { return false } } return true } return false }() return r1 && r2 } return result } func save(to path: String) { toDictionary().write(toFile: path, atomically: true) } func toDictionary() -> NSDictionary { let dict = ["typeMask": liveTypes.rawValue, "eventMask": eventTypes.rawValue, "difficultyMask": difficultyTypes.rawValue] as NSDictionary return dict } init?(fromFile path: String) { guard let dict = NSDictionary.init(contentsOfFile: path) else { return nil } guard let typeMask = dict.object(forKey: "typeMask") as? UInt, let eventMask = dict.object(forKey: "eventMask") as? UInt, let difficultyMask = dict.object(forKey: "difficultyMask") as? UInt else { return nil } self.init(typeMask: typeMask, eventMask: eventMask, difficultyMask: difficultyMask) } }
mit
mperovic/my41
Array+Extensions.swift
1
332
// // Array+Extensions.swift // my41 // // Created by Miroslav Perovic on 2.2.21.. // Copyright © 2021 iPera. All rights reserved. // import Foundation extension Array where Element: Equatable { mutating func remove(_ object: Element) { guard let index = firstIndex(of: object) else { return } remove(at: index) } }
bsd-3-clause