repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
apple/swift
stdlib/public/core/Availability.swift
6
3623
//===----------------------------------------------------------------------===// // // 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 SwiftShims /// Returns 1 if the running OS version is greater than or equal to /// major.minor.patchVersion and 0 otherwise. /// /// This is a magic entry point known to the compiler. It is called in /// generated code for API availability checking. @_semantics("availability.osversion") @_effects(readnone) public func _stdlib_isOSVersionAtLeast( _ major: Builtin.Word, _ minor: Builtin.Word, _ patch: Builtin.Word ) -> Builtin.Int1 { #if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && SWIFT_RUNTIME_OS_VERSIONING if Int(major) == 9999 { return true._value } let runningVersion = _swift_stdlib_operatingSystemVersion() let result = (runningVersion.majorVersion,runningVersion.minorVersion,runningVersion.patchVersion) >= (Int(major),Int(minor),Int(patch)) return result._value #else // FIXME: As yet, there is no obvious versioning standard for platforms other // than Darwin-based OSes, so we just assume false for now. // rdar://problem/18881232 return false._value #endif } #if os(macOS) && SWIFT_RUNTIME_OS_VERSIONING // This is a magic entry point known to the compiler. It is called in // generated code for API availability checking. @_semantics("availability.osversion") @_effects(readnone) public func _stdlib_isOSVersionAtLeastOrVariantVersionAtLeast( _ major: Builtin.Word, _ minor: Builtin.Word, _ patch: Builtin.Word, _ variantMajor: Builtin.Word, _ variantMinor: Builtin.Word, _ variantPatch: Builtin.Word ) -> Builtin.Int1 { return _stdlib_isOSVersionAtLeast(major, minor, patch) } #endif public typealias _SwiftStdlibVersion = SwiftShims._SwiftStdlibVersion /// Return true if the main executable was linked with an SDK version /// corresponding to the given Swift Stdlib release, or later. Otherwise, return /// false. /// /// This is useful to maintain compatibility with older binaries after a /// behavioral change in the stdlib. /// /// This function must not be called from inlinable code. @inline(__always) internal func _isExecutableLinkedOnOrAfter( _ stdlibVersion: _SwiftStdlibVersion ) -> Bool { #if SWIFT_RUNTIME_OS_VERSIONING return _swift_stdlib_isExecutableLinkedOnOrAfter(stdlibVersion) #else return true #endif } extension _SwiftStdlibVersion { @_alwaysEmitIntoClient public static var v5_6_0: Self { Self(_value: 0x050600) } @_alwaysEmitIntoClient public static var v5_7_0: Self { Self(_value: 0x050700) } // Note: As of now, there is no bincompat level defined for v5.8. If you need // to use this in a call to `_isExecutableLinkedOnOrAfter`, then you'll need // to define this version in the runtime. @_alwaysEmitIntoClient public static var v5_8_0: Self { Self(_value: 0x050800) } @available(SwiftStdlib 5.7, *) public static var current: Self { .v5_8_0 } } @available(SwiftStdlib 5.7, *) extension _SwiftStdlibVersion: CustomStringConvertible { @available(SwiftStdlib 5.7, *) public var description: String { let major = _value >> 16 let minor = (_value >> 8) & 0xFF let patch = _value & 0xFF return "\(major).\(minor).\(patch)" } }
apache-2.0
07a63c95b1d4f26803c67f2d930b79a6
31.348214
89
0.691416
4.021088
false
false
false
false
quran/quran-ios
Sources/BatchDownloader/Entities/DownloadBatchResponse.swift
1
2300
// // DownloadBatchResponse.swift // Quran // // Created by Mohamed Afifi on 5/14/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import Foundation import PromiseKit class DownloadResponse { let progress: QProgress var download: Download var task: NetworkSessionTask? let promise: Promise<Void> private let resolver: Resolver<Void> init(download: Download, progress: QProgress) { self.download = download self.progress = progress (promise, resolver) = Promise<Void>.pending() } func fulfill() { resolver.fulfill(()) } func reject(_ error: Error) { resolver.reject(error) } } public final class DownloadBatchResponse { weak var cancellable: NetworkResponseCancellable? let batchId: Int64 let responses: [DownloadResponse] public let progress: QProgress public let promise: Promise<Void> private let resolver: Resolver<Void> public var requests: [DownloadRequest] { responses.map(\.download.request) } init(batchId: Int64, responses: [DownloadResponse], cancellable: NetworkResponseCancellable?) { self.batchId = batchId self.responses = responses self.cancellable = cancellable (promise, resolver) = Promise<Void>.pending() progress = QProgress(totalUnitCount: Double(responses.count)) responses.forEach { progress.add(child: $0.progress, withPendingUnitCount: 1) } } public func cancel() { if promise.isPending { cancellable?.cancel(batch: self) } } func fulfill() { resolver.fulfill(()) } func reject(_ error: Error) { resolver.reject(error) } }
apache-2.0
859bf8cc7214b99736d8c287b7081380
25.436782
99
0.665652
4.414587
false
false
false
false
SwiftStudies/OysterKit
Sources/STLR/Generated/Extensions/STLR+DynamicRules.swift
1
12562
// Copyright (c) 2016, RED When Excited // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation import OysterKit fileprivate struct RecursionWrapper : Rule { var behaviour: Behaviour var annotations: RuleAnnotations var wrapped : RecursiveRule func test(with lexer: LexicalAnalyzer, for ir: IntermediateRepresentation) throws { try wrapped.test(with: lexer, for: ir) } func rule(with behaviour: Behaviour?, annotations: RuleAnnotations?) -> Rule { return RecursionWrapper(behaviour: behaviour ?? self.behaviour, annotations: annotations ?? self.annotations, wrapped: wrapped) } var shortDescription: String { return behaviour.describe(match: wrapped.description, annotatedWith: annotations) } var description: String { return behaviour.describe(match: wrapped.shortDescription, annotatedWith: annotations) } } fileprivate final class Symbol : SymbolType { let identifier : String private var expression: Rule private var baseAnnotations : RuleAnnotations private var baseKind : Behaviour.Kind static func build(for identifier: String, from grammar: STLR.Grammar, in symbolTable: SymbolTable<Symbol>) -> Symbol { let declaration = grammar[identifier] if grammar.isLeftHandRecursive(identifier: identifier){ let recursive = RecursiveRule(stubFor: Behaviour(.scanning), with: [:]) let wrapped = RecursionWrapper(behaviour: Behaviour(.scanning), annotations: [:], wrapped: recursive) return Symbol(identifier, with: wrapped, baseKind: declaration.behaviour.kind, baseAnnotations: declaration.annotations?.ruleAnnotations ?? [:]) } else { var rule = grammar[identifier].expression.rule(using: symbolTable) // Terminal rules if let terminalRule = rule as? TerminalRule, !terminalRule.annotations.isEmpty { rule = [rule].sequence } return Symbol(identifier, with: rule, baseKind: declaration.behaviour.kind, baseAnnotations: declaration.annotations?.ruleAnnotations ?? [:]) } } func resolve(from grammar:STLR.Grammar, in symbolTable: SymbolTable<Symbol>) throws { if let wrapper = expression as? RecursionWrapper { wrapper.wrapped.surrogateRule = grammar[identifier].expression.rule(using: symbolTable) } } func validate(from grammar: STLR.Grammar, in symbolTable: SymbolTable<Symbol>) throws { } init(_ identifier:String, with expression:Rule, baseKind: Behaviour.Kind, baseAnnotations:RuleAnnotations){ self.identifier = identifier self.expression = expression self.baseKind = baseKind self.baseAnnotations = baseAnnotations } func reference(with behaviour:Behaviour, and instanceAnnotations:RuleAnnotations)->Rule{ return expression.annotatedWith(baseAnnotations.merge(with: instanceAnnotations)).reference(behaviour.kind).rule(with:behaviour,annotations: nil).scan() } var rule : Rule { let behaviour = Behaviour(baseKind, cardinality: expression.behaviour.cardinality, negated: expression.behaviour.negate, lookahead: expression.behaviour.lookahead) return expression.rule(with: behaviour, annotations: baseAnnotations.merge(with: expression.annotations)) } } extension STLR.DefinedLabel { var ruleAnnotation : RuleAnnotation{ switch self { case .token: return RuleAnnotation.token case .error: return RuleAnnotation.error case .void: return RuleAnnotation.void case .transient: return RuleAnnotation.transient } } } extension STLR.Label { var ruleAnnotation : RuleAnnotation { switch self { case .customLabel(let customLabel): return RuleAnnotation.custom(label: customLabel) case .definedLabel(let definedLabel): return definedLabel.ruleAnnotation } } } extension STLR.Literal { var ruleAnnotationValue : RuleAnnotationValue { switch self { case .string(let string): return RuleAnnotationValue.string(string.stringBody) case .number(let number): return RuleAnnotationValue.int(number) case .boolean(let boolean): return RuleAnnotationValue.bool(boolean == .true) } } } extension STLR.Annotation { var ruleAnnotation : RuleAnnotation { return label.ruleAnnotation } var ruleAnnotationValue : RuleAnnotationValue { return literal?.ruleAnnotationValue ?? RuleAnnotationValue.set } } fileprivate extension Array where Element == STLR.Element { func choice(with behaviour: Behaviour, and annotations:RuleAnnotations, using symbolTable:SymbolTable<Symbol>) -> Rule { return ChoiceRule(behaviour, and: annotations, for: map({$0.rule(symbolTable: symbolTable)})) } func sequence(with behaviour: Behaviour, and annotations:RuleAnnotations, using symbolTable:SymbolTable<Symbol>) -> Rule { return SequenceRule(behaviour, and: annotations, for: map({$0.rule(symbolTable: symbolTable)})) } } fileprivate extension STLR.Element { private static func rule(for element:STLR.Element, using symbolTable:SymbolTable<Symbol>)->Rule { if let terminal = element.terminal { return terminal.rule(with: element.behaviour, and: element.annotations?.ruleAnnotations ?? [:]) } else if let identifier = element.identifier { return symbolTable[identifier].reference(with: element.behaviour, and: element.annotations?.ruleAnnotations ?? [:]) } else if let group = element.group { // if case let _STLR.Expression.element(singleElement) = group.expression { // #warning("Could this be more efficiently implemented by creating a RuleReference rather than a sequence?") // return [singleElement.rule(symbolTable: symbolTable)].sequence.rule(with: element.behaviour, annotations: element.annotations?.ruleAnnotations ?? [:]) // } else { #warning("This might be bogus, remove warning when tests pass") return [group.expression.rule(using: symbolTable)].sequence.rule(with: element.behaviour,annotations: element.annotations?.ruleAnnotations ?? [:]) // } } fatalError("Element is not a terminal, and identifier reference, or a group") } func rule(symbolTable:SymbolTable<Symbol>)->Rule { let element : STLR.Element if let token = token { element = STLR.Element(annotations: annotations?.filter({!$0.label.isToken}), group: nil, identifier: "\(token)", lookahead: lookahead, negated: negated, quantifier: quantifier, terminal: nil, transient: transient, void: void) } else { element = self } return STLR.Element.rule(for:element, using:symbolTable) } } extension STLR.CharacterSetName { var characterSet : CharacterSet { switch self { case .letter: return CharacterSet.letters case .uppercaseLetter: return CharacterSet.uppercaseLetters case .lowercaseLetter: return CharacterSet.lowercaseLetters case .alphaNumeric: return CharacterSet.alphanumerics case .decimalDigit: return CharacterSet.decimalDigits case .whitespaceOrNewline: return CharacterSet.whitespacesAndNewlines case .whitespace: return CharacterSet.whitespaces case .newline: return CharacterSet.newlines case .backslash: return CharacterSet(charactersIn: "\\") } } } extension STLR.Terminal { func rule(with behaviour:Behaviour, and annotations:RuleAnnotations)->Rule { switch self { case .regex(let regex): let regularExpression = try! NSRegularExpression(pattern: "^\(regex)", options: []) return TerminalRule(behaviour, and: annotations, for: regularExpression) case .characterRange(let characterRange): let characterSet = CharacterSet(charactersIn: characterRange[0].terminalBody.first!.unicodeScalars.first!...characterRange[1].terminalBody.first!.unicodeScalars.first!) return TerminalRule(behaviour, and: annotations, for: characterSet) case .characterSet(let characterSet): return TerminalRule(behaviour, and: annotations, for: characterSet.terminal) case .terminalString(let terminalString): return TerminalRule(behaviour, and: annotations, for: terminalString.terminal) case .endOfFile(_): return TerminalRule(behaviour, and: annotations, for: EndOfFile()) } } } fileprivate extension STLR.Expression { func rule(using symbolTable:SymbolTable<Symbol>)->Rule { switch self { case .sequence(let elements): return elements.map({ (element) -> Rule in element.rule(symbolTable: symbolTable) }).sequence case .choice(let elements): return elements.map({ (element) -> Rule in element.rule(symbolTable: symbolTable) }).choice case .element(let element): return element.rule(symbolTable: symbolTable) } } } fileprivate extension STLR.Rule { var cardinality : Cardinality { return Cardinality.one } var kind : Behaviour.Kind { if let _ = void { return .skipping } else if let _ = transient { return .scanning } else { return .structural(token: StringToken(identifier)) } } var behaviour : Behaviour { return Behaviour(kind, cardinality: cardinality, negated: false, lookahead: false) } var ruleAnnotations : RuleAnnotations { #warning("This is only required whilst legacy rules may be involved, as it is formally captured in Behaviour.Kind") let assumed : RuleAnnotations = void != nil ? [.void : .set] : transient != nil ? [.transient : .set ] : [:] return assumed.merge(with: annotations?.ruleAnnotations ?? [:]) } } public extension STLR.Grammar { /// Builds a set of `Rule`s that can be used directly at run-time in your application public var dynamicRules : [Rule] { let symbolTable = SymbolTable<Symbol>(self) do { try symbolTable.build() try symbolTable.resolve() try symbolTable.validate() } catch { fatalError("Failed to construct symbol table: \(error)") } let rootRules = rules.filter({ return self.isRoot(identifier: $0.identifier) }) if rootRules.isEmpty { guard let lastRule = rules.last else { return [] } return [ symbolTable[lastRule.identifier].rule ] } else { return rootRules.map({symbolTable[$0.identifier].rule}) } } }
bsd-2-clause
8f76dbbdd52f49243f89430e048e739e
39.262821
238
0.659847
4.930141
false
false
false
false
hACKbUSTER/UberGuide-iOS
Pods/p2.OAuth2/OAuth2/OAuth2ClientConfig.swift
2
6107
// // OAuth2ClientConfig.swift // OAuth2 // // Created by Pascal Pfiffner on 16/11/15. // Copyright © 2015 Pascal Pfiffner. All rights reserved. // import Foundation public class OAuth2ClientConfig { /// The client id. public final var clientId: String? /// The client secret, usually only needed for code grant. public final var clientSecret: String? /// The name of the client, e.g. for use during dynamic client registration. public final var clientName: String? /// The URL to authorize against. public final let authorizeURL: NSURL /// The URL where we can exchange a code for a token. public final var tokenURL: NSURL? /// Where a logo/icon for the app can be found. public final var logoURL: NSURL? /// The scope currently in use. public var scope: String? /// The redirect URL string currently in use. public var redirect: String? /// All redirect URLs passed to the initializer. public var redirectURLs: [String]? /// The receiver's access token. public var accessToken: String? /// The access token's expiry date. public var accessTokenExpiry: NSDate? /// If set to true (the default), uses a keychain-supplied access token even if no "expires_in" parameter was supplied. public var accessTokenAssumeUnexpired = true /// The receiver's long-time refresh token. public var refreshToken: String? /// The URL to register a client against. public final var registrationURL: NSURL? /// How the client communicates the client secret with the server. Defaults to ".None" if there is no secret, ".ClientSecretPost" if /// "secret_in_body" is `true` and ".ClientSecretBasic" otherwise. Interacts with the `authConfig.secretInBody` client setting. public final var endpointAuthMethod = OAuth2EndpointAuthMethod.None public init(settings: OAuth2JSON) { clientId = settings["client_id"] as? String clientSecret = settings["client_secret"] as? String clientName = settings["client_name"] as? String // authorize URL var aURL: NSURL? if let auth = settings["authorize_uri"] as? String { aURL = NSURL(string: auth) } authorizeURL = aURL ?? NSURL(string: "http://localhost")! // token, registration and logo URLs if let token = settings["token_uri"] as? String { tokenURL = NSURL(string: token) } if let registration = settings["registration_uri"] as? String { registrationURL = NSURL(string: registration) } if let logo = settings["logo_uri"] as? String { logoURL = NSURL(string: logo) } // client authentication options scope = settings["scope"] as? String if let redirs = settings["redirect_uris"] as? [String] { redirectURLs = redirs redirect = redirs.first } if let inBody = settings["secret_in_body"] as? Bool where inBody { endpointAuthMethod = .ClientSecretPost } else if nil != clientSecret { endpointAuthMethod = .ClientSecretBasic } // access token options if let assume = settings["token_assume_unexpired"] as? Bool { accessTokenAssumeUnexpired = assume } } func updateFromResponse(json: OAuth2JSON) { if let access = json["access_token"] as? String { accessToken = access } accessTokenExpiry = nil if let expires = json["expires_in"] as? NSTimeInterval { accessTokenExpiry = NSDate(timeIntervalSinceNow: expires) } else if let expires = json["expires_in"] as? String { // when parsing implicit grant from URL fragment accessTokenExpiry = NSDate(timeIntervalSinceNow: Double(expires) ?? 0.0) } if let refresh = json["refresh_token"] as? String { refreshToken = refresh } } func storableCredentialItems() -> [String: NSCoding]? { guard let clientId = clientId where !clientId.isEmpty else { return nil } var items: [String: NSCoding] = ["id": clientId] if let secret = clientSecret { items["secret"] = secret } items["endpointAuthMethod"] = endpointAuthMethod.rawValue return items } func storableTokenItems() -> [String: NSCoding]? { guard let access = accessToken where !access.isEmpty else { return nil } var items: [String: NSCoding] = ["accessToken": access] if let date = accessTokenExpiry where date == date.laterDate(NSDate()) { items["accessTokenDate"] = date } if let refresh = refreshToken where !refresh.isEmpty { items["refreshToken"] = refresh } return items } /** Updates receiver's instance variables with values found in the dictionary. Returns a list of messages that can be logged on debug. */ func updateFromStorableItems(items: [String: NSCoding]) -> [String] { var messages = [String]() if let id = items["id"] as? String { clientId = id messages.append("Found client id") } if let secret = items["secret"] as? String { clientSecret = secret messages.append("Found client secret") } if let methodName = items["endpointAuthMethod"] as? String, let method = OAuth2EndpointAuthMethod(rawValue: methodName) { endpointAuthMethod = method } if let token = items["accessToken"] as? String where !token.isEmpty { if let date = items["accessTokenDate"] as? NSDate { if date == date.laterDate(NSDate()) { messages.append("Found access token, valid until \(date)") accessTokenExpiry = date accessToken = token } else { messages.append("Found access token but it seems to have expired") } } else if accessTokenAssumeUnexpired { messages.append("Found access token but no expiration date, assuming unexpired (set `accessTokenAssumeUnexpired` to false to discard)") accessToken = token } else { messages.append("Found access token but no expiration date, discarding (set `accessTokenAssumeUnexpired` to true to still use it)") } } if let token = items["refreshToken"] as? String where !token.isEmpty { messages.append("Found refresh token") refreshToken = token } return messages } /** Forgets the configuration's client id and secret. */ public func forgetCredentials() { clientId = nil clientSecret = nil } public func forgetTokens() { accessToken = nil accessTokenExpiry = nil refreshToken = nil } }
mit
db9a5c886de7f18e207864ba5fc408fe
29.838384
139
0.702915
3.889172
false
false
false
false
ShunzhiTang/TextKitDemo
TextKitDemo/TextKitDemo/TSZLabel.swift
2
3632
// // TSZLabel.swift // TextKitDemo // // Created by Tsz on 15/10/25. // Copyright © 2015年 Tsz. All rights reserved. import UIKit class TSZLabel: UILabel { /// MARK: 重写text属性 override var text: String? { didSet{ //把文本的内容 设置给textStorage 存储 prepareTextStorage() } } //绘制内容 , 只要重写就需要自己绘制的方法 ,绘制由layoutManager override func drawTextInRect(rect: CGRect) { let range = NSMakeRange(0, textStorage.length) //绘制的textStorage 中保留的内容 layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero) } //MARK: 准备 override init(frame: CGRect) { super.init(frame: frame) prepareTextSystem() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareTextSystem() } ///准备文本系统 private func prepareTextSystem() { //根据 textKit 的 关系 布局 /** 准备 textStorage */ prepareTextStorage() //建立对象之间 的关系 textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) } ///准备文本存储的内容 private func prepareTextStorage(){ //1、使用label 自身的文字设置storage //attributedText 是UILabel的一个属性 是这个类型的 NSAttributedString , if attributedText != nil { textStorage.setAttributedString(attributedText!) }else{ textStorage.setAttributedString(NSAttributedString(string: text!)) } //2、检测 URL 的范围 if let ranges = urlRanges() { //遍历范围 设置文字字体的颜色属性 for r in ranges { textStorage.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: r) } } } /// 检测文本中url 的所有范围 private func urlRanges() -> [NSRange]? { /// 需要的正则表达式 , 这个正则表达式匹配 字母 和数字 let pattern = "[a-zA-Z]*://[a-zA-Z0-9/\\.]*" let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators) //用正则匹配url的内容 matchesInString 重复匹配多次 let results = regex.matchesInString(textStorage.string, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, textStorage.length)) // 遍历 数组 , 生成结果 var ranges = [NSRange]() //遍历得到结果 ,0 和 pattern 完全匹配的内容 1 第一个 () 的内容 for r in results { ranges.append(r.rangeAtIndex(0)) } return ranges } //更新绘制结果 override func layoutSubviews() { super.layoutSubviews() //保持容器尺寸的及时更新 // textContainer.size = bounds.size } //MARK: TextKit类的格式的懒加载 ///存储内容 ,NSTextStorage 是NSMutableAttributedString 的子类 ,保存着文本的主要信息 private lazy var textStorage = NSTextStorage() /// 负责布局 private lazy var layoutManager = NSLayoutManager() ///设置尺寸 -- 只需要在一个地方 设置 layoutSubviews private lazy var textContainer = NSTextContainer() }
mit
16984d58ad29d05c81386a0307bca212
25.504274
147
0.581425
4.56701
false
false
false
false
wwu-pi/md2-framework
de.wwu.md2.framework/res/resources/ios/lib/util/SwiftyJSON.swift
2
36463
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // 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 // MARK: - Error ///Error domain public let ErrorDomain: String! = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. :param: data The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary :param: opt The JSON serialization reading options. `.AllowFragments` by default. :param: error error The NSErrorPointer used to return the error. `nil` by default. :returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { if let object: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: opt, error: error) { self.init(object) } else { self.init(NSNull()) } } /** Creates a JSON using the object. :param: object The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. :returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] :param: jsonArray A Swift array of JSON objects :returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /** Creates a JSON from a [String: JSON] :param: jsonDictionary A Swift dictionary of JSON objects :returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { var dictionary = [String: AnyObject]() for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary) } /// Private object private var _object: AnyObject = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? /// Object in JSON public var object: AnyObject { get { return _object } set { _object = newValue switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } case let string as NSString: _type = .String case let null as NSNull: _type = .Null case let array as [AnyObject]: _type = .Array case let dictionary as [String : AnyObject]: _type = .Dictionary default: _type = .Unknown _object = NSNull() _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json public static var nullJSON: JSON { get { return JSON(NSNull()) } } } // MARK: - SequenceType extension JSON : Swift.SequenceType { /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. public var isEmpty: Bool { get { switch self.type { case .Array: return (self.object as! [AnyObject]).isEmpty case .Dictionary: return (self.object as! [String : AnyObject]).isEmpty default: return false } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { get { switch self.type { case .Array: return (self.object as! [AnyObject]).count case .Dictionary: return (self.object as! [String : AnyObject]).count default: return 0 } } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. :returns: Return a *generator* over the elements of this *sequence*. */ public func generate() -> GeneratorOf <(String, JSON)> { switch self.type { case .Array: let array_ = object as! [AnyObject] var generate_ = array_.generate() var index_: Int = 0 return GeneratorOf<(String, JSON)> { if let element_: AnyObject = generate_.next() { return ("\(index_++)", JSON(element_)) } else { return nil } } case .Dictionary: let dictionary_ = object as! [String : AnyObject] var generate_ = dictionary_.generate() return GeneratorOf<(String, JSON)> { if let (key_: String, value_: AnyObject) = generate_.next() { return (key_, JSON(value_)) } else { return nil } } default: return GeneratorOf<(String, JSON)> { return nil } } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public protocol SubscriptType {} extension Int: SubscriptType {} extension String: SubscriptType {} extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(#index: Int) -> JSON { get { if self.type != .Array { var errorResult_ = JSON.nullJSON errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return errorResult_ } let array_ = self.object as! [AnyObject] if index >= 0 && index < array_.count { return JSON(array_[index]) } var errorResult_ = JSON.nullJSON errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return errorResult_ } set { if self.type == .Array { var array_ = self.object as! [AnyObject] if array_.count > index { array_[index] = newValue.object self.object = array_ } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(#key: String) -> JSON { get { var returnJSON = JSON.nullJSON if self.type == .Dictionary { let dictionary_ = self.object as! [String : AnyObject] if let object_: AnyObject = dictionary_[key] { returnJSON = JSON(object_) } else { returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return returnJSON } set { if self.type == .Dictionary { var dictionary_ = self.object as! [String : AnyObject] dictionary_[key] = newValue.object self.object = dictionary_ } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(#sub: SubscriptType) -> JSON { get { if sub is String { return self[key:sub as! String] } else { return self[index:sub as! Int] } } set { if sub is String { self[key:sub as! String] = newValue } else { self[index:sub as! Int] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. :param: path The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] :returns: Return a json found by the path or a null json with error */ public subscript(path: [SubscriptType]) -> JSON { get { if path.count == 0 { return JSON.nullJSON } var next = self for sub in path { next = next[sub:sub] } return next } set { switch path.count { case 0: return case 1: self[sub:path[0]] = newValue default: var last = newValue var newPath = path newPath.removeLast() for sub in path.reverse() { var previousLast = self[newPath] previousLast[sub:sub] = last last = previousLast if newPath.count <= 1 { break } newPath.removeLast() } self[sub:newPath[0]] = last } } } /** Find a json in the complex data structuresby using the Int/String's array. :param: path The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] :returns: Return a json found by the path or a null json with error */ public subscript(path: SubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { var dictionary_ = [String : AnyObject]() for (key_, value) in elements { dictionary_[key_] = value } self.init(dictionary_) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(0), error: NSErrorPointer = nil) -> NSData? { return NSJSONSerialization.dataWithJSONObject(self.object, options: opt, error:error) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: if let data = self.rawData(options: opt) { return NSString(data: data, encoding: encoding) as? String } else { return nil } case .String: return (self.object as! String) case .Number: return (self.object as! NSNumber).stringValue case .Bool: return (self.object as! Bool).description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return map(self.object as! [AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.object as? [AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableArray(array: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] { var result = [Key: NewValue](minimumCapacity:source.count) for (key,value) in source { result[key] = transform(value) } return result } //Optional [String : JSON] public var dictionary: [String : JSON]? { get { if self.type == .Dictionary { return _map(self.object as! [String : AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { get { return self.dictionary ?? [:] } } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.object as? [String : AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.object.boolValue default: return nil } } set { if newValue != nil { self.object = NSNumber(bool: newValue!) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if newValue != nil { self.object = NSString(string:newValue!) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as! String case .Number: return self.object.stringValue case .Bool: return (self.object as! Bool).description default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.object as? NSNumber default: return nil } } set { self.object = newValue?.copy() ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let scanner = NSScanner(string: self.object as! String) if scanner.scanDouble(nil){ if (scanner.atEnd) { return NSNumber(double:(self.object as! NSString).doubleValue) } } return NSNumber(double: 0.0) case .Number, .Bool: return self.object as! NSNumber default: return NSNumber(double: 0.0) } } set { self.object = newValue.copy() } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return NSNull() default: return nil } } set { self.object = NSNull() } } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if newValue != nil { self.object = NSNumber(double: newValue!) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if newValue != nil { self.object = NSNumber(float: newValue!) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if newValue != nil { self.object = NSNumber(integer: newValue!) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLong: newValue!) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if newValue != nil { self.object = NSNumber(char: newValue!) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if newValue != nil { self.object = NSNumber(unsignedChar: newValue!) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if newValue != nil { self.object = NSNumber(short: newValue!) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if newValue != nil { self.object = NSNumber(unsignedShort: newValue!) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if newValue != nil { self.object = NSNumber(int: newValue!) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if newValue != nil { self.object = NSNumber(unsignedInt: newValue!) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if newValue != nil { self.object = NSNumber(longLong: newValue!) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLongLong: newValue!) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON: Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) == (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) == (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) <= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) >= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) > (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) > (rhs.object as! String) default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) < (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) < (rhs.object as! String) default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber: Swift.Comparable { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } } //MARK:- Unavailable @availability(*, unavailable, renamed="JSON") public typealias JSONValue = JSON extension JSON { @availability(*, unavailable, message="use 'init(_ object:AnyObject)' instead") public init(object: AnyObject) { self = JSON(object) } @availability(*, unavailable, renamed="dictionaryObject") public var dictionaryObjects: [String : AnyObject]? { get { return self.dictionaryObject } } @availability(*, unavailable, renamed="arrayObject") public var arrayObjects: [AnyObject]? { get { return self.arrayObject } } @availability(*, unavailable, renamed="int8") public var char: Int8? { get { return self.number?.charValue } } @availability(*, unavailable, renamed="int8Value") public var charValue: Int8 { get { return self.numberValue.charValue } } @availability(*, unavailable, renamed="uInt8") public var unsignedChar: UInt8? { get{ return self.number?.unsignedCharValue } } @availability(*, unavailable, renamed="uInt8Value") public var unsignedCharValue: UInt8 { get{ return self.numberValue.unsignedCharValue } } @availability(*, unavailable, renamed="int16") public var short: Int16? { get{ return self.number?.shortValue } } @availability(*, unavailable, renamed="int16Value") public var shortValue: Int16 { get{ return self.numberValue.shortValue } } @availability(*, unavailable, renamed="uInt16") public var unsignedShort: UInt16? { get{ return self.number?.unsignedShortValue } } @availability(*, unavailable, renamed="uInt16Value") public var unsignedShortValue: UInt16 { get{ return self.numberValue.unsignedShortValue } } @availability(*, unavailable, renamed="int") public var long: Int? { get{ return self.number?.longValue } } @availability(*, unavailable, renamed="intValue") public var longValue: Int { get{ return self.numberValue.longValue } } @availability(*, unavailable, renamed="uInt") public var unsignedLong: UInt? { get{ return self.number?.unsignedLongValue } } @availability(*, unavailable, renamed="uIntValue") public var unsignedLongValue: UInt { get{ return self.numberValue.unsignedLongValue } } @availability(*, unavailable, renamed="int64") public var longLong: Int64? { get{ return self.number?.longLongValue } } @availability(*, unavailable, renamed="int64Value") public var longLongValue: Int64 { get{ return self.numberValue.longLongValue } } @availability(*, unavailable, renamed="uInt64") public var unsignedLongLong: UInt64? { get{ return self.number?.unsignedLongLongValue } } @availability(*, unavailable, renamed="uInt64Value") public var unsignedLongLongValue: UInt64 { get{ return self.numberValue.unsignedLongLongValue } } @availability(*, unavailable, renamed="int") public var integer: Int? { get { return self.number?.integerValue } } @availability(*, unavailable, renamed="intValue") public var integerValue: Int { get { return self.numberValue.integerValue } } @availability(*, unavailable, renamed="uInt") public var unsignedInteger: Int? { get { return self.number?.unsignedIntegerValue } } @availability(*, unavailable, renamed="uIntValue") public var unsignedIntegerValue: Int { get { return self.numberValue.unsignedIntegerValue } } }
apache-2.0
0ca086c3b45c2e929b31c414f80b57c9
25.772394
259
0.525656
4.763914
false
false
false
false
ls1intum/sReto
Source/sReto/Core/Routing/LinkStateRoutingTable.swift
1
10073
// // RoutingTable.swift // sReto // // Created by Julian Asamer on 15/08/14. // Copyright (c) 2014 - 2016 Chair for Applied Software Engineering // // Licensed under the MIT License // // 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 /** * A Change object contains changes that occurred in the routing table caused by some operation. * */ struct RoutingTableChange<T> { /** * Contains information about nodes that became reachable. * */ let nowReachable: [(node: T, nextHop: T, cost: Double)] /** Contains all nodes that are now unreachable. */ let nowUnreachable: [T] /** * Contains informatiown about nodes that have changed routes. * */ let routeChanged: [(node: T, nextHop: T, oldCost: Double, newCost: Double)] /** Returns whether this Change object is actually empty. */ var isEmpty: Bool { get { return nowReachable.isEmpty && nowUnreachable.isEmpty && routeChanged.isEmpty } } } /** Finds the next hop to a given destination node based on the predecessor relationships of the nodes. */ private func findNextHop<T>(_ predecessorRelationships: [T: T], destination: T) -> T { let path = Array(Array( iterateMapping( initialState: destination, mapping: { predecessorRelationships[$0] } ) ).reversed()) return path[1] } /** * A LinkStateRoutingTable manages a graph of nodes in the network with type T. * * Link state routing works by gathering information about the full network topology, i.e. for each node in the network, * all of its neighbors are known eventually. Based on this information, the next hop to a node can be computed using a shortest path algorithm. * * Advantages of link state routing (as opposed to distance vector routing) include that link state routing converges rather quickly and * is not subject to the count-to-infinity problem, hence, no measures to combat this problem need to be taken. As the full network topology * is known to every node, rather advanced routing techniques can be implemented. * * Disadvantages include that the link state information needs to be flooded through the network, causing higher overhead than link state protocols. * The memory and computational requirements are also higher. * * The LinkStateRoutingTable class is not responsible for distributing link state information across the network, * however, it processes received link state information and can provide link state information for the local peer. * * This routing table is designed to compute all next hops and path costs for all known nodes every time when new * network topology information becomes available (e.g. neighbors added, updated or lost, and link state information received from * any peer). * * These changes in the routing table are returned as a LinkStateRoutingTable.Change object. This object includes information about * nodes that became reachable or unreachable, or information about route changes to nodes that were reachable before. * */ class LinkStateRoutingTable<T: Hashable> { /** A directed, weighted graph used to represent the network of nodes and their link states. */ var graph: Graph<T, DefaultEdge> = Graph() /** The local node. In all neighbor related operations, the neighbor is considered a neighbor of this node. */ var localNode: T /** Constructs a new LinkStateRoutingTable. */ init(localNode: T) { self.localNode = localNode self.graph.addVertex(self.localNode) } /** * Computes the changes to the routing table when updating or adding a new neighbor. * If the neighbor is not yet known to the routing table, it is added. * * @param neighbor The neighbor to update or add. * @param cost The cost to reach that neighbor. * @return A LinkStateRoutingTable.Change object representing the changes that occurred in the routing table. * */ func getRoutingTableChangeForNeighborUpdate(_ neighbor: T, cost: Double) -> RoutingTableChange<T> { return self.trackGraphChanges { self.updateNeighbor(neighbor, cost: cost) } } /** * Computes the changes to the routing table when removing a neighbor. * * @param neighbor The neighbor to remove * @return A LinkStateRoutingTable.Change object representing the changes that occurred in the routing table. * */ func getRoutingTableChangeForNeighborRemoval(_ neighbor: T) -> RoutingTableChange<T> { return self.trackGraphChanges { self.removeNeighbor(neighbor) } } /** * Computes the changes to the routing table when link state information is received for a given node. * * @param node The node for which a list of neighbors (ie. link state information) was received. * @param neighbors The node's neighbors. * @return A LinkStateRoutingTable.Change object representing the changes that occurred in the routing table. * */ func getRoutingTableChangeForLinkStateInformationUpdate(_ node: T, neighbors: [(neighborId: T, cost: Double)]) -> RoutingTableChange<T> { return self.trackGraphChanges { self.updateLinkStateInformation(node, neighbors: neighbors) } } /** Returns a list of neighbors for the local node (ie. link state information). */ func linkStateInformation() -> [(nodeId: T, cost: Double)] { if let info = self.graph.getEdges(startingAtVertex: self.localNode) { return info.map{ (nodeId: $0.endVertex, cost: $0.annotation.weight) } } return [] } /** Updates or adds a neighbor. */ fileprivate func updateNeighbor(_ neighbor: T, cost: Double) { self.graph.removeEdges(startingAtVertex: self.localNode, endingAtVertex: neighbor) self.graph.addEdge(self.localNode, neighbor, DefaultEdge(weight: cost)) } /** Removes a neighbor. */ fileprivate func removeNeighbor(_ neighbor: T) { self.graph.removeEdges(startingAtVertex: self.localNode, endingAtVertex: neighbor) } /** Updates link state information for a given node. */ fileprivate func updateLinkStateInformation(_ node: T, neighbors: [(neighborId: T, cost: Double)]) { self.graph.removeEdges(startingAtVertex: node) for (neighbor, cost) in neighbors { self.graph.addEdge(node, neighbor, DefaultEdge(weight: cost)) } } func nextHop(_ destination: T) -> T? { if let (path, _) = graph.shortestPath(self.localNode, end: destination) { return path[1] } return nil } func getHopTree(_ destinations: Set<T>) -> Tree<T> { return self.graph.getSteinerTreeApproximation(rootVertex: self.localNode, includedVertices: destinations + [self.localNode]) } /** * Computes a Change object for arbitrary modifications of the graph. * * This method first computes the shortest paths to all reachable nodes in the graph, then runs the graph action, and then calculates all shortest paths again. * * From changes in which nodes are reachable, and changes in the paths, a LinkStateRoutingTable.Change object is created. * * @param graphAction A Runnable that is expected to perform some changes on the graph. * @return A LinkStateRoutingTable.Change object representing the changes caused by the changes performed by the graphAction. * */ fileprivate func trackGraphChanges(_ graphAction: () -> ()) -> RoutingTableChange<T> { let (previousPredecessorRelationships, previousDistances) = graph.shortestPaths(self.localNode) graphAction() let (updatedPredecessorRelationships, updatedDistances) = graph.shortestPaths(self.localNode) let nowReachable = (Set(updatedPredecessorRelationships.keys) - Set(previousPredecessorRelationships.keys)).map( { ( node: $0, nextHop: findNextHop(updatedPredecessorRelationships, destination: $0), cost: updatedDistances[$0]! ) } ) let nowUnreachable = Set(previousPredecessorRelationships.keys) - Set(updatedPredecessorRelationships.keys) let changedRoutes = Set(updatedPredecessorRelationships.keys).intersection(Set(previousPredecessorRelationships.keys)) .filter { previousDistances[$0] != updatedDistances[$0] || findNextHop(previousPredecessorRelationships, destination: $0) != findNextHop(updatedPredecessorRelationships, destination: $0) } .map { ( node: $0, nextHop: findNextHop(updatedPredecessorRelationships, destination: $0), oldCost: previousDistances[$0]!, newCost: updatedDistances[$0]! ) } return RoutingTableChange( nowReachable: Array(nowReachable), nowUnreachable: Array(nowUnreachable), routeChanged: Array(changedRoutes) ) } }
mit
37ed24b1a4fe56a8099567861ecaa188
48.136585
162
0.696615
4.562047
false
false
false
false
pjk1129/SONetwork
Demo/SwiftOne/Classes/UI/User/SOUserViewController.swift
1
2802
// // SOUserViewController.swift // SwiftOne // // Created by JK.PENG on 2017/3/20. // Copyright © 2017年 XXXXX. All rights reserved. // import UIKit import WebKit class SOUserViewController: SOBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. navTitle = "我的" setupUIConstraints() reloadWebView() } private func reloadWebView() { let url = NSURL(string: "https://www.baidu.com") as! URL let requst = NSURLRequest(url: url) webView.load(requst as URLRequest) } private func setupUIConstraints(){ containerView.addSubview(webView) containerView.addSubview(progressView) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[webView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["webView" : webView])) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[webView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["webView" : webView])) progressView.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 2) } //MARK:- 变量 var goodsItem: SOGoodsItem! lazy var webView : WKWebView = { let web = WKWebView(frame: CGRect.zero) web.navigationDelegate = self web.translatesAutoresizingMaskIntoConstraints = false return web }() // 进度条 lazy var progressView:UIProgressView = { let progress = UIProgressView() progress.progressTintColor = UIColor.blue progress.trackTintColor = .clear return progress }() } extension SOUserViewController: WKNavigationDelegate { // 页面开始加载时调用 func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){ /// 获取网页的progress UIView.animate(withDuration: 0.5) { self.progressView.progress = Float(webView.estimatedProgress) } } // 当内容开始返回时调用 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){ } // 页面加载完成之后调用 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){ UIView.animate(withDuration: 0.5) { self.progressView.progress = 1.0 self.progressView.isHidden = true } } // 页面加载失败时调用 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){ UIView.animate(withDuration: 0.5) { self.progressView.progress = 0.0 self.progressView.isHidden = true } } }
mit
938e6556a294c583fcf165471a8230d5
31.130952
198
0.648018
4.776991
false
false
false
false
fgengine/quickly
Quickly/Database/Expressions/QDatabaseCompareExpression.swift
1
1726
// // Quickly // public extension QDatabase { struct CompareExpression : IQDatabaseExpressable { public enum Operator { case equal case notEqual case more case moreOrEqual case less case lessOrEqual } public let column: QDatabase.Column public let `operator`: Operator public let expression: IQDatabaseExpressable public init( _ column: QDatabase.Column, _ `operator`: Operator, _ expression: IQDatabaseExpressable ) { self.column = column self.operator = `operator` self.expression = expression } public init( _ column: QDatabase.Column, _ `operator`: Operator, _ value: IQDatabaseInputValue ) { self.init(column, `operator`, LiteralExpression(value)) } public func inputValues() -> [IQDatabaseInputValue] { return self.expression.inputValues() } public func queryExpression() -> String { return self.column.name + " " + self.operator.queryString() + " " + self.expression.queryExpression() } } } // MARK: Internal • QDatabase.CompareExpression.Operator internal extension QDatabase.CompareExpression.Operator { func queryString() -> String { switch self { case .equal: return "==" case .notEqual: return "<>" case .more: return ">" case .moreOrEqual: return ">=" case .less: return "<" case .lessOrEqual: return "<=" } } }
mit
16d307cc46ae3ff7d98d21ab607bc56c
24.731343
113
0.530742
5.192771
false
false
false
false
ps2/rileylink_ios
MinimedKit/PumpManager/PumpState.swift
1
2741
// // PumpState.swift // RileyLink // // Created by Nathan Racklyeft on 4/9/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct PumpState: RawRepresentable, Equatable { public typealias RawValue = [String: Any] public var timeZone: TimeZone public var pumpModel: PumpModel? public var useMySentry: Bool public var awakeUntil: Date? public var lastValidFrequency: Measurement<UnitFrequency>? public var lastTuned: Date? var isAwake: Bool { if let awakeUntil = awakeUntil { return awakeUntil.timeIntervalSinceNow > 0 } return false } var lastWakeAttempt: Date? public init() { self.timeZone = .currentFixed self.useMySentry = true } public init(timeZone: TimeZone, pumpModel: PumpModel, useMySentry: Bool) { self.timeZone = timeZone self.pumpModel = pumpModel self.useMySentry = useMySentry } public init?(rawValue: RawValue) { guard let timeZoneSeconds = rawValue["timeZone"] as? Int, let timeZone = TimeZone(secondsFromGMT: timeZoneSeconds) else { return nil } self.timeZone = timeZone self.useMySentry = rawValue["useMySentry"] as? Bool ?? true if let pumpModelNumber = rawValue["pumpModel"] as? PumpModel.RawValue { pumpModel = PumpModel(rawValue: pumpModelNumber) } if let frequencyRaw = rawValue["lastValidFrequency"] as? Double { lastValidFrequency = Measurement<UnitFrequency>(value: frequencyRaw, unit: .megahertz) } } public var rawValue: RawValue { var rawValue: RawValue = [ "timeZone": timeZone.secondsFromGMT(), "useMySentry": useMySentry, ] if let pumpModel = pumpModel { rawValue["pumpModel"] = pumpModel.rawValue } if let frequency = lastValidFrequency?.converted(to: .megahertz) { rawValue["lastValidFrequency"] = frequency.value } return rawValue } } extension PumpState: CustomDebugStringConvertible { public var debugDescription: String { return [ "## PumpState", "timeZone: \(timeZone)", "pumpModel: \(pumpModel?.rawValue ?? "")", "useMySentry: \(useMySentry)", "awakeUntil: \(awakeUntil ?? .distantPast)", "lastValidFrequency: \(String(describing: lastValidFrequency))", "lastTuned: \(awakeUntil ?? .distantPast))", "lastWakeAttempt: \(String(describing: lastWakeAttempt))" ].joined(separator: "\n") } }
mit
5a46da3c243725c5035e5d7f7a8f17cd
26.128713
98
0.60365
4.79021
false
false
false
false
Maxim-38RUS-Zabelin/ios-charts
Charts/Classes/Renderers/HorizontalBarChartRenderer.swift
1
22135
// // HorizontalBarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // 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 CoreGraphics import UIKit public class HorizontalBarChartRenderer: BarChartRenderer { private var xOffset: CGFloat = 0.0 private var yOffset: CGFloat = 0.0 public override init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(delegate: delegate, animator: animator, viewPortHandler: viewPortHandler) } internal override func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int) { CGContextSaveGState(context) var barData = delegate!.barChartRendererData(self) var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self) var dataSetOffset = (barData.dataSetCount - 1) var groupSpace = barData.groupSpace var groupSpaceHalf = groupSpace / 2.0 var barSpace = dataSet.barSpace var barSpaceHalf = barSpace / 2.0 var containsStacks = dataSet.isStacked var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] var barWidth: CGFloat = 0.5 var phaseY = _animator.phaseY var barRect = CGRect() var barShadow = CGRect() var y: Double // do the drawing for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++) { var e = entries[j] // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(j) + groupSpaceHalf var vals = e.values if (!containsStacks || vals == nil) { y = e.value var bottom = x - barWidth + barSpaceHalf var top = x + barWidth - barSpaceHalf var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { barShadow.origin.x = viewPortHandler.contentLeft barShadow.origin.y = barRect.origin.y barShadow.size.width = viewPortHandler.contentWidth barShadow.size.height = barRect.size.height CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) if let (raundingCorners, cornerRadii) = self.calcShadowRectCorners() { let path: UIBezierPath = UIBezierPath(roundedRect: barShadow, byRoundingCorners: raundingCorners, cornerRadii: cornerRadii) path.fill() } else { CGContextFillRect(context, barShadow) } } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) if let (raundingCorners, cornerRadii) = self.calcRectCorners(y) { let path: UIBezierPath = UIBezierPath( roundedRect: barRect, byRoundingCorners: raundingCorners, cornerRadii: cornerRadii) path.fill() } else { CGContextFillRect(context, barRect) } } else { var allPos = e.positiveSum var allNeg = e.negativeSum // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value var bottom = x - barWidth + barSpaceHalf var top = x + barWidth - barSpaceHalf var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) barShadow.origin.x = viewPortHandler.contentLeft barShadow.origin.y = barRect.origin.y barShadow.size.width = viewPortHandler.contentWidth barShadow.size.height = barRect.size.height CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) if let (raundingCorners, cornerRadii) = self.calcShadowRectCorners() { let path: UIBezierPath = UIBezierPath(roundedRect: barShadow, byRoundingCorners: raundingCorners, cornerRadii: cornerRadii) path.fill() } else { CGContextFillRect(context, barShadow) } } // fill the stack for (var k = 0; k < vals.count; k++) { let value = vals[k] if value >= 0.0 { allPos -= value y = value + allPos } else { allNeg -= abs(value) y = value + allNeg } var bottom = x - barWidth + barSpaceHalf var top = x + barWidth - barSpaceHalf var right = y >= 0.0 ? CGFloat(y) : 0.0 var left = y <= 0.0 ? CGFloat(y) : 0.0 // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { // Skip to next bar break } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor) if let (raundingCorners, cornerRadii) = self.calcRectCorners(y) { let path: UIBezierPath = UIBezierPath( roundedRect: barRect, byRoundingCorners: raundingCorners, cornerRadii: cornerRadii) path.fill() } else { CGContextFillRect(context, barRect) } } } } CGContextRestoreGState(context) } internal override func prepareBarHighlight(#x: CGFloat, y: Double, barspacehalf: CGFloat, from: Double, trans: ChartTransformer, inout rect: CGRect) { let barWidth: CGFloat = 0.5 var top = x - barWidth + barspacehalf var bottom = x + barWidth - barspacehalf var left = y >= from ? CGFloat(y) : CGFloat(from) var right = y <= from ? CGFloat(y) : CGFloat(from) rect.origin.x = left rect.origin.y = top rect.size.width = right - left rect.size.height = bottom - top trans.rectValueToPixelHorizontal(&rect, phaseY: _animator.phaseY) } public override func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint] { return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY) } public override func drawValues(#context: CGContext) { // if values are drawn if (passesCheck()) { var barData = delegate!.barChartRendererData(self) var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self) var dataSets = barData.dataSets var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self) var drawValuesForWholeStackEnabled = delegate!.barChartIsDrawValuesForWholeStackEnabled(self) let textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right let valueOffsetPlus: CGFloat = 5.0 var posOffset: CGFloat var negOffset: CGFloat for (var i = 0, count = barData.dataSetCount; i < count; i++) { var dataSet = dataSets[i] if (!dataSet.isDrawValuesEnabled) { continue } var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency) var valueFont = dataSet.valueFont var valueTextColor = dataSet.valueTextColor var yOffset = -valueFont.lineHeight / 2.0 var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency) var entries = dataSet.yVals as! [BarChartDataEntry] var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i) // if only single values are drawn (sum) if (!drawValuesForWholeStackEnabled) { for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { if (!viewPortHandler.isInBoundsX(valuePoints[j].x)) { continue } if (!viewPortHandler.isInBoundsTop(valuePoints[j].y)) { break } if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y)) { continue } var val = entries[j].value var valueText = formatter!.stringFromNumber(val)! // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (isInverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } self.modifyValuesOffsets(&posOffset, negOffset: &negOffset, valueTextWidth: valueTextWidth, valuePoint: valuePoints[j]) drawValue( context: context, value: valueText, xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoints[j].y + yOffset, font: valueFont, align: textAlign, color: valueTextColor) } } else { // if each value of a potential stack should be drawn for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { var e = entries[j] var vals = e.values // we still draw stacked bars, but there is one non-stacked in between if (vals == nil) { if (!viewPortHandler.isInBoundsX(valuePoints[j].x)) { continue } if (!viewPortHandler.isInBoundsTop(valuePoints[j].y)) { break } if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y)) { continue } var val = e.value var valueText = formatter!.stringFromNumber(val)! // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (isInverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } self.modifyValuesOffsets(&posOffset, negOffset: &negOffset, valueTextWidth: valueTextWidth, valuePoint: valuePoints[j]) drawValue( context: context, value: valueText, xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoints[j].y + yOffset, font: valueFont, align: textAlign, color: valueTextColor) } else { var transformed = [CGPoint]() var allPos = e.positiveSum var allNeg = e.negativeSum for (var k = 0; k < vals.count; k++) { let value = vals[k] var y: Double if value >= 0.0 { allPos -= value y = value + allPos } else { allNeg -= abs(value) y = value + allNeg } transformed.append(CGPoint(x: CGFloat(y) * _animator.phaseY, y: 0.0)) } trans.pointValuesToPixel(&transformed) for (var k = 0; k < transformed.count; k++) { var val = vals[k] var valueText = formatter!.stringFromNumber(val)! // calculate the correct offset depending on the draw position of the value var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (isInverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } self.modifyValuesOffsets(&posOffset, negOffset: &negOffset, valueTextWidth: valueTextWidth, valuePoint: valuePoints[j]) var x = transformed[k].x + (val >= 0 ? posOffset : negOffset) var y = valuePoints[j].y if (!viewPortHandler.isInBoundsX(x)) { continue } if (!viewPortHandler.isInBoundsTop(y)) { break } if (!viewPortHandler.isInBoundsBottom(y)) { continue } drawValue(context: context, value: valueText, xPos: x, yPos: y + yOffset, font: valueFont, align: textAlign, color: valueTextColor) } } } } } } } internal override func passesCheck() -> Bool { var barData = delegate!.barChartRendererData(self) if (barData === nil) { return false } return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleY } public func modifyValuesOffsets(inout posOffset: CGFloat, inout negOffset: CGFloat, valueTextWidth: CGFloat, valuePoint: CGPoint) { } public func calcShadowRectCorners() -> (raundingCorners: UIRectCorner, cornerRadii: CGSize)? { return nil } }
apache-2.0
d4b5f6ec18d1631204bfa94e34554a90
42.066148
170
0.428959
6.943225
false
false
false
false
caobo56/Juyou
JuYou/JuYou/Home/VIew/ISHotHeadView.swift
1
2926
// // ISHotHeadView.swift // JuYou // // Created by caobo56 on 16/5/19. // Copyright © 2016年 caobo56. All rights reserved. // import UIKit import SDWebImage class ISHotHeadView: UIView{ //MARK: - property 属性 var imageURLArray: [String] = ["http://101.200.164.224/juyou_statics/data/img/freedom/210015.jpg"] var cyclePictureView: CyclePictureView! var imageVLeft: UIImageView? = UIImageView.init() var imageVRight: UIImageView? = UIImageView.init() //MARK: - View Lifecycle (View 的生命周期) override init(frame: CGRect) { super.init(frame: frame) self.initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: - Custom Accessors (自定义访问器) func initUI() { let he = DestCellH+30+(((Screen_weight-30)/2)/690*360)+30 self.setSize(CGSizeMake(Screen_weight,he )) self.backgroundColor = UIColor.whiteColor() self.cyclePictureView = CyclePictureView(frame: CGRectMake(0, 0, Screen_weight, DestCellH), imageURLArray: self.imageURLArray) self.addSubview(self.cyclePictureView) self.cyclePictureView.backgroundColor = UIColor.whiteColor() self.cyclePictureView.timeInterval = 2 self.cyclePictureView.pageControlAliment = .RightBottom self.addSubview(imageVLeft!) self.imageVLeft!.setSize(CGSizeMake((Screen_weight-30)/2,(Screen_weight-30)/2/690*360)) self.imageVLeft!.setOrigin(CGPointMake(10, self.cyclePictureView.bottom+10)) self.imageVLeft?.sd_setImageWithURL(NSURL(string: "http://juyoufenqi.com/juyou/resource/upload/tongxue.png")) self.addSubview(imageVRight!) self.imageVRight!.setSize(CGSizeMake((Screen_weight-30)/2,(Screen_weight-30)/2/690*360)) self.imageVRight!.setOrigin(CGPointMake((self.imageVLeft?.right)!+10, self.cyclePictureView.bottom+10)) self.imageVRight?.sd_setImageWithURL(NSURL(string: "http://juyoufenqi.com/juyou/resource/upload/youxue.png")) let lineView = UIView.init(frame: CGRectMake(0, (self.imageVRight?.bottom)!+10, Screen_weight, 10)) lineView.backgroundColor = UIColorWithHex(0xeeeeee, alpha: 1.0) self.addSubview(lineView) let titleLable:UILabel = UILabel.init(frame: CGRectMake(10, lineView.bottom, 200, 30)) titleLable.text = "热门路线" titleLable.textAlignment = NSTextAlignment.Left titleLable.font = UIFont.systemFontOfSize(14) titleLable.textColor = UIColorWithHex(0xFF7F05,alpha: 1.0) self.addSubview(titleLable) } func loadData(fits:[Filterfreedom]){ imageURLArray.removeAll() for fit:Filterfreedom in fits{ imageURLArray.append(fit.pic!) } cyclePictureView.imageURLArray = imageURLArray } }
apache-2.0
bee0a0794b4320f04240ca458d52f362
37.932432
134
0.67303
3.903794
false
false
false
false
Nana-Muthuswamy/AadhuEats
AadhuEats/Model/Log.swift
1
2609
// // Log.swift // AadhuEats // // Created by Nana on 10/26/17. // Copyright © 2017 Nana. All rights reserved. // import Foundation struct Log: Exportable, DateFormatable { var date = Date() var type: LogType var milkType: MilkType var breastOrientation: BreastOrientation var volume: Int var duration: Int var displayTime: String { return Log.timeFormatter.string(from: date) } var displayVolume: String { return "\(volume) ml" } var displayDuration: String { return "\(duration) mins" } init(date: Date, type: LogType, milkType: MilkType, breastOrientation: BreastOrientation, volume: Int, duration: Int) { self.date = date self.type = type self.milkType = milkType self.breastOrientation = breastOrientation self.volume = volume self.duration = duration } init?(source:Dictionary<String,Any>) { // Guard the initiation source guard let logDateStr = source[kDate] as? String, let logDate = Log.dateTimeFormatter.date(from:logDateStr), let logTypeRaw = source[kType] as? Int, let logType = LogType(rawValue: logTypeRaw), let logMilkTypeRaw = source[kMilkType] as? Int, let logMilkType = MilkType(rawValue: logMilkTypeRaw), let logBreastOrientationRaw = source[kBreastOrientation] as? Int, let logBreastOrientation = BreastOrientation(rawValue: logBreastOrientationRaw), let logVolume = source[kVolume] as? Int, let logDuration = source[kDuration] as? Int else { return nil } date = logDate type = logType milkType = logMilkType breastOrientation = logBreastOrientation volume = logVolume duration = logDuration } func description() -> String { return "Log of type \"\(type)\" with milkType \"\(milkType)\" and breastOrientation \"\(breastOrientation)\" tracked at \"\(date)\" for volume \"\(volume)\" in durationMinutes \"\(duration)\"" } func export() -> Dictionary<String,Any> { var exportDict = Dictionary<String,Any>() exportDict.updateValue(Log.dateTimeFormatter.string(from: date), forKey: kDate) exportDict.updateValue(type.rawValue, forKey: kType) exportDict.updateValue(milkType.rawValue, forKey: kMilkType) exportDict.updateValue(breastOrientation.rawValue, forKey: kBreastOrientation) exportDict.updateValue(volume, forKey: kVolume) exportDict.updateValue(duration, forKey: kDuration) return exportDict } }
mit
a29d33c7882b3baa4b5c11781bba1a38
33.315789
200
0.657209
4.139683
false
false
false
false
usbong/UsbongKit
UsbongKit/Usbong.swift
2
1309
// // Usbong.swift // UsbongKit // // Created by Chris Amanse on 27/05/2016. // Copyright © 2016 Usbong Social Systems, Inc. All rights reserved. // import UIKit /// Usbong is a collection of functions to manage utree files public struct Usbong { fileprivate init() {} /** Read utree file and present viewer - parameters: - viewController: The parent view controller for the to be presented viewer - url: URL for the utree file */ public static func presentViewer(onViewController viewController: UIViewController, withUtreeURL url: URL, andData data: UsbongTreeData = UsbongTreeData()) { let storyboard = UIStoryboard(name: "UsbongKit", bundle: Bundle(for: TreeViewController.self)) let navController = storyboard.instantiateInitialViewController() as! UINavigationController let treeVC = navController.topViewController as! TreeViewController treeVC.treeURL = url treeVC.store = IAPHelper(bundles: data.bundles) viewController.present(navController, animated: true, completion: nil) } } public struct UsbongTreeData { public var bundles: [IAPBundle] = [] public init() {} public init(bundles: [IAPBundle]) { self.bundles = bundles } }
apache-2.0
786b48b87d63b58ef3e94238fabe1bab
29.418605
161
0.674312
4.589474
false
false
false
false
or1onsli/Fou.run-
MusicRun/PhysicsCategory.swift
1
394
// // PhysicsCategory.swift // Fou.run() // // Copyright © 2016 Shock&Awe. All rights reserved. // struct PhysicsCategory { static let None : UInt32 = 0 static let All : UInt32 = UInt32.max static let Character : UInt32 = 0b0001 static let HighBarrier: UInt32 = 0b0010 static let LowBarrier : UInt32 = 0b0100 static let Note : UInt32 = 0b1000 }
mit
d682257b0fb5ac44d589f1998e712094
25.2
52
0.636132
3.447368
false
false
false
false
benlangmuir/swift
test/Profiler/pgo_checked_cast.swift
17
3428
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_checked_cast -o %t/main // This unusual use of 'sh' allows the path of the profraw file to be // substituted by %target-run. // RUN: %target-codesign %t/main // RUN: %target-run sh -c 'env LLVM_PROFILE_FILE=$1 $2' -- %t/default.profraw %t/main // RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata // RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=SIL // need to lower checked_cast_addr_br(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -emit-ir -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=IR // RUN: %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=SIL-OPT // need to lower checked_cast_addr_br(addr) into IR for this // %target-swift-frontend %s -Xllvm -sil-full-demangle -profile-use=%t/default.profdata -O -emit-ir -module-name pgo_checked_cast -o - | %FileCheck %s --check-prefix=IR-OPT // REQUIRES: profile_runtime // REQUIRES: executable_test // REQUIRES: OS=macosx // SIL-LABEL: // pgo_checked_cast.check1<A>(Any, A) -> A // SIL-LABEL: sil @$s16pgo_checked_cast6check1yxyp_xtlF : $@convention(thin) <T> (@in_guaranteed Any, @in_guaranteed T) -> @out T !function_entry_count(5001) { // IR-LABEL: define swiftcc i32 @$s6pgo_checked_cast6guess1s5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$s6pgo_checked_cast6guess1s5Int32VAD1x_tF public func check1<T>(_ a : Any, _ t : T) -> T { // SIL: checked_cast_addr_br take_always Any in {{.*}} : $*Any to T in {{.*}} : $*T, {{.*}}, {{.*}} !true_count(5000) !false_count(1) // SIL-OPT: checked_cast_addr_br take_always Any in {{.*}} : $*Any to T in {{.*}} : $*T, {{.*}}, {{.*}} !true_count(5000) !false_count(1) if let x = a as? T { return x } else { return t } } public class B {} public class C : B {} public class D : C {} // SIL-LABEL: // pgo_checked_cast.check2(pgo_checked_cast.B) -> Swift.Int32 // SIL-LABEL: sil @$s16pgo_checked_cast6check2ys5Int32VAA1BCF : $@convention(thin) (@guaranteed B) -> Int32 !function_entry_count(5003) { // IR-LABEL: define swiftcc i32 @$s6pgo_checked_cast6guess1s5Int32VAD1x_tF // IR-OPT-LABEL: define swiftcc i32 @$s6pgo_checked_cast6guess1s5Int32VAD1x_tF public func check2(_ a : B) -> Int32 { // SIL: checked_cast_br %0 : $B to D, {{.*}}, {{.*}} !true_count(5000) // SIL: checked_cast_br %0 : $B to C, {{.*}}, {{.*}} !true_count(2) // SIL-OPT: checked_cast_br %0 : $B to D, {{.*}}, {{.*}} !true_count(5000) // SIL-OPT: checked_cast_br %0 : $B to C, {{.*}}, {{.*}} !true_count(2) switch a { case is D: return 42 case is C: return 23 default: return 13 } } func main() { let answer : Int32 = 42 var sum : Int32 = 0 sum += check1("The answer to the life, the universe, and everything", answer) sum += check2(B()) sum += check2(C()) sum += check2(C()) for i : Int32 in 1...5000 { sum += check1(i, answer) sum += check2(D()) } } main() // IR: !{!"branch_weights", i32 5001, i32 2} // IR-OPT: !{!"branch_weights", i32 5001, i32 2}
apache-2.0
144be4ae1035d1002d3966277629b0b8
42.948718
196
0.644107
2.830718
false
false
false
false
nvh/DataSourceable
DataSourceableTests/DataSourceTypeSpec.swift
1
1774
// // DataSourceTypeSpec.swift // DataSourceable // // Created by Niels van Hoorn on 13/10/15. // Copyright © 2015 Zeker Waar. All rights reserved. // import DataSourceable import Quick import Nimble struct DataSource: DataContaining { var data: [Int]? = nil } class DataSourceTypeSpec: QuickSpec { override func spec() { describe("DataSourceType") { var dataSource = DataSource() context("when data is nil") { beforeEach { dataSource.data = nil } it("numberOfItems should return 0") { expect(dataSource.numberOfItems).to(equal(0)) } it("should return nil when requesting a item at index") { for index in -5...5 { expect(dataSource.item(atIndex: index)).to(beNil()) } } } context("when data is set") { let data = [4,5,6] beforeEach { dataSource.data = data } it("should return the correct index") { for (index, value) in data.enumerate() { expect(dataSource.item(atIndex: index)).to(equal(value)) } } it("should return nil when index is greater than number of elements") { expect(dataSource.item(atIndex: 3)).to(beNil()) } it("should return nil when index is below 0") { expect(dataSource.item(atIndex: -1)).to(beNil()) } } } } }
mit
3d60980cceffb00c4abbf2e92a779ca8
28.55
87
0.456289
5.13913
false
false
false
false
Eitot/vienna-rss
Vienna/Sources/Main window/TabbedBrowserViewController.swift
1
13078
// // TabbedBrowserViewController.swift // Vienna // // Copyright 2018 Tassilo Karge // // 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 // // https://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 Cocoa import MMTabBarView class TabbedBrowserViewController: NSViewController, RSSSource { @IBOutlet private(set) weak var tabBar: MMTabBarView? { didSet { guard let tabBar = self.tabBar else { return } tabBar.setStyleNamed("Mojave") tabBar.onlyShowCloseOnHover = true tabBar.canCloseOnlyTab = false tabBar.disableTabClose = false tabBar.allowsBackgroundTabClosing = true tabBar.hideForSingleTab = true tabBar.showAddTabButton = true tabBar.buttonMinWidth = 120 tabBar.useOverflowMenu = true tabBar.automaticallyAnimates = true // TODO: figure out what this property means tabBar.allowsScrubbing = true } } @IBOutlet private(set) weak var tabView: NSTabView? /// The browser can have a fixed first tab (e.g. bookmarks). /// This method will set the primary tab the first time it is called /// - Parameter tabViewItem: the tab view item configured with the view that shall be in the first fixed tab. var primaryTab: NSTabViewItem? { didSet { // Temove from tabView if there was a prevous primary tab if let primaryTab = oldValue { self.closeTab(primaryTab) } if let primaryTab = self.primaryTab { tabView?.insertTabViewItem(primaryTab, at: 0) tabBar?.select(primaryTab) } } } var restoredTabs = false var activeTab: Tab? { tabView?.selectedTabViewItem?.viewController as? Tab } var browserTabCount: Int { tabView?.numberOfTabViewItems ?? 0 } weak var rssSubscriber: RSSSubscriber? { didSet { for source in tabView?.tabViewItems ?? [] { (source as? RSSSource)?.rssSubscriber = self.rssSubscriber } } } weak var contextMenuDelegate: BrowserContextMenuDelegate? override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder: NSCoder) { guard let tabBar = coder.decodeObject(of: MMTabBarView.self, forKey: "tabBar"), let tabView = coder.decodeObject(of: NSTabView.self, forKey: "tabView"), let primaryTab = coder.decodeObject(of: NSTabViewItem.self, forKey: "primaryTab") else { return nil } self.tabBar = tabBar self.tabView = tabView self.primaryTab = primaryTab super.init(coder: coder) } override func encode(with aCoder: NSCoder) { aCoder.encode(tabBar, forKey: "tabBar") aCoder.encode(tabBar, forKey: "tabView") aCoder.encode(tabBar, forKey: "primaryTab") } override func viewWillAppear() { super.viewWillAppear() if !restoredTabs { // Defer to avoid loading first tab, because primary tab is set // after view load. restoreTabs() restoredTabs = true } } func restoreTabs() { guard let tabLinks = Preferences.standard.array(forKey: "TabList") as? [String] else { return } let tabTitles = Preferences.standard.object(forKey: "TabTitleDict") as? [String: String] for urlString in tabLinks { guard let url = URL(string: urlString) else { continue } let tab = createNewTab(url, inBackground: true, load: false) as? BrowserTab tab?.title = tabTitles?[urlString] } } func saveOpenTabs() { let tabsOptional = tabBar?.tabView.tabViewItems.compactMap { $0.viewController as? BrowserTab } guard let tabs = tabsOptional else { return } let tabLinks = tabs.compactMap { $0.tabUrl?.absoluteString } let tabTitleList: [(String, String)] = tabs.filter { $0.tabUrl != nil && $0.title != nil }.map { ($0.tabUrl?.absoluteString ?? "", $0.title ?? "") } let tabTitles = Dictionary(tabTitleList) { $1 } Preferences.standard.setArray(tabLinks as [Any], forKey: "TabList") Preferences.standard.setObject(tabTitles, forKey: "TabTitleDict") Preferences.standard.save() } func closeTab(_ tabViewItem: NSTabViewItem) { self.tabBar?.close(tabViewItem) } } extension TabbedBrowserViewController: Browser { func createNewTab(_ url: URL?, inBackground: Bool, load: Bool) -> Tab { createNewTab(url, inBackground: inBackground, load: load, insertAt: nil) } func createNewTab(_ request: URLRequest, config: WKWebViewConfiguration, inBackground: Bool, insertAt index: Int? = nil) -> Tab { let newTab = BrowserTab(request, config: config) return initNewTab(newTab, request.url, false, inBackground, insertAt: index) } func createNewTab(_ url: URL? = nil, inBackground: Bool = false, load: Bool = false, insertAt index: Int? = nil) -> Tab { let newTab = BrowserTab() return initNewTab(newTab, url, load, inBackground, insertAt: index) } private func initNewTab(_ newTab: BrowserTab, _ url: URL?, _ load: Bool, _ inBackground: Bool, insertAt index: Int? = nil) -> Tab { newTab.rssSubscriber = self.rssSubscriber let newTabViewItem = TitleChangingTabViewItem(viewController: newTab) newTabViewItem.hasCloseButton = true // This must be executed after setup of titleChangingTabViewItem to // observe new title properly. newTab.tabUrl = url if load { newTab.loadTab() } if let index = index { tabView?.insertTabViewItem(newTabViewItem, at: index) } else { tabView?.addTabViewItem(newTabViewItem) } if !inBackground { tabBar?.select(newTabViewItem) if load { newTab.webView.becomeFirstResponder() } else { newTab.activateAddressBar() } // TODO: make first responder? } newTab.webView.contextMenuProvider = self // TODO: tab view order return newTab } func switchToPrimaryTab() { if self.primaryTab != nil { self.tabView?.selectTabViewItem(at: 0) } } func showPreviousTab() { self.tabView?.selectPreviousTabViewItem(nil) } func showNextTab() { self.tabView?.selectNextTabViewItem(nil) } func closeActiveTab() { if let selectedTabViewItem = self.tabView?.selectedTabViewItem { self.closeTab(selectedTabViewItem) } } func closeAllTabs() { self.tabView?.tabViewItems.filter { $0 != primaryTab } .forEach(closeTab) } func getTextSelection() -> String { // TODO: implement return "" } func getActiveTabHTML() -> String { // TODO: implement return "" } func getActiveTabURL() -> URL? { // TODO: implement return URL(string: "") } } extension TabbedBrowserViewController: MMTabBarViewDelegate { func tabView(_ aTabView: NSTabView, shouldClose tabViewItem: NSTabViewItem) -> Bool { tabViewItem != primaryTab } func tabView(_ aTabView: NSTabView, willClose tabViewItem: NSTabViewItem) { guard let tab = tabViewItem.viewController as? Tab else { return } tab.stopLoadingTab() tab.tabUrl = URL(string: "about:blank") tab.loadTab() } func tabView(_ aTabView: NSTabView, selectOnClosing tabViewItem: NSTabViewItem) -> NSTabViewItem? { // Select tab item on the right of currently selected item. Cannot // select tab on the right, if selected tab is rightmost one. if let tabView = self.tabBar?.tabView, let selected = tabBar?.selectedTabViewItem, selected == tabViewItem, tabViewItem != tabView.tabViewItems.last, let indexToSelect = tabView.tabViewItems.firstIndex(of: selected)?.advanced(by: 1) { return tabView.tabViewItems[indexToSelect] } else { // Default (left of currently selected item / no change if deleted // item not selected) return nil } } func tabView(_ aTabView: NSTabView, menuFor tabViewItem: NSTabViewItem) -> NSMenu { // TODO: return menu corresponding to browser or primary tab view item return NSMenu() } func tabView(_ aTabView: NSTabView, shouldDrag tabViewItem: NSTabViewItem, in tabBarView: MMTabBarView) -> Bool { tabViewItem != primaryTab } func tabView(_ aTabView: NSTabView, validateDrop sender: NSDraggingInfo, proposedItem tabViewItem: NSTabViewItem, proposedIndex: UInt, in tabBarView: MMTabBarView) -> NSDragOperation { proposedIndex != 0 ? [.every] : [] } func tabView(_ aTabView: NSTabView, validateSlideOfProposedItem tabViewItem: NSTabViewItem, proposedIndex: UInt, in tabBarView: MMTabBarView) -> NSDragOperation { (tabViewItem != primaryTab && proposedIndex != 0) ? [.every] : [] } func addNewTab(to aTabView: NSTabView) { _ = self.createNewTab() } func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { let tab = (tabViewItem?.viewController as? BrowserTab) if let loaded = tab?.loadedTab, !loaded { tab?.loadTab() } } } // MARK: WKUIDelegate + BrowserContextMenuDelegate extension TabbedBrowserViewController: CustomWKUIDelegate { // TODO: implement functionality for alerts and maybe peek actions func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { let newTab = self.createNewTab(navigationAction.request, config: configuration, inBackground: false, insertAt: getIndexAfterSelected()) if let webView = webView as? CustomWKWebView { //the listeners are removed from the old webview userContentController on creating the new one, restore them webView.resetScriptListeners() } return (newTab as? BrowserTab)?.webView } func contextMenuItemsFor(purpose: WKWebViewContextMenuContext, existingMenuItems: [NSMenuItem]) -> [NSMenuItem] { var menuItems = existingMenuItems switch purpose { case .page(url: _): break case .link(let url): addLinkMenuCustomizations(&menuItems, url) case .picture: break case .pictureLink(image: _, link: let link): addLinkMenuCustomizations(&menuItems, link) case .text: break } return self.contextMenuDelegate? .contextMenuItemsFor(purpose: purpose, existingMenuItems: menuItems) ?? menuItems } private func addLinkMenuCustomizations(_ menuItems: inout [NSMenuItem], _ url: (URL)) { guard let index = menuItems.firstIndex(where: { $0.identifier == .WKMenuItemOpenLinkInNewWindow }) else { return } menuItems[index].title = NSLocalizedString("Open Link in New Tab", comment: "") let openInBackgroundTitle = NSLocalizedString("Open Link in Background", comment: "") let openInBackgroundItem = NSMenuItem(title: openInBackgroundTitle, action: #selector(openLinkInBackground(menuItem:)), keyEquivalent: "") openInBackgroundItem.identifier = .WKMenuItemOpenLinkInBackground openInBackgroundItem.representedObject = url menuItems.insert(openInBackgroundItem, at: menuItems.index(after: index)) } @objc func openLinkInBackground(menuItem: NSMenuItem) { if let url = menuItem.representedObject as? URL { _ = self.createNewTab(url, inBackground: true, load: true, insertAt: getIndexAfterSelected()) } } private func getIndexAfterSelected() -> Int { guard let tabView = tabView, let selectedItem = tabView.selectedTabViewItem else { return 0 } let selectedIndex = tabView.tabViewItems.firstIndex(of: selectedItem) ?? 0 return tabView.tabViewItems.index(after: selectedIndex) } }
apache-2.0
88464c093c37f19e69cb7807dcc6ea7e
34.538043
188
0.634883
4.799266
false
false
false
false
JadenGeller/Generational
Sources/Cycle.swift
1
980
// // Cycle.swift // Generational // // Created by Jaden Geller on 12/28/15. // Copyright © 2015 Jaden Geller. All rights reserved. // public struct CyclicSequence<Base: CollectionType>: SequenceType { private let base: Base public init(_ base: Base) { self.base = base } public func generate() -> CyclicGenerator<Base> { return CyclicGenerator(base) } } public struct CyclicGenerator<Base: CollectionType>: GeneratorType { private let base: Base private var index: Base.Index public init(_ base: Base) { self.base = base self.index = base.startIndex } public mutating func next() -> Base.Generator.Element? { let value = base[index] index = index.successor() if index == base.endIndex { index = base.startIndex } return value } } extension CollectionType { func cycle() -> CyclicSequence<Self> { return CyclicSequence(self) } }
mit
1e56a8b98f7ac9f9376b4aca25f7d565
22.333333
68
0.624106
4.238095
false
false
false
false
stephanecopin/ObjectMapper
ObjectMapperTests/NestedKeysTests.swift
3
6228
// // NestedKeysTests.swift // ObjectMapper // // Created by Syo Ikeda on 3/10/15. // Copyright (c) 2015 hearst. All rights reserved. // import Foundation import XCTest import ObjectMapper import Nimble class NestedKeysTests: 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 testNestedKeys() { let JSON: [String: AnyObject] = [ "nested": [ "int64": NSNumber(longLong: INT64_MAX), "bool": true, "int": 255, "double": 100.0 as Double, "float": 50.0 as Float, "string": "String!", "nested": [ "int64Array": [NSNumber(longLong: INT64_MAX), NSNumber(longLong: INT64_MAX - 1), NSNumber(longLong: INT64_MAX - 10)], "boolArray": [false, true, false], "intArray": [1, 2, 3], "doubleArray": [1.0, 2.0, 3.0], "floatArray": [1.0 as Float, 2.0 as Float, 3.0 as Float], "stringArray": ["123", "ABC"], "int64Dict": ["1": NSNumber(longLong: INT64_MAX)], "boolDict": ["2": true], "intDict": ["3": 999], "doubleDict": ["4": 999.999], "floatDict": ["5": 123.456 as Float], "stringDict": ["6": "InDict"], "int64Enum": 1000, "intEnum": 255, "doubleEnum": 100.0, "floatEnum": 100.0, "stringEnum": "String B", "nested": [ "object": ["value": 987], "objectArray": [ ["value": 123], ["value": 456] ], "objectDict": ["key": ["value": 999]] ] ] ] ] let mapper = Mapper<NestedKeys>() let value: NestedKeys! = mapper.map(JSON) expect(value).notTo(beNil()) let JSONFromValue = mapper.toJSON(value) let valueFromParsedJSON: NestedKeys! = mapper.map(JSONFromValue) expect(valueFromParsedJSON).notTo(beNil()) expect(value.int64).to(equal(valueFromParsedJSON.int64)) expect(value.bool).to(equal(valueFromParsedJSON.bool)) expect(value.int).to(equal(valueFromParsedJSON.int)) expect(value.double).to(equal(valueFromParsedJSON.double)) expect(value.float).to(equal(valueFromParsedJSON.float)) expect(value.string).to(equal(valueFromParsedJSON.string)) expect(value.int64Array).to(equal(valueFromParsedJSON.int64Array)) expect(value.boolArray).to(equal(valueFromParsedJSON.boolArray)) expect(value.intArray).to(equal(valueFromParsedJSON.intArray)) expect(value.doubleArray).to(equal(valueFromParsedJSON.doubleArray)) expect(value.floatArray).to(equal(valueFromParsedJSON.floatArray)) expect(value.stringArray).to(equal(valueFromParsedJSON.stringArray)) expect(value.int64Dict).to(equal(valueFromParsedJSON.int64Dict)) expect(value.boolDict).to(equal(valueFromParsedJSON.boolDict)) expect(value.intDict).to(equal(valueFromParsedJSON.intDict)) expect(value.doubleDict).to(equal(valueFromParsedJSON.doubleDict)) expect(value.floatDict).to(equal(valueFromParsedJSON.floatDict)) expect(value.stringDict).to(equal(valueFromParsedJSON.stringDict)) expect(value.int64Enum).to(equal(valueFromParsedJSON.int64Enum)) expect(value.intEnum).to(equal(valueFromParsedJSON.intEnum)) expect(value.doubleEnum).to(equal(valueFromParsedJSON.doubleEnum)) expect(value.floatEnum).to(equal(valueFromParsedJSON.floatEnum)) expect(value.stringEnum).to(equal(valueFromParsedJSON.stringEnum)) expect(value.object).to(equal(valueFromParsedJSON.object)) expect(value.objectArray).to(equal(valueFromParsedJSON.objectArray)) expect(value.objectDict).to(equal(valueFromParsedJSON.objectDict)) } } class NestedKeys: Mappable { var int64: NSNumber? var bool: Bool? var int: Int? var double: Double? var float: Float? var string: String? var int64Array: [NSNumber] = [] var boolArray: [Bool] = [] var intArray: [Int] = [] var doubleArray: [Double] = [] var floatArray: [Float] = [] var stringArray: [String] = [] var int64Dict: [String: NSNumber] = [:] var boolDict: [String: Bool] = [:] var intDict: [String: Int] = [:] var doubleDict: [String: Double] = [:] var floatDict: [String: Float] = [:] var stringDict: [String: String] = [:] var int64Enum: Int64Enum? var intEnum: IntEnum? var doubleEnum: DoubleEnum? var floatEnum: FloatEnum? var stringEnum: StringEnum? var object: Object? var objectArray: [Object] = [] var objectDict: [String: Object] = [:] static func newInstance() -> Mappable { return NestedKeys() } func mapping(map: Map) { int64 <- map["nested.int64"] bool <- map["nested.bool"] int <- map["nested.int"] double <- map["nested.double"] float <- map["nested.float"] string <- map["nested.string"] int64Array <- map["nested.nested.int64Array"] boolArray <- map["nested.nested.boolArray"] intArray <- map["nested.nested.intArray"] doubleArray <- map["nested.nested.doubleArray"] floatArray <- map["nested.nested.floatArray"] stringArray <- map["nested.nested.stringArray"] int64Dict <- map["nested.nested.int64Dict"] boolDict <- map["nested.nested.boolDict"] intDict <- map["nested.nested.intDict"] doubleDict <- map["nested.nested.doubleDict"] floatDict <- map["nested.nested.floatDict"] stringDict <- map["nested.nested.stringDict"] int64Enum <- map["nested.nested.int64Enum"] intEnum <- map["nested.nested.intEnum"] doubleEnum <- map["nested.nested.doubleEnum"] floatEnum <- map["nested.nested.floatEnum"] stringEnum <- map["nested.nested.stringEnum"] object <- map["nested.nested.nested.object"] objectArray <- map["nested.nested.nested.objectArray"] objectDict <- map["nested.nested.nested.objectDict"] } } class Object: Mappable, Equatable { var value: Int = Int.min static func newInstance() -> Mappable { return Object() } func mapping(map: Map) { value <- map["value"] } } func == (lhs: Object, rhs: Object) -> Bool { return lhs.value == rhs.value } enum Int64Enum: NSNumber { case A = 0 case B = 1000 } enum IntEnum: Int { case A = 0 case B = 255 } enum DoubleEnum: Double { case A = 0.0 case B = 100.0 } enum FloatEnum: Float { case A = 0.0 case B = 100.0 } enum StringEnum: String { case A = "String A" case B = "String B" }
mit
8ddd0b0e2be482c06b87dbc747778265
27.568807
122
0.688022
3.203704
false
false
false
false
steelwheels/KiwiControls
Source/Controls/KCCheckBoxCore.swift
1
4312
/* * @file KCCheckBoxCore.swift * @brief Define KCCheckBoxCore class * @par Copyright * Copyright (C) 2016 Steel Wheels Project */ #if os(iOS) import UIKit #else import Cocoa #endif import CoconutData public class KCCheckBoxCore: KCCoreView { #if os(iOS) @IBOutlet weak var mSwitch: UISwitch! @IBOutlet weak var mLabel: UILabel! #else @IBOutlet weak var mCheckBox: NSButton! #endif public var checkUpdatedCallback: ((_ value: Bool) -> Void)? = nil public func setup(frame frm: CGRect) -> Void { #if os(OSX) super.setup(isSingleView: true, coreView: mCheckBox) KCView.setAutolayoutMode(views: [self, mCheckBox]) #else super.setup(isSingleView: false, coreView: mSwitch) KCView.setAutolayoutMode(views: [self, mSwitch, mLabel]) #endif } #if os(iOS) @IBAction func checkUpdated(_ sender: UISwitch) { if let updatecallback = checkUpdatedCallback { let ison = sender.isOn updatecallback(ison) } } #else @IBAction func checkUpdated(_ sender: NSButton) { if let updatecallback = checkUpdatedCallback { let ison = (sender.state == .on) updatecallback(ison) } } #endif public var title: String { get { #if os(iOS) if let text = mLabel.text { return text } else { return "" } #else return mCheckBox.title #endif } set(newval){ #if os(iOS) self.mLabel.text = newval #else self.mCheckBox.title = newval #endif } } public var isEnabled: Bool { get { #if os(iOS) return mSwitch.isEnabled #else return mCheckBox.isEnabled #endif } set(newval){ #if os(iOS) self.mSwitch.isEnabled = newval self.mLabel.isEnabled = newval #else self.mCheckBox.isEnabled = newval #endif } } public var isVisible: Bool { get { #if os(iOS) return !(mSwitch.isHidden) #else return !(mCheckBox.isHidden) #endif } set(newval){ #if os(iOS) self.mSwitch.isHidden = !newval self.mLabel.isHidden = !newval #else self.mCheckBox.isHidden = !newval #endif } } public var status: Bool { get { let result: Bool #if os(OSX) switch mCheckBox.state { case .mixed: result = false case .off: result = false case .on: result = true default: result = false } #else result = mSwitch.isOn #endif return result } set(newval) { #if os(OSX) mCheckBox.state = newval ? .on : .off #else mSwitch.isOn = newval #endif } } open override func setFrameSize(_ newsize: CGSize) { super.setFrameSize(newsize) #if os(iOS) let totalwidth = newsize.width var labelwidth = mLabel.intrinsicContentSize.width var switchwidth = totalwidth - labelwidth if switchwidth < 0.0 { labelwidth = totalwidth / 2.0 switchwidth = totalwidth / 2.0 } mSwitch.setFrame(size: CGSize(width: switchwidth, height: newsize.height)) mLabel.setFrame(size: CGSize(width: labelwidth, height: newsize.height)) #endif } #if os(OSX) open override var fittingSize: CGSize { get { return contentSize() } } #else open override func sizeThatFits(_ size: CGSize) -> CGSize { return contentSize() } #endif open override var intrinsicContentSize: CGSize { get { return contentSize() } } private func contentSize() -> CGSize { #if os(iOS) let labelsize = mLabel.intrinsicContentSize let switchsize = mSwitch.intrinsicContentSize let space = CNPreference.shared.windowPreference.spacing return CNUnionSize(sizeA: labelsize, sizeB: switchsize, doVertical: false, spacing: space) #else return super.intrinsicContentSize #endif } public override func invalidateIntrinsicContentSize() { super.invalidateIntrinsicContentSize() #if os(iOS) mLabel.invalidateIntrinsicContentSize() #endif } public override func setExpandabilities(priorities prival: KCViewBase.ExpansionPriorities) { super.setExpandabilities(priorities: prival) #if os(OSX) mCheckBox.setExpansionPriorities(priorities: prival) #else let fixpri = KCViewBase.ExpansionPriorities(holizontalHugging: .fixed, holizontalCompression: .fixed, verticalHugging: .fixed, verticalCompression: .fixed) mSwitch.setExpansionPriorities(priorities: fixpri) mLabel.setExpansionPriorities(priorities: prival) #endif } }
lgpl-2.1
a7d59fbec24809c3d97091e2b31b8563
21.112821
93
0.681818
3.136
false
false
false
false
imzyf/99-projects-of-swift
020-pinterest/Pinterest/Views/AnnotatedPhotoCell.swift
1
2297
/** * Copyright (c) 2017 Razeware LLC * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class AnnotatedPhotoCell: UICollectionViewCell { @IBOutlet fileprivate weak var containerView: UIView! @IBOutlet fileprivate weak var imageView: UIImageView! @IBOutlet fileprivate weak var captionLabel: UILabel! @IBOutlet fileprivate weak var commentLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() containerView.layer.cornerRadius = 6 containerView.layer.masksToBounds = true } var photo: Photo? { didSet { if let photo = photo { imageView.image = photo.image captionLabel.text = photo.caption commentLabel.text = photo.comment } } } }
mit
2125500336fc1afcc1ee271a08eca32a
40.017857
82
0.747061
4.76556
false
false
false
false
badoo/FreehandDrawing-iOS
FreehandDrawing-iOS/DrawViewController.swift
1
1769
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit class DrawViewController: UIViewController { override func viewDidLoad() { self.drawController = FreehandDrawController(canvas: self.drawView, view: self.drawView) self.drawController.width = 3.0 self.toolbar.colorChangeHandler = { [unowned self] color in self.drawController.color = color } self.toolbar.undoHandler = { [unowned self] in self.drawController.undo() } } var drawView: DrawView { return self.view as! DrawView } private var drawController: FreehandDrawController! @IBOutlet var toolbar: Toolbar! }
mit
0f2e96c13ebaf987086e7e4df4b4a03c
35.102041
96
0.734878
4.679894
false
false
false
false
kpedersen00/patronus
Patronus/blah.swift
1
3283
// // blah.swift // Patronus // // Created by Monica Sun on 7/12/15. // Copyright (c) 2015 Monica Sun. All rights reserved. // import UIKit class blah: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
8dc55c54700adf6064ed2d2f90ee0514
32.845361
157
0.680475
5.517647
false
false
false
false
RubyNative/RubyKit
Data.swift
2
2559
// // Data.swift // SwiftRuby // // Created by John Holdsworth on 26/09/2015. // Copyright © 2015 John Holdsworth. All rights reserved. // // $Id: //depot/SwiftRuby/Data.swift#11 $ // // Repo: https://github.com/RubyNative/SwiftRuby // // See: http://ruby-doc.org/core-2.2.3/Data.html // import Darwin public protocol data_like { var to_d: Data { get } } public func ==(lhs: Data, rhs: Data) -> Bool { return lhs.length == rhs.length && memcmp(lhs.bytes, rhs.bytes, lhs.length) == 0 } open class Data: RubyObject, string_like, array_like, char_like, data_like { open var bytes: UnsafeMutablePointer<Int8> open var length = 0 { didSet { if length > capacity { SRFatal("Data length \(length) > capacity \(capacity)", file: #file, line: #line) } bytes[length] = 0 } } open var capacity = 0 { didSet { bytes = realloc(bytes, capacity+1)!.assumingMemoryBound(to: Int8.self) } } public init(bytes: UnsafeMutablePointer<Int8>, length: Int = 0) { self.bytes = bytes self.length = length super.init() } public convenience init(capacity: Int? = 0) { let capacity = capacity ?? 10 * 1024 self.init(bytes: malloc(capacity+1)!.assumingMemoryBound(to: Int8.self)) self.capacity = capacity } public convenience init(array: [CChar]) { let alen = array.count self.init(capacity: alen) memcpy(bytes, array, alen) length = alen-1 } open func append(_ extra: data_like) -> Int { let extra = extra.to_d let required = length + extra.length if required + 1 > capacity { capacity += max(required - capacity, 10_000) } memcpy(bytes+length, extra.bytes, extra.length) length += extra.length return extra.length } open var to_a: [String] { return [to_s] } open var to_c: [CChar] { var data = [CChar](repeating: 0, count: length+1) /// memcpy(&data, bytes, data.count) return data } open var to_d: Data { return self } open var to_s: String { if let string = String(cString: bytes, encoding: STRING_ENCODING) { return string } SRLog("Data.to_s: Could not decode string from input") return U(String(cString: bytes, encoding: FALLBACK_INPUT_ENCODING)) } deinit { if capacity != 0 { free(bytes) } } }
mit
7c6f409a0f36f9cb823a27c7c2ac746b
23.361905
97
0.565676
3.723435
false
false
false
false
pietbrauer/Beverages
Beverages/AppDelegate.swift
2
699
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) if let window = window { let viewController = ViewController(style: .Plain) let navigationController = UINavigationController(rootViewController: viewController) window.rootViewController = navigationController window.backgroundColor = UIColor.whiteColor() window.makeKeyAndVisible() } return true } }
mit
087b12edc263122c22756212bdb6e253
33.95
127
0.69814
6.354545
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch14/14.2.1构造器重载概念.playground/section-1.swift
1
1296
// 本书网站:http://www.51work6.com/swift.php // 智捷iOS课堂在线课堂:http://v.51work6.com // 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973 // 智捷iOS课堂微信公共账号:智捷iOS课堂 // 作者微博:http://weibo.com/516inc // 官方csdn博客:http://blog.csdn.net/tonny_guan // Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected] class Rectangle { var width : Double var height : Double init(width : Double, height : Double) { self.width = width self.height = height } init(W width : Double,H height : Double) { self.width = width self.height = height } init(length : Double) { self.width = length self.height = length } init() { self.width = 640.0 self.height = 940.0 } } var rectc1 = Rectangle(width : 320.0, height : 480.0) println("长方形1:\(rectc1.width) x \(rectc1.height)") var rectc2 = Rectangle(W : 320.0, H : 480.0) println("长方形2:\(rectc2.width) x \(rectc2.height)") var rectc3 = Rectangle(length: 500.0) println("长方形3:\(rectc3.width) x \(rectc3.height)") var rectc4 = Rectangle() println("长方形4:\(rectc4.width) x \(rectc4.height)")
gpl-2.0
38deb0c288f89f6f6e7b0bf9a9e43a82
23.531915
62
0.609375
2.851485
false
false
false
false
JohnEstropia/CoreStore
Sources/CustomSchemaMappingProvider.swift
1
37820
// // CustomSchemaMappingProvider.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import CoreData import Foundation // MARK: - CustomSchemaMappingProvider /** A `SchemaMappingProvider` that accepts custom mappings for some entities. Mappings of entities with no `CustomMapping` provided will be automatically calculated if possible. */ public class CustomSchemaMappingProvider: Hashable, SchemaMappingProvider { /** The source model version for the mapping. */ public let sourceVersion: ModelVersion /** The destination model version for the mapping. */ public let destinationVersion: ModelVersion /** Creates a `CustomSchemaMappingProvider` - parameter sourceVersion: the source model version for the mapping - parameter destinationVersion: the destination model version for the mapping - parameter entityMappings: a list of `CustomMapping`s. Mappings of entities with no `CustomMapping` provided will be automatically calculated if possible. Any conflicts or ambiguity will raise an assertion. */ public required init(from sourceVersion: ModelVersion, to destinationVersion: ModelVersion, entityMappings: Set<CustomMapping> = []) { Internals.assert( Internals.with { let sources = entityMappings.compactMap({ $0.entityMappingSourceEntity }) let destinations = entityMappings.compactMap({ $0.entityMappingDestinationEntity }) return sources.count == Set(sources).count && destinations.count == Set(destinations).count }, "Duplicate source/destination entities found in provided \"entityMappings\" argument." ) self.sourceVersion = sourceVersion self.destinationVersion = destinationVersion self.entityMappings = entityMappings } // MARK: - CustomMapping /** Provides the type of mapping for an entity. Mappings of entities with no `CustomMapping` provided will be automatically calculated if possible. Any conflicts or ambiguity will raise an assertion. */ public enum CustomMapping: Hashable { /** The `sourceEntity` is meant to be removed from the source `DynamicSchema` and should not be migrated to the destination `DynamicSchema`. */ case deleteEntity(sourceEntity: EntityName) /** The `destinationEntity` is newly added to the destination `DynamicSchema` and has no mapping from the source `DynamicSchema`. */ case insertEntity(destinationEntity: EntityName) /** The `DynamicSchema`s entity has no changes and can be copied directly from `sourceEntity` to `destinationEntity`. */ case copyEntity(sourceEntity: EntityName, destinationEntity: EntityName) /** The `DynamicSchema`s entity needs transformations from `sourceEntity` to `destinationEntity`. The `transformer` closure will be used to apply the changes. The `CustomMapping.inferredTransformation` method can be used directly as the `transformer` if the changes can be inferred (i.e. lightweight). */ case transformEntity(sourceEntity: EntityName, destinationEntity: EntityName, transformer: Transformer) /** The closure type for `CustomMapping.transformEntity`. - parameter sourceObject: a proxy object representing the source entity. The properties can be accessed via keyPath. - parameter createDestinationObject: the closure to create the object for the destination entity. The `CustomMapping.inferredTransformation` method can be used directly as the `transformer` if the changes can be inferred (i.e. lightweight). The object is created lazily and executing the closure multiple times will return the same instance. The destination object's properties can be accessed and updated via keyPath. */ public typealias Transformer = (_ sourceObject: UnsafeSourceObject, _ createDestinationObject: () -> UnsafeDestinationObject) throws -> Void /** The `CustomMapping.inferredTransformation` method can be used directly as the `transformer` if the changes can be inferred (i.e. lightweight). */ public static func inferredTransformation(_ sourceObject: UnsafeSourceObject, _ createDestinationObject: () -> UnsafeDestinationObject) throws -> Void { let destinationObject = createDestinationObject() destinationObject.enumerateAttributes { (attribute, sourceAttribute) in if let sourceAttribute = sourceAttribute { destinationObject[attribute] = sourceObject[sourceAttribute] } } } // MARK: Equatable public static func == (lhs: CustomMapping, rhs: CustomMapping) -> Bool { switch (lhs, rhs) { case (.deleteEntity(let sourceEntity1), .deleteEntity(let sourceEntity2)): return sourceEntity1 == sourceEntity2 case (.insertEntity(let destinationEntity1), .insertEntity(let destinationEntity2)): return destinationEntity1 == destinationEntity2 case (.copyEntity(let sourceEntity1, let destinationEntity1), .copyEntity(let sourceEntity2, let destinationEntity2)): return sourceEntity1 == sourceEntity2 && destinationEntity1 == destinationEntity2 case (.transformEntity(let sourceEntity1, let destinationEntity1, _), .transformEntity(let sourceEntity2, let destinationEntity2, _)): return sourceEntity1 == sourceEntity2 && destinationEntity1 == destinationEntity2 default: return false } } // MARK: Hashable public func hash(into hasher: inout Hasher) { switch self { case .deleteEntity(let sourceEntity): hasher.combine(0) hasher.combine(sourceEntity) case .insertEntity(let destinationEntity): hasher.combine(1) hasher.combine(destinationEntity) case .copyEntity(let sourceEntity, let destinationEntity): hasher.combine(2) hasher.combine(sourceEntity) hasher.combine(destinationEntity) case .transformEntity(let sourceEntity, let destinationEntity, _): hasher.combine(3) hasher.combine(sourceEntity) hasher.combine(destinationEntity) } } // MARK: FilePrivate fileprivate var entityMappingSourceEntity: EntityName? { switch self { case .deleteEntity(let sourceEntity), .copyEntity(let sourceEntity, _), .transformEntity(let sourceEntity, _, _): return sourceEntity case .insertEntity: return nil } } fileprivate var entityMappingDestinationEntity: EntityName? { switch self { case .insertEntity(let destinationEntity), .copyEntity(_, let destinationEntity), .transformEntity(_, let destinationEntity, _): return destinationEntity case .deleteEntity: return nil } } } // MARK: - UnsafeSourceObject /** The read-only proxy object used for the source object in a mapping's `Transformer` closure. Properties can be accessed either by keyPath string or by `NSAttributeDescription`. */ public final class UnsafeSourceObject { /** Accesses the property value via its keyPath. */ public subscript(attribute: KeyPathString) -> Any? { return self.rawObject.getValue(forKvcKey: attribute) } /** Accesses the property value via its `NSAttributeDescription`, which can be accessed from the `enumerateAttributes(_:)` method. */ public subscript(attribute: NSAttributeDescription) -> Any? { return self.rawObject.getValue(forKvcKey: attribute.name) } /** Enumerates the all `NSAttributeDescription`s. The `attribute` argument can be used as the subscript key to access the property. */ public func enumerateAttributes(_ closure: (_ attribute: NSAttributeDescription) -> Void) { func enumerate(_ entity: NSEntityDescription, _ closure: (NSAttributeDescription) -> Void) { if let superEntity = entity.superentity { enumerate(superEntity, closure) } for case let attribute as NSAttributeDescription in entity.properties { closure(attribute) } } enumerate(self.rawObject.entity, closure) } // MARK: Internal internal init(_ rawObject: NSManagedObject) { self.rawObject = rawObject } // MARK: Private private let rawObject: NSManagedObject } // MARK: - UnsafeDestinationObject /** The read-write proxy object used for the destination object that can be created in a mapping's `Transformer` closure. Properties can be accessed and mutated either through keyPath string or by `NSAttributeDescription`. */ public final class UnsafeDestinationObject { /** Accesses or mutates the property value via its keyPath. */ public subscript(attribute: KeyPathString) -> Any? { get { return self.rawObject.getValue(forKvcKey: attribute) } set { self.rawObject.setValue(newValue, forKvcKey: attribute) } } /** Accesses or mutates the property value via its `NSAttributeDescription`, which can be accessed from the `enumerateAttributes(_:)` method. */ public subscript(attribute: NSAttributeDescription) -> Any? { get { return self.rawObject.getValue(forKvcKey: attribute.name) } set { self.rawObject.setValue(newValue, forKvcKey: attribute.name) } } /** Enumerates the all `NSAttributeDescription`s. The `attribute` argument can be used as the subscript key to access and mutate the property. The `sourceAttribute` can be used to access properties from the source `UnsafeSourceObject`. */ public func enumerateAttributes(_ closure: (_ attribute: NSAttributeDescription, _ sourceAttribute: NSAttributeDescription?) -> Void) { func enumerate(_ entity: NSEntityDescription, _ closure: (_ attribute: NSAttributeDescription, _ sourceAttribute: NSAttributeDescription?) -> Void) { if let superEntity = entity.superentity { enumerate(superEntity, closure) } for case let attribute as NSAttributeDescription in entity.properties { closure(attribute, self.sourceAttributesByDestinationKey[attribute.name]) } } enumerate(self.rawObject.entity, closure) } // MARK: Internal internal init(_ rawObject: NSManagedObject, _ sourceAttributesByDestinationKey: [KeyPathString: NSAttributeDescription]) { self.rawObject = rawObject self.sourceAttributesByDestinationKey = sourceAttributesByDestinationKey } // MARK: FilePrivate fileprivate let rawObject: NSManagedObject fileprivate let sourceAttributesByDestinationKey: [KeyPathString: NSAttributeDescription] } // MARK: Equatable public static func == (lhs: CustomSchemaMappingProvider, rhs: CustomSchemaMappingProvider) -> Bool { return lhs.sourceVersion == rhs.sourceVersion && lhs.destinationVersion == rhs.destinationVersion } // MARK: Hashable public func hash(into hasher: inout Hasher) { hasher.combine(self.sourceVersion) hasher.combine(self.destinationVersion) hasher.combine(ObjectIdentifier(Self.self)) } // MARK: SchemaMappingProvider public func cs_createMappingModel(from sourceSchema: DynamicSchema, to destinationSchema: DynamicSchema, storage: LocalStorage) throws -> (mappingModel: NSMappingModel, migrationType: MigrationType) { let sourceModel = sourceSchema.rawModel() let destinationModel = destinationSchema.rawModel() let mappingModel = NSMappingModel() let (deleteMappings, insertMappings, copyMappings, transformMappings) = self.resolveEntityMappings( sourceModel: sourceModel, destinationModel: destinationModel ) func expression(forSource sourceEntity: NSEntityDescription) -> NSExpression { return NSExpression(format: "FETCH(FUNCTION($\(NSMigrationManagerKey), \"fetchRequestForSourceEntityNamed:predicateString:\" , \"\(sourceEntity.name!)\", \"\(NSPredicate(value: true))\"), FUNCTION($\(NSMigrationManagerKey), \"\(#selector(getter: NSMigrationManager.sourceContext))\"), \(false))") } let sourceEntitiesByName = sourceModel.entitiesByName let destinationEntitiesByName = destinationModel.entitiesByName var entityMappings: [NSEntityMapping] = [] for case .deleteEntity(let sourceEntityName) in deleteMappings { let sourceEntity = sourceEntitiesByName[sourceEntityName]! let entityMapping = NSEntityMapping() entityMapping.sourceEntityName = sourceEntity.name entityMapping.sourceEntityVersionHash = sourceEntity.versionHash entityMapping.mappingType = .removeEntityMappingType entityMapping.sourceExpression = expression(forSource: sourceEntity) entityMappings.append(entityMapping) } for case .insertEntity(let destinationEntityName) in insertMappings { let destinationEntity = destinationEntitiesByName[destinationEntityName]! let entityMapping = NSEntityMapping() entityMapping.destinationEntityName = destinationEntity.name entityMapping.destinationEntityVersionHash = destinationEntity.versionHash entityMapping.mappingType = .addEntityMappingType entityMapping.attributeMappings = autoreleasepool { () -> [NSPropertyMapping] in var attributeMappings: [NSPropertyMapping] = [] for (_, destinationAttribute) in destinationEntity.attributesByName { let propertyMapping = NSPropertyMapping() propertyMapping.name = destinationAttribute.name attributeMappings.append(propertyMapping) } return attributeMappings } entityMapping.relationshipMappings = autoreleasepool { () -> [NSPropertyMapping] in var relationshipMappings: [NSPropertyMapping] = [] for (_, destinationRelationship) in destinationEntity.relationshipsByName { let propertyMapping = NSPropertyMapping() propertyMapping.name = destinationRelationship.name relationshipMappings.append(propertyMapping) } return relationshipMappings } entityMappings.append(entityMapping) } for case .copyEntity(let sourceEntityName, let destinationEntityName) in copyMappings { let sourceEntity = sourceEntitiesByName[sourceEntityName]! let destinationEntity = destinationEntitiesByName[destinationEntityName]! let entityMapping = NSEntityMapping() entityMapping.sourceEntityName = sourceEntity.name entityMapping.sourceEntityVersionHash = sourceEntity.versionHash entityMapping.destinationEntityName = destinationEntity.name entityMapping.destinationEntityVersionHash = destinationEntity.versionHash entityMapping.mappingType = .copyEntityMappingType entityMapping.sourceExpression = expression(forSource: sourceEntity) entityMapping.attributeMappings = autoreleasepool { () -> [NSPropertyMapping] in let sourceAttributes = sourceEntity.cs_resolveAttributeNames() let destinationAttributes = destinationEntity.cs_resolveAttributeRenamingIdentities() var attributeMappings: [NSPropertyMapping] = [] for (renamingIdentifier, destination) in destinationAttributes { let sourceAttribute = sourceAttributes[renamingIdentifier]!.attribute let destinationAttribute = destination.attribute let propertyMapping = NSPropertyMapping() propertyMapping.name = destinationAttribute.name propertyMapping.valueExpression = NSExpression(format: "FUNCTION($\(NSMigrationSourceObjectKey), \"\(#selector(NSManagedObject.value(forKey:)))\", \"\(sourceAttribute.name)\")") attributeMappings.append(propertyMapping) } return attributeMappings } entityMapping.relationshipMappings = autoreleasepool { () -> [NSPropertyMapping] in let sourceRelationships = sourceEntity.cs_resolveRelationshipNames() let destinationRelationships = destinationEntity.cs_resolveRelationshipRenamingIdentities() var relationshipMappings: [NSPropertyMapping] = [] for (renamingIdentifier, destination) in destinationRelationships { let sourceRelationship = sourceRelationships[renamingIdentifier]!.relationship let destinationRelationship = destination.relationship let sourceRelationshipName = sourceRelationship.name let propertyMapping = NSPropertyMapping() propertyMapping.name = destinationRelationship.name propertyMapping.valueExpression = NSExpression(format: "FUNCTION($\(NSMigrationManagerKey), \"destinationInstancesForSourceRelationshipNamed:sourceInstances:\", \"\(sourceRelationshipName)\", FUNCTION($\(NSMigrationSourceObjectKey), \"\(#selector(NSManagedObject.value(forKey:)))\", \"\(sourceRelationshipName)\"))") relationshipMappings.append(propertyMapping) } return relationshipMappings } entityMappings.append(entityMapping) } for case .transformEntity(let sourceEntityName, let destinationEntityName, let transformEntity) in transformMappings { let sourceEntity = sourceEntitiesByName[sourceEntityName]! let destinationEntity = destinationEntitiesByName[destinationEntityName]! let entityMapping = NSEntityMapping() entityMapping.sourceEntityName = sourceEntity.name entityMapping.sourceEntityVersionHash = sourceEntity.versionHash entityMapping.destinationEntityName = destinationEntity.name entityMapping.destinationEntityVersionHash = destinationEntity.versionHash entityMapping.mappingType = .customEntityMappingType entityMapping.sourceExpression = expression(forSource: sourceEntity) entityMapping.entityMigrationPolicyClassName = NSStringFromClass(CustomEntityMigrationPolicy.self) var userInfo: [AnyHashable: Any] = [ CustomEntityMigrationPolicy.UserInfoKey.transformer: transformEntity ] autoreleasepool { let sourceAttributes = sourceEntity.cs_resolveAttributeNames() let destinationAttributes = destinationEntity.cs_resolveAttributeRenamingIdentities() let transformedRenamingIdentifiers = Set(destinationAttributes.keys) .intersection(sourceAttributes.keys) var sourceAttributesByDestinationKey: [KeyPathString: NSAttributeDescription] = [:] for renamingIdentifier in transformedRenamingIdentifiers { let sourceAttribute = sourceAttributes[renamingIdentifier]!.attribute let destinationAttribute = destinationAttributes[renamingIdentifier]!.attribute sourceAttributesByDestinationKey[destinationAttribute.name] = sourceAttribute } userInfo[CustomEntityMigrationPolicy.UserInfoKey.sourceAttributesByDestinationKey] = sourceAttributesByDestinationKey } entityMapping.relationshipMappings = autoreleasepool { () -> [NSPropertyMapping] in let sourceRelationships = sourceEntity.cs_resolveRelationshipNames() let destinationRelationships = destinationEntity.cs_resolveRelationshipRenamingIdentities() let transformedRenamingIdentifiers = Set(destinationRelationships.keys) .intersection(sourceRelationships.keys) var relationshipMappings: [NSPropertyMapping] = [] for renamingIdentifier in transformedRenamingIdentifiers { let sourceRelationship = sourceRelationships[renamingIdentifier]!.relationship let destinationRelationship = destinationRelationships[renamingIdentifier]!.relationship let sourceRelationshipName = sourceRelationship.name let destinationRelationshipName = destinationRelationship.name let propertyMapping = NSPropertyMapping() propertyMapping.name = destinationRelationshipName propertyMapping.valueExpression = NSExpression(format: "FUNCTION($\(NSMigrationManagerKey), \"destinationInstancesForSourceRelationshipNamed:sourceInstances:\", \"\(sourceRelationshipName)\", FUNCTION($\(NSMigrationSourceObjectKey), \"\(#selector(NSManagedObject.value(forKey:)))\", \"\(sourceRelationshipName)\"))") relationshipMappings.append(propertyMapping) } return relationshipMappings } entityMapping.userInfo = userInfo entityMappings.append(entityMapping) } mappingModel.entityMappings = entityMappings return ( mappingModel, .heavyweight( sourceVersion: self.sourceVersion, destinationVersion: self.destinationVersion ) ) } // MARK: Private // MARK: - CustomEntityMigrationPolicy private final class CustomEntityMigrationPolicy: NSEntityMigrationPolicy { // MARK: NSEntityMigrationPolicy override func createDestinationInstances(forSource sInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws { let userInfo = mapping.userInfo! let transformer = userInfo[CustomEntityMigrationPolicy.UserInfoKey.transformer]! as! CustomMapping.Transformer let sourceAttributesByDestinationKey = userInfo[CustomEntityMigrationPolicy.UserInfoKey.sourceAttributesByDestinationKey] as! [KeyPathString: NSAttributeDescription] var destinationObject: UnsafeDestinationObject? try transformer( UnsafeSourceObject(sInstance), { if let destinationObject = destinationObject { return destinationObject } let rawObject = NSEntityDescription.insertNewObject( forEntityName: mapping.destinationEntityName!, into: manager.destinationContext ) destinationObject = UnsafeDestinationObject(rawObject, sourceAttributesByDestinationKey) return destinationObject! } ) if let dInstance = destinationObject?.rawObject { manager.associate(sourceInstance: sInstance, withDestinationInstance: dInstance, for: mapping) } } override func createRelationships(forDestination dInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws { try super.createRelationships(forDestination: dInstance, in: mapping, manager: manager) } // MARK: FilePrivate fileprivate enum UserInfoKey { fileprivate static let transformer = "CoreStore.CustomEntityMigrationPolicy.transformer" fileprivate static let sourceAttributesByDestinationKey = "CoreStore.CustomEntityMigrationPolicy.sourceAttributesByDestinationKey" } } // MARK: - private let entityMappings: Set<CustomMapping> private func resolveEntityMappings(sourceModel: NSManagedObjectModel, destinationModel: NSManagedObjectModel) -> (delete: Set<CustomMapping>, insert: Set<CustomMapping>, copy: Set<CustomMapping>, transform: Set<CustomMapping>) { var deleteMappings: Set<CustomMapping> = [] var insertMappings: Set<CustomMapping> = [] var copyMappings: Set<CustomMapping> = [] var transformMappings: Set<CustomMapping> = [] var allMappedSourceKeys: [KeyPathString: KeyPathString] = [:] var allMappedDestinationKeys: [KeyPathString: KeyPathString] = [:] let sourceRenamingIdentifiers = sourceModel.cs_resolveNames() let sourceEntityNames = sourceModel.entitiesByName let destinationRenamingIdentifiers = destinationModel.cs_resolveRenamingIdentities() let destinationEntityNames = destinationModel.entitiesByName let removedRenamingIdentifiers = Set(sourceRenamingIdentifiers.keys) .subtracting(destinationRenamingIdentifiers.keys) let addedRenamingIdentifiers = Set(destinationRenamingIdentifiers.keys) .subtracting(sourceRenamingIdentifiers.keys) let transformedRenamingIdentifiers = Set(destinationRenamingIdentifiers.keys) .subtracting(addedRenamingIdentifiers) .subtracting(removedRenamingIdentifiers) // First pass: resolve source-destination entities for mapping in self.entityMappings { switch mapping { case .deleteEntity(let sourceEntity): Internals.assert( sourceEntityNames[sourceEntity] != nil, "A \(Internals.typeName(CustomMapping.self)) with value '\(mapping)' passed to \(Internals.typeName(CustomSchemaMappingProvider.self)) could not be mapped to any \(Internals.typeName(NSEntityDescription.self)) from the source \(Internals.typeName(NSManagedObjectModel.self))." ) Internals.assert( allMappedSourceKeys[sourceEntity] == nil, "Duplicate \(Internals.typeName(CustomMapping.self))s found for source entity name \"\(sourceEntity)\" in \(Internals.typeName(CustomSchemaMappingProvider.self))." ) deleteMappings.insert(mapping) allMappedSourceKeys[sourceEntity] = "" case .insertEntity(let destinationEntity): Internals.assert( destinationEntityNames[destinationEntity] != nil, "A \(Internals.typeName(CustomMapping.self)) with value '\(mapping)' passed to \(Internals.typeName(CustomSchemaMappingProvider.self)) could not be mapped to any \(Internals.typeName(NSEntityDescription.self)) from the destination \(Internals.typeName(NSManagedObjectModel.self))." ) Internals.assert( allMappedDestinationKeys[destinationEntity] == nil, "Duplicate \(Internals.typeName(CustomMapping.self))s found for destination entity name \"\(destinationEntity)\" in \(Internals.typeName(CustomSchemaMappingProvider.self))." ) insertMappings.insert(mapping) allMappedDestinationKeys[destinationEntity] = "" case .transformEntity(let sourceEntity, let destinationEntity, _): Internals.assert( sourceEntityNames[sourceEntity] != nil, "A \(Internals.typeName(CustomMapping.self)) with value '\(mapping)' passed to \(Internals.typeName(CustomSchemaMappingProvider.self)) could not be mapped to any \(Internals.typeName(NSEntityDescription.self)) from the source \(Internals.typeName(NSManagedObjectModel.self))." ) Internals.assert( destinationEntityNames[destinationEntity] != nil, "A \(Internals.typeName(CustomMapping.self)) with value '\(mapping)' passed to \(Internals.typeName(CustomSchemaMappingProvider.self)) could not be mapped to any \(Internals.typeName(NSEntityDescription.self)) from the destination \(Internals.typeName(NSManagedObjectModel.self))." ) Internals.assert( allMappedSourceKeys[sourceEntity] == nil, "Duplicate \(Internals.typeName(CustomMapping.self))s found for source entity name \"\(sourceEntity)\" in \(Internals.typeName(CustomSchemaMappingProvider.self))." ) Internals.assert( allMappedDestinationKeys[destinationEntity] == nil, "Duplicate \(Internals.typeName(CustomMapping.self))s found for destination entity name \"\(destinationEntity)\" in \(Internals.typeName(CustomSchemaMappingProvider.self))." ) transformMappings.insert(mapping) allMappedSourceKeys[sourceEntity] = destinationEntity allMappedDestinationKeys[destinationEntity] = sourceEntity case .copyEntity(let sourceEntity, let destinationEntity): Internals.assert( sourceEntityNames[sourceEntity] != nil, "A \(Internals.typeName(CustomMapping.self)) with value '\(mapping)' passed to \(Internals.typeName(CustomSchemaMappingProvider.self)) could not be mapped to any \(Internals.typeName(NSEntityDescription.self)) from the source \(Internals.typeName(NSManagedObjectModel.self))." ) Internals.assert( destinationEntityNames[destinationEntity] != nil, "A \(Internals.typeName(CustomMapping.self)) with value '\(mapping)' passed to \(Internals.typeName(CustomSchemaMappingProvider.self)) could not be mapped to any \(Internals.typeName(NSEntityDescription.self)) from the destination \(Internals.typeName(NSManagedObjectModel.self))." ) Internals.assert( sourceEntityNames[sourceEntity]!.versionHash == destinationEntityNames[destinationEntity]!.versionHash, "A \(Internals.typeName(CustomMapping.self)) with value '\(mapping)' was passed to \(Internals.typeName(CustomSchemaMappingProvider.self)) but the \(Internals.typeName(NSEntityDescription.self))'s \"versionHash\" of the source and destination entities do not match." ) Internals.assert( allMappedSourceKeys[sourceEntity] == nil, "Duplicate \(Internals.typeName(CustomMapping.self))s found for source entity name \"\(sourceEntity)\" in \(Internals.typeName(CustomSchemaMappingProvider.self))." ) Internals.assert( allMappedDestinationKeys[destinationEntity] == nil, "Duplicate \(Internals.typeName(CustomMapping.self))s found for destination entity name \"\(destinationEntity)\" in \(Internals.typeName(CustomSchemaMappingProvider.self))." ) copyMappings.insert(mapping) allMappedSourceKeys[sourceEntity] = destinationEntity allMappedDestinationKeys[destinationEntity] = sourceEntity } } for renamingIdentifier in transformedRenamingIdentifiers { let sourceEntity = sourceRenamingIdentifiers[renamingIdentifier]!.entity let destinationEntity = destinationRenamingIdentifiers[renamingIdentifier]!.entity let sourceEntityName = sourceEntity.name! let destinationEntityName = destinationEntity.name! switch (allMappedSourceKeys[sourceEntityName], allMappedDestinationKeys[destinationEntityName]) { case (nil, nil): if sourceEntity.versionHash == destinationEntity.versionHash { copyMappings.insert( .copyEntity( sourceEntity: sourceEntityName, destinationEntity: destinationEntityName ) ) } else { transformMappings.insert( .transformEntity( sourceEntity: sourceEntityName, destinationEntity: destinationEntityName, transformer: CustomMapping.inferredTransformation ) ) } allMappedSourceKeys[sourceEntityName] = destinationEntityName allMappedDestinationKeys[destinationEntityName] = sourceEntityName case (""?, nil): insertMappings.insert(.insertEntity(destinationEntity: destinationEntityName)) allMappedDestinationKeys[destinationEntityName] = "" case (nil, ""?): deleteMappings.insert(.deleteEntity(sourceEntity: sourceEntityName)) allMappedSourceKeys[sourceEntityName] = "" default: continue } } for renamingIdentifier in removedRenamingIdentifiers { let sourceEntity = sourceRenamingIdentifiers[renamingIdentifier]!.entity let sourceEntityName = sourceEntity.name! switch allMappedSourceKeys[sourceEntityName] { case nil: deleteMappings.insert(.deleteEntity(sourceEntity: sourceEntityName)) allMappedSourceKeys[sourceEntityName] = "" default: continue } } for renamingIdentifier in addedRenamingIdentifiers { let destinationEntity = destinationRenamingIdentifiers[renamingIdentifier]!.entity let destinationEntityName = destinationEntity.name! switch allMappedDestinationKeys[destinationEntityName] { case nil: insertMappings.insert(.insertEntity(destinationEntity: destinationEntityName)) allMappedDestinationKeys[destinationEntityName] = "" default: continue } } return (deleteMappings, insertMappings, copyMappings, transformMappings) } }
mit
1f25f4ac20e59494afd593920ca39b19
49.025132
427
0.628282
6.111668
false
false
false
false
jokechat/swift3-novel
swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationLineScalePulseOut.swift
8
1748
// // NVActivityIndicatorAnimationLineScalePulseOut.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/24/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationLineScalePulseOut: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let lineSize = size.width / 9 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let duration: CFTimeInterval = 1 let beginTime = CACurrentMediaTime() let beginTimes = [0.4, 0.2, 0, 0.2, 0.4] let timingFunction = CAMediaTimingFunction(controlPoints: 0.85, 0.25, 0.37, 0.85) // Animation let animation = CAKeyframeAnimation(keyPath: "transform.scale.y") animation.keyTimes = [0, 0.5, 1] animation.timingFunctions = [timingFunction, timingFunction] animation.values = [1, 0.4, 1] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw lines for i in 0 ..< 5 { let line = NVActivityIndicatorShape.line.layerWith(size: CGSize(width: lineSize, height: size.height), color: color) let frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: lineSize, height: size.height) animation.beginTime = beginTime + beginTimes[i] line.frame = frame line.add(animation, forKey: "animation") layer.addSublayer(line) } } }
apache-2.0
427af37a3c95984c218acdb2294cf409
37
128
0.59611
4.648936
false
false
false
false
hoanganh6491/SwiftGen
SwiftGen.playground/Sources/SwiftGenStoryboardEnumBuilder.swift
1
6439
import Foundation //@import SwiftIdentifier //@import SwiftGenIndentation public final class SwiftGenStoryboardEnumBuilder { private typealias Scene = (storyboardID: String, customClass: String?) private var storyboards = [String : [Scene]]() public init() {} public func addStoryboardAtPath(path: String) { let parser = NSXMLParser(contentsOfURL: NSURL.fileURLWithPath(path)) class ParserDelegate : NSObject, NSXMLParserDelegate { var scenes = [Scene]() var inScene = false var readyForFirstObject = false @objc func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { switch elementName { case "scene": inScene = true case "objects" where inScene: readyForFirstObject = true case _ where readyForFirstObject: if let storyboardID = attributeDict["storyboardIdentifier"] { let customClass = attributeDict["customClass"] scenes.append(Scene(storyboardID, customClass)) } readyForFirstObject = false default: break } } @objc func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { switch elementName { case "scene": inScene = false case "objects" where inScene: readyForFirstObject = false default: break; } } } let delegate = ParserDelegate() parser?.delegate = delegate parser?.parse() let storyboardName = path.lastPathComponent.stringByDeletingPathExtension storyboards[storyboardName] = delegate.scenes } public func parseDirectory(path: String) { if let dirEnum = NSFileManager.defaultManager().enumeratorAtPath(path) { while let subPath = dirEnum.nextObject() as? String { if subPath.pathExtension == "storyboard" { self.addStoryboardAtPath(path.stringByAppendingPathComponent(subPath)) } } } } public func build(enumName enumName: String? = "Name", indentation indent : SwiftGenIndentation = .Spaces(4)) -> String { var text = "// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen\n\n" let t = indent.string text += commonCode(indentationString: t) text += "extension UIStoryboard {\n" let s = enumName == nil ? "" : t if let enumName = enumName { text += "\(t)enum \(enumName.asSwiftIdentifier()) {\n" } for (name, scenes) in storyboards { let enumName = name.asSwiftIdentifier(forbiddenChars: "_") text += "\(s)\(t)enum \(enumName) : String, StoryboardScene {\n" text += "\(s)\(t)\(t)static let storyboardName = \"\(name)\"\n" for scene in scenes { let caseName = scene.storyboardID.asSwiftIdentifier(forbiddenChars: "_") let lcCaseName = lowercaseFirst(caseName) let vcClass = scene.customClass ?? "UIViewController" let cast = scene.customClass == nil ? "" : " as! \(vcClass)" text += "\n" text += "\(s)\(t)\(t)case \(caseName) = \"\(scene.storyboardID)\"\n" text += "\(s)\(t)\(t)static var \(lcCaseName)ViewController : \(vcClass) {\n" text += "\(s)\(t)\(t)\(t)return \(enumName).\(caseName).viewController()\(cast)\n" text += "\(s)\(t)\(t)}\n" } text += "\(s)\(t)}\n" } if enumName != nil { text += "\(t)}\n" } text += "}\n\n" return text } // MARK: - Private Helpers private func commonCode(indentationString t : String) -> String { var text = "" text += "import Foundation\n" text += "import UIKit\n" text += "\n" text += "protocol StoryboardScene : RawRepresentable {\n" text += "\(t)static var storyboardName : String { get }\n" text += "\(t)static func storyboard() -> UIStoryboard\n" text += "\(t)static func initialViewController() -> UIViewController\n" text += "\(t)func viewController() -> UIViewController\n" text += "\(t)static func viewController(identifier: Self) -> UIViewController\n" text += "}\n" text += "\n" text += "extension StoryboardScene where Self.RawValue == String {\n" text += "\(t)static func storyboard() -> UIStoryboard {\n" text += "\(t)\(t)return UIStoryboard(name: self.storyboardName, bundle: nil)\n" text += "\(t)}\n" text += "\n" text += "\(t)static func initialViewController() -> UIViewController {\n" text += "\(t)\(t)return storyboard().instantiateInitialViewController()!\n" text += "\(t)}\n" text += "\n" text += "\(t)func viewController() -> UIViewController {\n" text += "\(t)\(t)return Self.storyboard().instantiateViewControllerWithIdentifier(self.rawValue)\n" text += "\(t)}\n" text += "\(t)static func viewController(identifier: Self) -> UIViewController {\n" text += "\(t)\(t)return identifier.viewController()\n" text += "\(t)}\n" text += "}\n\n" return text } private func lowercaseFirst(string: String) -> String { let ns = string as NSString let cs = NSCharacterSet.uppercaseLetterCharacterSet() var count = 0 while cs.characterIsMember(ns.characterAtIndex(count)) { count++ } let lettersToLower = count > 1 ? count-1 : count return ns.substringToIndex(lettersToLower).lowercaseString + ns.substringFromIndex(lettersToLower) } }
mit
6cc882fe914e014298d6f1f27b7b2fbf
38.25
125
0.537051
5.1786
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/ObjectMapper/Sources/ImmutableMappable.swift
28
11804
// // ImmutableMappble.swift // ObjectMapper // // Created by Suyeol Jeon on 23/09/2016. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public protocol ImmutableMappable: BaseMappable { init(map: Map) throws } public extension ImmutableMappable { /// Implement this method to support object -> JSON transform. public func mapping(map: Map) {} /// Initializes object from a JSON String public init(JSONString: String, context: MapContext? = nil) throws { self = try Mapper(context: context).map(JSONString: JSONString) } /// Initializes object from a JSON Dictionary public init(JSON: [String: Any], context: MapContext? = nil) throws { self = try Mapper(context: context).map(JSON: JSON) } /// Initializes object from a JSONObject public init(JSONObject: Any, context: MapContext? = nil) throws { self = try Mapper(context: context).map(JSONObject: JSONObject) } } public extension Map { fileprivate func currentValue(for key: String, nested: Bool? = nil, delimiter: String = ".") -> Any? { let isNested = nested ?? key.contains(delimiter) return self[key, nested: isNested, delimiter: delimiter].currentValue } // MARK: Basic /// Returns a value or throws an error. public func value<T>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let value = currentValue as? T else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '\(T.self)'", file: file, function: function, line: line) } return value } /// Returns a transformed value or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> Transform.Object { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let value = transform.transformFromJSON(currentValue) else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } return value } /// Returns a RawRepresentable type or throws an error. public func value<T: RawRepresentable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line) } // MARK: BaseMappable /// Returns a `BaseMappable` object or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let JSONObject = currentValue else { throw MapError(key: key, currentValue: currentValue, reason: "Found unexpected nil value", file: file, function: function, line: line) } return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject) } // MARK: [BaseMappable] /// Returns a `[BaseMappable]` or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonArray = currentValue as? [Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) } return try jsonArray.enumerated().map { i, JSONObject -> T in return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject) } } /// Returns a `[BaseMappable]` using transform or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [Transform.Object] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonArray = currentValue as? [Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line) } return try jsonArray.enumerated().map { i, json -> Transform.Object in guard let object = transform.transformFromJSON(json) else { throw MapError(key: "\(key)[\(i)]", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } return object } } // MARK: [String: BaseMappable] /// Returns a `[String: BaseMappable]` or throws an error. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: T] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonDictionary = currentValue as? [String: Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) } var value: [String: T] = [:] for (key, json) in jsonDictionary { value[key] = try Mapper<T>(context: context).mapOrFail(JSONObject: json) } return value } /// Returns a `[String: BaseMappable]` using transform or throws an error. public func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: Transform.Object] { let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter) guard let jsonDictionary = currentValue as? [String: Any] else { throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line) } var value: [String: Transform.Object] = [:] for (key, json) in jsonDictionary { guard let object = transform.transformFromJSON(json) else { throw MapError(key: key, currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line) } value[key] = object } return value } } public extension Mapper where N: ImmutableMappable { public func map(JSON: [String: Any]) throws -> N { return try self.mapOrFail(JSON: JSON) } public func map(JSONString: String) throws -> N { return try mapOrFail(JSONString: JSONString) } public func map(JSONObject: Any) throws -> N { return try mapOrFail(JSONObject: JSONObject) } // MARK: Array mapping functions public func mapArray(JSONArray: [[String: Any]]) throws -> [N] { return try JSONArray.flatMap(mapOrFail) } public func mapArray(JSONString: String) throws -> [N] { guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") } return try mapArray(JSONObject: JSONObject) } public func mapArray(JSONObject: Any) throws -> [N] { guard let JSONArray = JSONObject as? [[String: Any]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[String: Any]]'") } return try mapArray(JSONArray: JSONArray) } // MARK: Dictionary mapping functions public func mapDictionary(JSONString: String) throws -> [String: N] { guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else { throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'") } return try mapDictionary(JSONObject: JSONObject) } public func mapDictionary(JSONObject: Any?) throws -> [String: N] { guard let JSON = JSONObject as? [String: [String: Any]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") } return try mapDictionary(JSON: JSON) } public func mapDictionary(JSON: [String: [String: Any]]) throws -> [String: N] { return try JSON.filterMap(mapOrFail) } // MARK: Dictinoary of arrays mapping functions public func mapDictionaryOfArrays(JSONObject: Any?) throws -> [String: [N]] { guard let JSON = JSONObject as? [String: [[String: Any]]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''") } return try mapDictionaryOfArrays(JSON: JSON) } public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) throws -> [String: [N]] { return try JSON.filterMap { array -> [N] in try mapArray(JSONArray: array) } } // MARK: 2 dimentional array mapping functions public func mapArrayOfArrays(JSONObject: Any?) throws -> [[N]] { guard let JSONArray = JSONObject as? [[[String: Any]]] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[[String: Any]]]''") } return try JSONArray.map(mapArray) } } internal extension Mapper where N: BaseMappable { internal func mapOrFail(JSON: [String: Any]) throws -> N { let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues) // Check if object is ImmutableMappable, if so use ImmutableMappable protocol for mapping if let klass = N.self as? ImmutableMappable.Type, var object = try klass.init(map: map) as? N { object.mapping(map: map) return object } // If not, map the object the standard way guard let value = self.map(JSON: JSON) else { throw MapError(key: nil, currentValue: JSON, reason: "Cannot map to '\(N.self)'") } return value } internal func mapOrFail(JSONString: String) throws -> N { guard let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) else { throw MapError(key: nil, currentValue: JSONString, reason: "Cannot parse into '[String: Any]'") } return try mapOrFail(JSON: JSON) } internal func mapOrFail(JSONObject: Any) throws -> N { guard let JSON = JSONObject as? [String: Any] else { throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: Any]'") } return try mapOrFail(JSON: JSON) } }
apache-2.0
2bf20ba6347882c8d7d76db02c0918f7
41.923636
256
0.709251
3.81143
false
false
false
false
Countly/countly-sdk-samples
ios-swift/CountlyTestApp-iOS-swift/ViewController.swift
1
24363
// ViewController.swift // // This code is provided under the MIT License. // // Please visit www.count.ly for more information. import UIKit extension ViewController: UITableViewDataSource, UITableViewDelegate { } enum TestSection : Int { case CustomEvents = 0 case CrashReporting case UserDetails case APM case ViewTracking case PushNotifications case MultiThreading case Others } class ViewController: UIViewController { let sections : [String] = [ "Custom Events", "Crash Reporting", "User Details", "APM", "View Tracking", "Push Notifications", "Multi Threading", "Others" ] let tests : [[String]] = [ ["Record Event", "Record Event with Count", "Record Event with Sum", "Record Event with Duration", "Record Event with Segmentation", "Record Event with Segmentation & Count", "Record Event with Segmentation, Count & Sum", "Record Event with Segmentation, Count, Sum & Dur.", "Start Event", "End Event", "End Event with Segmentation, Count & Sum"], ["Unrecognized Selector", "Out of Bounds", "Unwrapping nil Optional", "Invalid Geometry", "Assert Fail", "Terminate", "Terminate 2", "Custom Crash Log", "Record Handled Exception", "Record Handled Exception With Stack Trace"], ["Record User Details", "Custom Modifiers 1", "Custom Modifiers 2", "User Logged in", "User Logged out"], ["sendSynchronous", "sendAsynchronous", "connectionWithRequest", "initWithRequest", "initWithRequest:startImmediately NO", "initWithRequest:startImmediately YES", "dataTaskWithRequest", "dataTaskWithRequest:completionHandler", "dataTaskWithURL", "dataTaskWithURL:completionHandler", "downloadTaskWithRequest", "downloadTaskWithRequest:completionHandler", "downloadTaskWithURL", "downloadTaskWithURL:completionHandler", "Add Exception URL", "Remove Exception URL"], ["Turn off AutoViewTracking", "Turn on AutoViewTracking", "Present Modal View Controller", "Push / Pop with Navigation Controller ", "Add Exception with Class Name", "Remove Exception with Class Name", "Add Exception with Title", "Remove Exception with Title", "Add Exception with Custom titleView", "Remove Exception with Custom titleView", "Report View Manually"], ["Ask for Notification Permission", "Ask for Notification Permission with Completion Handler", "Record Geo-Location for Push", "Record Push Notification Action"], ["Thread 1", "Thread 2", "Thread 3", "Thread 4", "Thread 5", "Thread 6", "Thread 7", "Thread 8"], ["Set Custom Header Field Value", "Ask for Star-Rating", "Set New Device ID", "Set New Device ID with Server Merge"] ] var queue : [DispatchQueue?] = Array(repeating: nil, count: 15) @IBOutlet weak var tableView: UITableView! let startSection = TestSection.CustomEvents.rawValue //start section of testing app can be set here. override func viewDidLoad() { super.viewDidLoad() tableView.scrollToRow(at: IndexPath(row: 0, section:startSection), at:UITableView.ScrollPosition.top, animated:false) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func numberOfSections(in tableView: UITableView) -> Int { return sections.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section] } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView headerView.backgroundView?.backgroundColor = UIColor.gray headerView.textLabel?.textColor = UIColor.white } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tests[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: "CountlyTestCell") cell.textLabel?.text = tests[indexPath.section][indexPath.row] cell.textLabel?.font = UIFont.systemFont(ofSize:12) return cell } @available(iOS, deprecated:10.0) public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("Test: \(sections[indexPath.section]) - \(tests[indexPath.section][indexPath.row])"); switch indexPath.section { case TestSection.CustomEvents.rawValue: //MARK: Custom Events switch (indexPath.row) { case 0: Countly.sharedInstance().recordEvent("button-click") break case 1: Countly.sharedInstance().recordEvent("button-click", count:5) break case 2: Countly.sharedInstance().recordEvent("button-click", sum:1.99) break case 3: Countly.sharedInstance().recordEvent("button-click", duration:3.14) break case 4: Countly.sharedInstance().recordEvent("button-click", segmentation:["k" : "v"]) break case 5: Countly.sharedInstance().recordEvent("button-click", segmentation:["k" : "v"], count:5) break case 6: Countly.sharedInstance().recordEvent("button-click", segmentation:["k" : "v"], count:5, sum:1.99) break case 7: Countly.sharedInstance().recordEvent("button-click", segmentation:["k" : "v"], count:5, sum:1.99, duration:0.314) break case 8: Countly.sharedInstance().startEvent("timed-event") break case 9: Countly.sharedInstance().endEvent("timed-event") break case 10: Countly.sharedInstance().endEvent("timed-event", segmentation:["k" : "v"], count:1, sum:0) break default: break } break case TestSection.CrashReporting.rawValue: //MARK: Crash Reporting switch (indexPath.row) { case 0: crashTest0() break case 1: crashTest1() break case 2: crashTest2() break case 3: crashTest3() break case 4: crashTest4() break case 5: crashTest5() break case 6: crashTest6() break case 7: Countly.sharedInstance().recordCrashLog("This is a custom crash log.") break case 8: let myException : NSException = NSException.init(name:NSExceptionName(rawValue: "MyException"), reason:"MyReason", userInfo:["key":"value"]) Countly.sharedInstance().recordHandledException(myException) Countly.sharedInstance().recordHandledException(myException, withStackTrace: Thread.callStackSymbols) break case 9: let myException : NSException = NSException.init(name:NSExceptionName(rawValue: "MyException"), reason:"MyReason", userInfo:["key":"value"]) Countly.sharedInstance().recordHandledException(myException, withStackTrace: Thread.callStackSymbols) break default: break } break case TestSection.UserDetails.rawValue: //MARK: User Details switch (indexPath.row) { case 0: let documentsDirectory : URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! let localImagePath : String = documentsDirectory.appendingPathComponent("SamplePicture.jpg").absoluteString // SamplePicture.png or SamplePicture.gif can be used too. Countly.user().name = "John Doe" as CountlyUserDetailsNullableString Countly.user().email = "[email protected]" as CountlyUserDetailsNullableString Countly.user().birthYear = 1970 as CountlyUserDetailsNullableNumber Countly.user().organization = "United Nations" as CountlyUserDetailsNullableString Countly.user().gender = "M" as CountlyUserDetailsNullableString Countly.user().phone = "+0123456789" as CountlyUserDetailsNullableString //Countly.user().pictureURL = "http://s12.postimg.org/qji0724gd/988a10da33b57631caa7ee8e2b5a9036.jpg" as CountlyUserDetailsNullableString Countly.user().pictureLocalPath = localImagePath as CountlyUserDetailsNullableString Countly.user().custom = ["testkey1":"testvalue1","testkey2":"testvalue2"] as CountlyUserDetailsNullableDictionary Countly.user().save() break case 1: Countly.user().set("key101", value:"value101") Countly.user().increment(by:"key102", value:5) Countly.user().push("key103", value:"singlevalue") Countly.user().push("key104", values:["first","second","third"]) Countly.user().push("key105", values:["a","b","c","d"]) Countly.user().save() break case 2: Countly.user().multiply("key102", value:2) Countly.user().unSet("key103") Countly.user().pull("key104", value:"second") Countly.user().pull("key105", values:["a","d"]) Countly.user().save() break case 3: Countly.sharedInstance().userLogged(in:"OwnUserID") break case 4: Countly.sharedInstance().userLoggedOut() break default: break } break case TestSection.APM.rawValue: //MARK: APM let urlString : String = "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json" //let urlString : String = "http://www.bbc.co.uk/radio1/playlist.json" //let urlString : String = "https://maps.googleapis.com/maps/api/geocode/json?address=Ebisu%20Garden%20Place,Tokyo" //let urlString : String = "https://itunes.apple.com/search?term=Michael%20Jackson&entity=musicVideo" let url : URL = URL.init(string: urlString)! let request : URLRequest = URLRequest.init(url: url) var response: URLResponse? switch (indexPath.row) { case 0: do { try NSURLConnection.sendSynchronousRequest(request, returning: &response) } catch { print(error) } break case 1: NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler: { (response, data, error) in print("sendAsynchronousRequest:queue:completionHandler: finished!") }) break case 2: print("connectionWithRequest is not available on Swift") break case 3: let testConnection : NSURLConnection? = NSURLConnection.init(request:request, delegate:self) print(testConnection!) break case 4: let testConnection : NSURLConnection? = NSURLConnection.init(request:request, delegate:self, startImmediately: false) testConnection?.start() break case 5: let testConnection : NSURLConnection? = NSURLConnection.init(request:request, delegate:self, startImmediately: true) print(testConnection!) break case 6: let testTask : URLSessionDataTask = URLSession.shared.dataTask(with: request) testTask.resume() //DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) { testTask.resume() } break case 7: let testTask : URLSessionDataTask = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in print("dataTaskWithRequest:completionHandler: finished!") }) testTask.resume() break case 8: let testTask : URLSessionDataTask = URLSession.shared.dataTask(with: url) testTask.resume() break case 9: let testTask : URLSessionDataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in print("dataTaskWithRequest finished!"); }) testTask.resume() break case 10: let testTask : URLSessionDownloadTask = URLSession.shared.downloadTask(with: request) testTask.resume() break case 11: let testTask : URLSessionDownloadTask = URLSession.shared.downloadTask(with: request, completionHandler: { (data, response, error) in print("downloadTaskWithRequest:completionHandler: finished!") }) testTask.resume() break case 12: let testTask : URLSessionDownloadTask = URLSession.shared.downloadTask(with: url) testTask.resume() break case 13: let testTask : URLSessionDownloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { (data, response, error) in print("downloadTaskWithRequest finished!"); }) testTask.resume() break case 14: Countly.sharedInstance().addException(forAPM: "http://finance.yahoo.com") break case 15: Countly.sharedInstance().removeException(forAPM: "http://finance.yahoo.com") break default:break } break case TestSection.ViewTracking.rawValue: //MARK: View Tracking switch (indexPath.row) { case 0: Countly.sharedInstance().isAutoViewTrackingEnabled = false; break case 1: Countly.sharedInstance().isAutoViewTrackingEnabled = true; break case 2: let storyboard = UIStoryboard(name: "Main", bundle: nil) let testVC = storyboard.instantiateViewController(withIdentifier: "TestViewControllerModal") as! TestViewControllerModal testVC.title = "MyViewControllerTitle" self.present(testVC, animated: true, completion: nil) break case 3: let storyboard = UIStoryboard(name: "Main", bundle: nil) let testVC = storyboard.instantiateViewController(withIdentifier: "TestViewControllerPushPop") as! TestViewControllerPushPop let titleView = UILabel(frame: CGRect(x:0,y:0,width:320,height:30)) titleView.text = "MyViewControllerCustomTitleView" titleView.textAlignment = NSTextAlignment.center titleView.textColor = UIColor.red titleView.font = UIFont.systemFont(ofSize:12) testVC.navigationItem.titleView = titleView let nc = UINavigationController(rootViewController: testVC) nc.title = "TestViewControllerPushPop" self.present(nc, animated: true, completion: nil) break case 4: Countly.sharedInstance().addException(forAutoViewTracking:String.init(utf8String: object_getClassName(TestViewControllerModal.self))!) break case 5: Countly.sharedInstance().removeException(forAutoViewTracking:String.init(utf8String: object_getClassName(TestViewControllerModal.self))!) break case 6: Countly.sharedInstance().addException(forAutoViewTracking:"MyViewControllerTitle") break case 7: Countly.sharedInstance().removeException(forAutoViewTracking:"MyViewControllerTitle") break case 8: Countly.sharedInstance().addException(forAutoViewTracking:"MyViewControllerCustomTitleView") break case 9: Countly.sharedInstance().removeException(forAutoViewTracking:"MyViewControllerCustomTitleView") break case 10: Countly.sharedInstance().reportView("ManualViewReportExample") break default: break } break case TestSection.PushNotifications.rawValue: //MARK: Push Notifications switch (indexPath.row) { case 0: Countly.sharedInstance().askForNotificationPermission() break case 1: let authorizationOptions : UNAuthorizationOptions = [.badge, .alert, .sound] Countly.sharedInstance().askForNotificationPermission(options: authorizationOptions, completionHandler: { (granted : Bool, error : Error?) in print("granted \(granted)") print("error \(error.debugDescription)") }) break case 2: Countly.sharedInstance().recordLocation(CLLocationCoordinate2D(latitude:33.6789, longitude:43.1234)) Countly.sharedInstance().recordIP("255.255.255.255") Countly.sharedInstance().recordCity("Tokyo", andISOCountryCode: "JP") Countly.sharedInstance().isGeoLocationEnabled = true break case 3: let userInfo : Dictionary<String, AnyObject> = Dictionary() // notification dictionary let buttonIndex : Int = 1 // clicked button index // 1 for first action button // 2 for second action button // 0 for default action Countly.sharedInstance().recordAction(forNotification:userInfo, clickedButtonIndex:buttonIndex) break default: break } break case TestSection.MultiThreading.rawValue: //MARK: Multi Threading let t : Int = indexPath.row let tag : String = String(t) let commonQueueName : String = "ly.count.multithreading" let queueName : String = commonQueueName + tag if(queue[t] == nil) { queue[t] = DispatchQueue(label: queueName) } for i in 0..<15 { let eventName : String = "MultiThreadingEvent" + tag let segmentation : Dictionary = ["k" : "v" + String(i)] queue[t]!.async { Countly.sharedInstance().recordEvent(eventName, segmentation:segmentation) } } break case TestSection.Others.rawValue: //MARK: Others switch (indexPath.row) { case 0: Countly.sharedInstance().setCustomHeaderFieldValue("thisismyvalue") break case 1: Countly.sharedInstance().ask(forStarRating: { (rating : Int) in print("rating \(rating)") }) break case 2: Countly.sharedInstance().setNewDeviceID("[email protected]", onServer:false) break case 3: Countly.sharedInstance().setNewDeviceID(CLYIDFV, onServer:true) break default: break } break default:break } tableView.deselectRow(at:indexPath, animated:true) } //MARK: Crash Tests func crashTest0() { let s : Selector = Selector("thisIsTheUnrecognized"+"SelectorCausingTheCrash"); Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: s, userInfo: nil, repeats: true) } func crashTest1() { let a : Array = ["one","two","three"] let s : String = a[5] print(s) } func crashTest2() { let crashingOptional: Int? = nil print("\(crashingOptional!)") } func crashTest3() { let aRect : CGRect = CGRect(x:0.0/0.0, y:0.0, width:100.0, height:100.0) let crashView : UIView = UIView.init(frame: aRect); crashView.frame = aRect; } func crashTest4() { assert(0 == 1, "This is the test assert that failed!") } func crashTest5() { kill(getpid(), SIGABRT) } func crashTest6() { kill(getpid(), SIGTERM) } }
mit
af4a687257829ac266cf52aa0fc830e1
38.808824
161
0.508558
5.84946
false
true
false
false
KeithPiTsui/Pavers
Pavers/Sources/CryptoSwift/BlockMode/CBC.swift
2
1870
// // CBC.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // Cipher-block chaining (CBC) // struct CBCModeWorker: BlockModeWorker { let cipherOperation: CipherOperationOnBlock private let iv: ArraySlice<UInt8> private var prev: ArraySlice<UInt8>? init(iv: ArraySlice<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) { self.iv = iv self.cipherOperation = cipherOperation } mutating func encrypt(_ plaintext: ArraySlice<UInt8>) -> Array<UInt8> { guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else { return Array(plaintext) } prev = ciphertext.slice return ciphertext } mutating func decrypt(_ ciphertext: ArraySlice<UInt8>) -> Array<UInt8> { guard let plaintext = cipherOperation(ciphertext) else { return Array(ciphertext) } let result: Array<UInt8> = xor(prev ?? iv, plaintext) prev = ciphertext return result } }
mit
12510f58b7eb882c5f925040129e28a3
39.630435
217
0.704655
4.592138
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Controllers/Chat/MessagesViewControllerSearching.swift
1
747
// // MessagesViewControllerSearching.swift // Rocket.Chat // // Created by Matheus Cardoso on 11/12/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // extension MessagesViewController { @objc func showSearchMessages() { guard let controller = storyboard?.instantiateViewController(withIdentifier: "MessagesList"), let messageList = controller as? MessagesListViewController else { return } messageList.data.subscription = subscription messageList.data.isSearchingMessages = true let searchMessagesNav = BaseNavigationController(rootViewController: messageList) present(searchMessagesNav, animated: true, completion: nil) } }
mit
e60e1561bb9f2b5757159f8107e09b53
26.62963
99
0.689008
5.29078
false
false
false
false
emilstahl/swift
validation-test/compiler_crashers_fixed/0032-swift-irgen-irgenfunction-emittypemetadataref.swift
14
420
// 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) // rdar://17240737 protocol a { } protocol b : a { } protocol c : a { } protocol d { typealias f = a } struct e : d { typealias f = b } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } i(e())
apache-2.0
1431ba0fb8f569cbf2b2c7f940d5bdf6
16.5
87
0.614286
2.763158
false
false
false
false
PhillipEnglish/TIY-Assignments
InDueTime/InDueTime/ToDoTableViewController.swift
1
5941
// // ToDoTableViewController.swift // InDueTime // // Created by Phillip English on 10/20/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreData class ToDoTableViewController: UITableViewController, UITextFieldDelegate { let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext var toDos = Array<ToDo>() override func viewDidLoad() { super.viewDidLoad() title = "To Do List" let fetchRequest = NSFetchRequest(entityName: "ToDo") do { let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [ToDo] toDos = fetchResults! } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return toDos.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ToDoCell", forIndexPath: indexPath) as! ToDoCell // Configure the cell... let aToDo = toDos[indexPath.row] if aToDo.toDoDescription == nil { cell.descriptionTextField.becomeFirstResponder() } else { cell.descriptionTextField.text = aToDo.toDoDescription } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let aTodo = toDos[indexPath.row] if aTodo.isComplete == true { toDos.removeAtIndex(indexPath.row) managedObjectContext.deleteObject(aTodo) saveContext() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ //MARK: - UITextfield Delegate func textFieldShouldReturn(textField: UITextField) -> Bool { var rc = false if textField.text != "" { rc = true let contentView = textField.superview let cell = contentView?.superview as! ToDoCell let indexPath = tableView.indexPathForCell(cell) let aTodo = toDos[indexPath!.row] aTodo.toDoDescription = textField.text textField.resignFirstResponder() saveContext() } return rc } //MARK: - Action Handlers @IBAction func AddTablePushed(sender: UIBarButtonItem) { let newTodo = NSEntityDescription.insertNewObjectForEntityForName("ToDo", inManagedObjectContext: managedObjectContext) as! ToDo toDos.append(newTodo) tableView.reloadData() } @IBAction func isCompleteChanged(sender: UISwitch) { let contentView = sender.superview let cell = contentView?.superview as! ToDoCell let indexPath = tableView.indexPathForCell(cell) let aToDo = toDos[indexPath!.row] if Bool(sender.enabled) == false { aToDo.isComplete == false } else { aToDo.isComplete == true } saveContext() tableView.reloadData() } //MARK: - Private func saveContext() { do { try managedObjectContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } }
cc0-1.0
0a84f3d925c1651da405064545853341
28.7
155
0.620034
5.662536
false
false
false
false
changjiashuai/AudioKit
Tests/Tests/AKADSREnvelope.swift
14
947
// // main.swift // AudioKit // // Created by Aurelius Prochazka and Nick Arner on 12/29/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: NSTimeInterval = 10.0 class Instrument : AKInstrument { override init() { super.init() let adsr = AKADSREnvelope() enableParameterLog("ADSR value = ", parameter: adsr, timeInterval:0.1) let oscillator = AKOscillator() oscillator.amplitude = adsr setAudioOutput(oscillator) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() AKOrchestra.addInstrument(instrument) let note1 = AKNote() let note2 = AKNote() let phrase = AKPhrase() phrase.addNote(note1, atTime:0.5) phrase.stopNote(note1, atTime: 2.5) note2.duration.floatValue = 5.0 phrase.addNote(note2, atTime:3.5) instrument.playPhrase(phrase) NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
mit
7263e495c81369517f81588195f8c05b
20.522727
78
0.715945
3.913223
false
true
false
false
1aurabrown/eidolon
Kiosk/Bid Fulfillment/SwipeCreditCardViewController.swift
1
3187
import UIKit public class SwipeCreditCardViewController: UIViewController, RegistrationSubController { @IBOutlet var cardStatusLabel: ARSerifLabel! let finishedSignal = RACSubject() @IBOutlet weak var spinner: Spinner! @IBOutlet weak var processingLabel: UILabel! @IBOutlet weak var illustrationImageView: UIImageView! @IBOutlet weak var titleLabel: ARSerifLabel! public class func instantiateFromStoryboard() -> SwipeCreditCardViewController { return UIStoryboard.fulfillment().viewControllerWithID(.RegisterCreditCard) as SwipeCreditCardViewController } dynamic var cardName = "" dynamic var cardLastDigits = "" dynamic var cardToken = "" lazy var keys = EidolonKeys() public override func viewDidLoad() { super.viewDidLoad() self.setInProgress(false) let merchantToken = AppSetup.sharedState.useStaging ? self.keys.cardflightMerchantAccountStagingToken() : self.keys.cardflightMerchantAccountToken() let cardHandler = CardHandler(apiKey: self.keys.cardflightAPIClientKey(), accountToken:merchantToken) // This will cause memory leaks if signals are not completed. cardHandler.cardSwipedSignal.subscribeNext({ (message) -> Void in self.cardStatusLabel.text = "Card Status: \(message)" if message as String == "Got Card" { self.setInProgress(true) } }, error: { (error) -> Void in self.cardStatusLabel.text = "Card Status: Errored" self.setInProgress(false) self.titleLabel.text = "Please Swipe a Valid Credit Card" self.titleLabel.textColor = UIColor.artsyRed() }, completed: { () -> Void in self.cardStatusLabel.text = "Card Status: completed" if let card = cardHandler.card { self.cardName = card.name self.cardLastDigits = card.encryptedSwipedCardNumber if AppSetup.sharedState.useStaging { self.cardToken = "/v1/marketplaces/TEST-MP7Fs9XluC54HnVAvBKSI3jQ/cards/CC1AF3Ood4u5GdLz4krD8upG" } else { self.cardToken = card.cardToken } } cardHandler.end() self.finishedSignal.sendCompleted() }) cardHandler.startSearching() if let bidDetails = self.navigationController?.fulfillmentNav().bidDetails { RAC(bidDetails, "newUser.creditCardName") <~ RACObserve(self, "cardName") RAC(bidDetails, "newUser.creditCardDigit") <~ RACObserve(self, "cardLastDigits") RAC(bidDetails, "newUser.creditCardToken") <~ RACObserve(self, "cardToken") } } func setInProgress(show: Bool) { illustrationImageView.alpha = show ? 0.1 : 1 processingLabel.hidden = !show spinner.hidden = !show } } private extension SwipeCreditCardViewController { @IBAction func dev_creditCradOKTapped(sender: AnyObject) { self.cardName = "MRS DEV" self.cardLastDigits = "2323" self.cardToken = "3223423423423" self.finishedSignal.sendCompleted() } }
mit
5520ddf4f9faeba3b5d6b41f652fdff8
35.215909
156
0.652024
4.714497
false
false
false
false
ruslanskorb/CoreStore
Sources/GroupBy.swift
1
5185
// // GroupBy.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - GroupBy /** The `GroupBy` clause specifies that the result of a query be grouped accoording to the specified key path. */ public struct GroupBy<O: DynamicObject>: GroupByClause, QueryClause, Hashable { /** Initializes a `GroupBy` clause with an empty list of key path strings */ public init() { self.init([]) } /** Initializes a `GroupBy` clause with a list of key path strings - parameter keyPath: a key path string to group results with - parameter keyPaths: a series of key path strings to group results with */ public init(_ keyPath: KeyPathString, _ keyPaths: KeyPathString...) { self.init([keyPath] + keyPaths) } /** Initializes a `GroupBy` clause with a list of key path strings - parameter keyPaths: a list of key path strings to group results with */ public init(_ keyPaths: [KeyPathString]) { self.keyPaths = keyPaths } // MARK: GroupByClause public typealias ObjectType = O public let keyPaths: [KeyPathString] // MARK: QueryClause public func applyToFetchRequest<ResultType>(_ fetchRequest: NSFetchRequest<ResultType>) { if let keyPaths = fetchRequest.propertiesToGroupBy as? [String], keyPaths != self.keyPaths { Internals.log( .warning, message: "An existing \"propertiesToGroupBy\" for the \(Internals.typeName(NSFetchRequest<ResultType>.self)) was overwritten by \(Internals.typeName(self)) query clause." ) } fetchRequest.propertiesToGroupBy = self.keyPaths } // MARK: Equatable public static func == (lhs: GroupBy, rhs: GroupBy) -> Bool { return lhs.keyPaths == rhs.keyPaths } // MARK: Hashable public func hash(into hasher: inout Hasher) { hasher.combine(self.keyPaths) } // MARK: Deprecated @available(*, deprecated, renamed: "O") public typealias D = O } extension GroupBy where O: NSManagedObject { /** Initializes a `GroupBy` clause with a key path - parameter keyPath: a key path to group results with */ public init<T>(_ keyPath: KeyPath<O, T>) { self.init([keyPath._kvcKeyPathString!]) } } extension GroupBy where O: CoreStoreObject { /** Initializes a `GroupBy` clause with a key path - parameter keyPath: a key path to group results with */ public init<T>(_ keyPath: KeyPath<O, ValueContainer<O>.Required<T>>) { self.init([O.meta[keyPath: keyPath].keyPath]) } /** Initializes a `GroupBy` clause with a key path - parameter keyPath: a key path to group results with */ public init<T>(_ keyPath: KeyPath<O, ValueContainer<O>.Optional<T>>) { self.init([O.meta[keyPath: keyPath].keyPath]) } /** Initializes a `GroupBy` clause with a key path - parameter keyPath: a key path to group results with */ public init<T>(_ keyPath: KeyPath<O, TransformableContainer<O>.Required<T>>) { self.init([O.meta[keyPath: keyPath].keyPath]) } /** Initializes a `GroupBy` clause with a key path - parameter keyPath: a key path to group results with */ public init<T>(_ keyPath: KeyPath<O, TransformableContainer<O>.Optional<T>>) { self.init([O.meta[keyPath: keyPath].keyPath]) } } // MARK: - GroupByClause /** Abstracts the `GroupBy` clause for protocol utilities. */ public protocol GroupByClause { /** The `DynamicObject` type associated with the clause */ associatedtype ObjectType: DynamicObject /** The list of key path strings to group results with */ var keyPaths: [KeyPathString] { get } }
mit
f4d5bc634db2f74c819a5e8119c470c8
27.021622
186
0.634645
4.691403
false
false
false
false
tanweirush/TodayHistory
TodayHistory/ctrl/THDictionaryVC.swift
1
1982
// // THDictionaryVC.swift // TodayHistory // // Created by 谭伟 on 15/11/17. // Copyright © 2015年 谭伟. All rights reserved. // import UIKit class THDictionaryVC: UIViewController, UITextFieldDelegate { @IBOutlet weak var tf_text: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationController?.navigationBar.tintColor = Colors.red } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: true) } override func viewWillDisappear(animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: true) } @IBAction func OnSearch(sender: UIButton) { if self.tf_text.text!.isEmpty { self.tf_text.becomeFirstResponder() return } self.tf_text.resignFirstResponder() let vc = GetViewCtrlFromStoryboard.ViewCtrlWithStoryboard("Main", identifier: "THWebView") as! THWebView vc.url = "http://m.zdic.net/s/?q=".stringByAppendingString(self.tf_text.text!) vc.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, transitionType: "cube", subType: "fromRight") } @IBAction func OnHideKeyboard(sender: UITapGestureRecognizer) { self.tf_text.resignFirstResponder() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
80495e83d8f3505902d3edce835cb755
31.85
112
0.678843
4.79562
false
false
false
false
xwu/swift
test/stdlib/RawRepresentable-tricky-hashing.swift
1
3453
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest let suite = TestSuite("RawRepresentable") extension Hasher { static func hash<H: Hashable>(_ value: H) -> Int { var hasher = Hasher() hasher.combine(value) return hasher.finalize() } } struct TrickyRawRepresentable: RawRepresentable, Hashable { var value: [Unicode.Scalar] var rawValue: String { return String(String.UnicodeScalarView(value)) } init?(rawValue: String) { self.value = Array(rawValue.unicodeScalars) } } suite.test("Tricky hashing") { // RawRepresentable is not Equatable itself, but it does provide a generic // implementation of == based on rawValue. This gets picked up as the // implementation of Equatable.== when a concrete RawRepresentable type // conforms to Equatable without providing its own implementation. // // However, RawRepresentable used to not provide equivalent implementations // for hashing, allowing the compiler to synthesize hashing as usual, based on // the actual contents of the type rather than its rawValue. Thus, the // definitions of equality and hashing did not actually match in some cases, // leading to broken behavior. // // The difference between rawValue and the actual contents is subtle, and it // only causes problems in custom RawRepresentable implementations where the // rawValue isn't actually the storage representation, like the weird struct // above. // // rdar://problem/45308741 let s1 = TrickyRawRepresentable(rawValue: "café")! let s2 = TrickyRawRepresentable(rawValue: "cafe\u{301}")! expectEqual(s1, s2) expectEqual(s1.hashValue, s2.hashValue) expectEqual(Hasher.hash(s1), Hasher.hash(s2)) expectEqual(s1._rawHashValue(seed: 42), s2._rawHashValue(seed: 42)) } struct CustomRawRepresentable: RawRepresentable, Hashable { var rawValue: Int init?(rawValue: Int) { self.rawValue = rawValue } func hash(into hasher: inout Hasher) { hasher.combine(23) } } suite.test("_rawHashValue forwarding") { // In 5.0, RawRepresentable had a bogus default implementation for // _rawHashValue(seed:) that interfered with custom hashing for // RawRepresentable types. Adding a custom hash(into:) implementation should // always be enough to customize hashing. // // See https://bugs.swift.org/browse/SR-10734 if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { let r = CustomRawRepresentable(rawValue: 42)! expectEqual(Hasher.hash(r), Hasher.hash(23)) } } struct Bogus: Hashable { var hashValue: Int { 42 } static func ==(left: Self, right: Self) -> Bool { true } } struct CustomRawRepresentable2: RawRepresentable, Hashable { var rawValue: Bogus init?(rawValue: Bogus) { self.rawValue = rawValue } func hash(into hasher: inout Hasher) { hasher.combine(23) } } suite.test("hashValue forwarding") { // In versions up to and including 5.5, RawRepresentable had a bogus default // implementation for `hashValue` that forwarded directly to // `rawValue.hashValue`, instead of `self.hash(into:)`. Adding a custom // hash(into:) implementation should always be enough to customize hashing. // // See https://github.com/apple/swift/pull/39155 if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { let r = CustomRawRepresentable2(rawValue: Bogus())! expectEqual(r.hashValue, 23.hashValue) } } runAllTests()
apache-2.0
5469782f6b176041b3fcd2e2fcac7c46
28.758621
80
0.716396
4.094899
false
true
false
false
HarrisLee/Utils
MySampleCode-master/SwiftTips/SwiftTips/main.swift
1
617
// // main.swift // SwiftTips // // Created by 张星宇 on 16/2/2. // Copyright © 2016年 zxy. All rights reserved. // import Foundation var person = Person() person.changeName("kt") // 可以获取name属性的值 print(person.name) // 报错,不能在PrivateSet.swift文件外对name属性赋值 //person.name = "newName" /// 可以简化reuseIdentifier let reuseIdentifier = String(TableViewCell) print(reuseIdentifier) // 可以把多个相关联的变量声明在一个元组中 var (top, left, width, height) = (0.0, 0.0, 100.0, 50.0) //rect.width = width /** * 自定义断点 */ customDebug()
mit
133bd91213b4b26f084f178b059f42ea
15.387097
56
0.692913
2.687831
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobile/AdUnits/Native/NativeAd.swift
1
11469
/* Copyright 2019-2020 Prebid.org, 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 Foundation import UIKit @objcMembers public class NativeAd: NSObject, CacheExpiryDelegate { // MARK: - Public properties public var nativeAdMarkup: NativeAdMarkup? public weak var delegate: NativeAdEventDelegate? // MARK: - Internal properties private static let nativeAdIABShouldBeViewableForTrackingDuration = 1.0 private static let nativeAdCheckViewabilityForTrackingFrequency = 0.25 //NativeAd Expire private var expired = false //Impression Tracker private var targetViewabilityValue = 0 private var viewabilityTimer: Timer? private var viewabilityValue = 0 private var impressionHasBeenTracked = false private var viewForTracking: UIView? //Click Handling private var gestureRecognizerRecords = [NativeAdGestureRecognizerRecord]() private let eventManager = EventManager() // MARK: - Array getters @objc public var titles: [NativeTitle] { nativeAdMarkup?.assets?.compactMap { return $0.title } ?? [] } @objc public var dataObjects: [NativeData] { nativeAdMarkup?.assets?.compactMap { return $0.data } ?? [] } @objc public var images: [NativeImage] { nativeAdMarkup?.assets?.compactMap { return $0.img } ?? [] } @objc public var eventTrackers: [NativeEventTrackerResponse]? { return nativeAdMarkup?.eventtrackers } // MARK: - Filtered array getters @objc public func dataObjects(of dataType: NativeDataAssetType) -> [NativeData] { dataObjects.filter { $0.type == dataType.rawValue } } @objc public func images(of imageType: NativeImageAssetType) -> [NativeImage] { images.filter { $0.type == imageType.rawValue } } // MARK: - Property getters @objc public var title: String? { return titles.first?.text } @objc public var imageUrl: String? { return images(of: .main).first?.url } @objc public var iconUrl: String? { return images(of: .icon).first?.url } @objc public var sponsoredBy: String? { return dataObjects(of: .sponsored).first?.value } @objc public var text: String? { return dataObjects(of: .desc).first?.value } @objc public var callToAction: String? { return dataObjects(of: .ctaText).first?.value } public static func create(cacheId: String) -> NativeAd? { guard let bidString = CacheManager.shared.get(cacheId: cacheId), let bidDic = Utils.shared.getDictionaryFromString(bidString) else { Log.error("No bid response for provided cache id.") return nil } guard let rawBid = PBMORTBBid<PBMORTBBidExt>(jsonDictionary: bidDic, extParser: { extDic in return PBMORTBBidExt.init(jsonDictionary: extDic) }) else { return nil } let ad = NativeAd() let internalEventTracker = PrebidServerEventTracker() if let impURL = rawBid.ext.prebid?.events?.imp { let impEvent = ServerEvent(url: impURL, expectedEventType: .impression) internalEventTracker.addServerEvents([impEvent]) } if let winURL = rawBid.ext.prebid?.events?.win { let winEvent = ServerEvent(url: winURL, expectedEventType: .prebidWin) internalEventTracker.addServerEvents([winEvent]) } ad.eventManager.registerTracker(internalEventTracker) // Track win event immediately ad.eventManager.trackEvent(.prebidWin) guard let nativeAdMarkup = NativeAdMarkup(jsonString: rawBid.adm) else { Log.warn("Can't retrieve native ad markup from bid response.") return nil } ad.nativeAdMarkup = nativeAdMarkup CacheManager.shared.delegate = ad return ad } private override init() { super.init() } deinit { unregisterViewFromTracking() } private func canOpenString(_ string: String?) -> Bool { guard let string = string else { return false } let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) if let match = detector.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) { return match.range.length == string.utf16.count } else { return false } } //MARK: registerView function @discardableResult public func registerView(view: UIView?, clickableViews: [UIView]? ) -> Bool { guard let view = view else { Log.error("A valid view is required for tracking") return false } guard !expired else { Log.error("The native Ad is expired, cannot use it for tracking") return false } viewForTracking = view setupViewabilityTracker() attachGestureRecognizersToNativeView(nativeView: view, withClickableViews: clickableViews) return true } private func unregisterViewFromTracking() { detachAllGestureRecognizers() viewForTracking = nil invalidateTimer(viewabilityTimer) } //MARK: NativeAd Expire func cacheExpired() { if viewForTracking == nil { expired = true delegate?.adDidExpire?(ad: self) unregisterViewFromTracking() } } private func invalidateTimer(_ timer :Timer?) { if let timer = timer, timer.isValid { timer.invalidate() } } //MARK: Impression Tracking private func setupViewabilityTracker() { let requiredAmountOfSimultaneousViewableEvents = lround(NativeAd.nativeAdIABShouldBeViewableForTrackingDuration / NativeAd.nativeAdCheckViewabilityForTrackingFrequency) + 1 targetViewabilityValue = lround(pow(Double(2),Double(requiredAmountOfSimultaneousViewableEvents)) - 1) Log.debug("\n\trequiredAmountOfSimultaneousViewableEvents=\(requiredAmountOfSimultaneousViewableEvents) \n\ttargetViewabilityValue=\(targetViewabilityValue)") viewabilityTimer = Timer.scheduledTimer(withTimeInterval: NativeAd.nativeAdCheckViewabilityForTrackingFrequency, repeats: true) { [weak self] timer in guard let strongSelf = self else { timer.invalidate() Log.debug("FAILED TO ACQUIRE strongSelf viewabilityTimer") return } strongSelf.checkViewability() } } @objc private func checkViewability() { viewabilityValue = (viewabilityValue << 1 | (viewForTracking?.pb_isAtLeastHalfViewable() == true ? 1 : 0)) & targetViewabilityValue let isIABViewable = (viewabilityValue == targetViewabilityValue) Log.debug("\n\tviewabilityValue=\(viewabilityValue) \n\tself.targetViewabilityValue=\(targetViewabilityValue) \n\tisIABViewable=\(isIABViewable)") if isIABViewable { trackImpression() } } private func trackImpression() { if !impressionHasBeenTracked { Log.debug("Firing impression trackers") fireEventTrackers() viewabilityTimer?.invalidate() eventManager.trackEvent(PBMTrackingEvent.impression) impressionHasBeenTracked = true } } private func fireEventTrackers() { if let eventTrackers = eventTrackers, eventTrackers.count > 0 { let eventTrackersUrls = eventTrackers.compactMap { $0.url } TrackerManager.shared.fireTrackerURLArray(arrayWithURLs: eventTrackersUrls) { [weak self] isTrackerFired in guard let strongSelf = self else { Log.debug("FAILED TO ACQUIRE strongSelf for fireEventTrackers") return } if isTrackerFired { strongSelf.delegate?.adDidLogImpression?(ad: strongSelf) } } } } //MARK: Click handling private func attachGestureRecognizersToNativeView(nativeView: UIView, withClickableViews clickableViews: [UIView]?) { if let clickableViews = clickableViews, clickableViews.count > 0 { clickableViews.forEach { clickableView in attachGestureRecognizerToView(view: clickableView) } } else { attachGestureRecognizerToView(view: nativeView) } } private func attachGestureRecognizerToView(view: UIView) { view.isUserInteractionEnabled = true let record = NativeAdGestureRecognizerRecord.init() record.viewWithTracking = view if let button = view as? UIButton { button.addTarget(self, action: #selector(handleClick), for: .touchUpInside) } else { let clickRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(handleClick)) view.addGestureRecognizer(clickRecognizer) record.gestureRecognizer = clickRecognizer } gestureRecognizerRecords.append(record) } private func detachAllGestureRecognizers() { gestureRecognizerRecords.forEach { record in if let view = record.viewWithTracking { if let button = view as? UIButton { button.removeTarget(self, action: #selector(handleClick), for: .touchUpInside) } else if let gesture = record.gestureRecognizer as? UITapGestureRecognizer { view.removeGestureRecognizer(gesture) } } } gestureRecognizerRecords.removeAll() } @objc private func handleClick() { self.delegate?.adWasClicked?(ad: self) if let clickUrl = nativeAdMarkup?.link?.url, let clickUrlString = clickUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: clickUrlString) { if !openURLWithExternalBrowser(url: url) { Log.debug("Could not open click URL: \(clickUrl)") } } } private func openURLWithExternalBrowser(url : URL) -> Bool { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) return true } else { return false } } } private class NativeAdGestureRecognizerRecord : NSObject { weak var viewWithTracking: UIView? weak var gestureRecognizer: UIGestureRecognizer? override init() { super.init() } deinit { viewWithTracking = nil gestureRecognizer = nil } }
apache-2.0
4ac33ba9a4e8eeac58116f2672ede17e
34.398148
180
0.633098
4.962787
false
false
false
false
MrSuperJJ/JJMediatorDemo
JJMediatorDemo/AppDelegate.swift
1
2540
// // AppDelegate.swift // JJMediatorDemo // // Created by Mr.JJ on 2017/5/11. // Copyright © 2017年 Mr.JJ. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.backgroundColor = .white let mainViewController = MainTableViewController() let navigationController = UINavigationController(rootViewController: mainViewController) self.window?.rootViewController = navigationController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
01e19d99fd8e78db95c152d974cb4284
45.981481
285
0.74931
5.701124
false
false
false
false
RyanTech/Loggerithm
Demo/Demo/ViewController.swift
1
1905
// // ViewController.swift // Demo // // Created by Honghao Zhang on 2014-12-10. // Copyright (c) 2014 HonghaoZ. All rights reserved. // import UIKit class ViewController: UIViewController { var cleanLogger = Loggerithm() func setupLocalLogger() { cleanLogger.showDateTime = false cleanLogger.showLogLevel = false cleanLogger.showFileName = false cleanLogger.showLineNumber = false cleanLogger.showFunctionName = false } override func viewDidLoad() { super.viewDidLoad() // Logger is setup in AppDelegate.swift setupLocalLogger() // Usage example log.verbose("Verbose message...") log.debug("Debug message...") log.info("Info message...") log.warning("Warning message...") log.error("Error message...") log.emptyLine() log.showDateTime = false log.info("date time is turned off.") log.showLineNumber = false log.info("Line number is turned off.") log.showFileName = false log.info("File name is turned off.") log.showFunctionName = false log.info("Function name is turned off.") log.showLogLevel = false log.info("Log level is turned off.") log.emptyLine() log.info("Restoring to full format...") log.showDateTime = true log.showLogLevel = true log.showFileName = true log.showLineNumber = true log.showFunctionName = true log.verboseWithFormat("I can use format: %d + %d = %d", args: 1, 1, 2) // Customize Color cleanLogger.emptyLine() cleanLogger.info("Customizing color...") log.verboseColor = UIColor.grayColor() log.debugColor = UIColor.greenColor() log.infoColor = UIColor.yellowColor() log.warningColor = UIColor.orangeColor() log.errorColor = UIColor.redColor() log.verbose("Verbose message...") log.debug("Debug message...") log.info("Info message...") log.warning("Warning message...") log.error("Error message...") } }
mit
51297ae12c9c1905769ffdfe7953220f
23.423077
72
0.679265
3.764822
false
false
false
false
johndpope/objc2swift
src/test/resources/if_statement_sample.swift
1
1511
class IfStatementSample: NSObject, SomeProtocol { @IBOutlet var label: UILabel! func fuga() { if a == 0 { b = a * b - 1 / a } if a > 2 { b = 2 } if a <= 1 { b = 3 } if a && b { b = 1 } if x && y { a = b + c } if a { b = 1 if b { c = d } } if a == b { return 1 } if a == b { return 2 } if comps.containsObject("画像") { return YSSSearchTypeImage } else { return YSSSearchTypeDefault } if comps.containsObject("画像") { return YSSSearchTypeImage } else { return YSSSearchTypeDefault } if comps.containsObject("画像") { a = b + c return YSSSearchTypeImage } else { if comps.containsObject("動画") { a = b - c return YSSSearchTypeVideo } else { a = b * c return YSSSearchTypeDefault } } if comps.containsObject("画像2") { return YSSSearchTypeImage } else { if comps.containsObject("動画2") { return YSSSearchTypeVideo } else { return YSSSearchTypeDefault } } } }
mit
9346662e96637b13e6ef138e8635608a
17.822785
49
0.376597
4.796774
false
false
false
false
WalterCreazyBear/Swifter30
UIAnimateDemo/UIAnimateDemo/Utils.swift
1
1426
// // Utils.swift // UIAnimateDemo // // Created by Bear on 2017/6/29. // Copyright © 2017年 Bear. All rights reserved. // import Foundation import UIKit let screenRect = UIScreen.main.bounds let generalFrame = CGRect(x: 0, y: 0, width: screenRect.width / 2.0, height: screenRect.height / 4.0) let generalCenter = CGPoint(x: screenRect.midX, y: screenRect.midY - 50) func drawRectView(_ color: UIColor, frame: CGRect, center: CGPoint) -> UIView { let view = UIView(frame: frame) view.center = center view.backgroundColor = color return view } func drawCircleView() -> UIView { let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100,y: screenRect.midY - 50), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true) let shapeLayer = CAShapeLayer() shapeLayer.path = circlePath.cgPath shapeLayer.fillColor = UIColor.red.cgColor shapeLayer.strokeColor = UIColor.red.cgColor shapeLayer.lineWidth = 3.0 let view = UIView() view.layer.addSublayer(shapeLayer) return view } func makeAlert(_ title: String, message: String, actionTitle: String) -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: actionTitle, style: UIAlertActionStyle.default, handler: nil)) return alert }
mit
765030699455c07a72289b752d1d4cf6
28.645833
180
0.709065
4.054131
false
false
false
false
stephentyrone/swift
test/IRGen/prespecialized-metadata/enum-outmodule-1argument-1distinct_use-struct-inmodule.swift
2
943
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/enum-public-nonfrozen-1argument.swift -emit-library -o %t/libArgument.dylib -emit-module -module-name Argument -emit-module-path %t/Argument.swiftmodule // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lArgument | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK-NOT: @"$s8Argument03OneA0Oy4main03TheA0VGMf" = @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } import Argument struct TheArgument { let value: Int } func doit() { consume( Argument.OneArgument.first(TheArgument(value: 13)) ) } doit()
apache-2.0
6f9775425b606d8e22b135c9993523bb
32.678571
263
0.715801
3.091803
false
false
false
false
congncif/SiFUtilities
Show/UIViewController+Alert.swift
1
5312
// // UIViewController+Alert.swift // SiFUtilities // // Created by FOLY on 2/4/17. // Copyright © 2017 [iF] Solution. All rights reserved. // import Foundation import UIKit extension UIViewController { public func confirm(title: String? = nil, message: String?, style: UIAlertController.Style = .alert, dismissOthers: Bool = false, cancelTitle: String = "Cancel", cancelHandler: (() -> Void)? = nil, confirmedTitle: String = "OK", confirmedHandler: @escaping () -> Void) { if let alert = self as? UIAlertController, let presenting = presentingViewController, dismissOthers { alert.dismiss(animated: false) { presenting.confirm(title: title, message: message, style: style, dismissOthers: dismissOthers, cancelTitle: cancelTitle, cancelHandler: cancelHandler, confirmedTitle: confirmedTitle, confirmedHandler: confirmedHandler) } return } let completion = { [weak self] in let alert = UIAlertController(title: title, message: message, preferredStyle: style) alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: { _ in cancelHandler?() })) alert.addAction(UIAlertAction(title: confirmedTitle, style: .default, handler: { _ in confirmedHandler() })) self?.present(alert, animated: true, completion: nil) } if let presented = presentedViewController, let alert = presented as? UIAlertController { if dismissOthers { alert.dismiss(animated: false, completion: completion) } else { print("☞ Alert is presented on view controller \(self). Set up dismissOthers = true to hide current alert before present new alert") return } } else { completion() } } public func notify(title: String? = nil, message: String?, style: UIAlertController.Style = .alert, dismissOthers: Bool = false, buttonTitle: String = "OK", handler: (() -> Void)? = nil) { if let alert = self as? UIAlertController, let presenting = presentingViewController, dismissOthers { alert.dismiss(animated: false) { presenting.notify(title: title, message: message, style: style, dismissOthers: dismissOthers, buttonTitle: buttonTitle, handler: handler) } return } let completion = { [weak self] in let alert = UIAlertController(title: title, message: message, preferredStyle: style) alert.addAction(UIAlertAction(title: buttonTitle, style: .cancel, handler: { _ in handler?() })) self?.present(alert, animated: true, completion: nil) } if let presented = presentedViewController, let alert = presented as? UIAlertController { if dismissOthers { alert.dismiss(animated: false, completion: completion) } else { print("☞ Alert is presented on view controller \(self). Set up dismissOthers = true to hide current alert before present new alert") return } } else { completion() } } } extension UIAlertController { open class func confirm(title: String? = nil, message: String?, style: UIAlertController.Style = .alert, dismissOthers: Bool = false, cancelTitle: String = "Cancel", cancelHandler: (() -> Void)? = nil, confirmedTitle: String = "OK", confirmedHandler: @escaping () -> Void) { let viewController = UIApplication.topViewController() viewController?.confirm(title: title, message: message, style: style, dismissOthers: dismissOthers, cancelTitle: cancelTitle, cancelHandler: cancelHandler, confirmedTitle: confirmedTitle, confirmedHandler: confirmedHandler) } open class func notify(title: String? = nil, message: String?, style: UIAlertController.Style = .alert, dismissOthers: Bool = false, buttonTitle: String = "OK", handler: (() -> Void)? = nil) { let viewController = UIApplication.topViewController() viewController?.notify(title: title, message: message, style: style, dismissOthers: dismissOthers, buttonTitle: buttonTitle, handler: handler) } } extension UIViewController { public func showErrorAlert(_ error: Error) { if let err = error as? LocalizedError { self.notify(title: err.errorDescription, message: err.failureReason) } else { let message = error.localizedDescription self.notify(message: message) } } }
mit
a6b0767433a6e256033b905ad0a1c302
43.225
234
0.558884
5.510903
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornTime/UI/iOS/Table View Controllers/ExtendedSubtitleTableViewController.swift
1
1957
import UIKit import struct PopcornKit.Subtitle class ExtendedSubtitleTableViewController: UITableViewController { var subtitles = Dictionary<String, [Subtitle]>() var currentSubtitle:Subtitle? var delegate:OptionsViewControllerDelegate? private var previousCell:UITableViewCell? // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // Always 1 section, the subtitles section return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return currentSubtitle != nil ? Array(subtitles[currentSubtitle!.language]!).count : 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell:UITableViewCell cell = tableView.dequeueReusableCell(withIdentifier: "cell")! let subtitle = Array(subtitles[currentSubtitle?.language ?? Locale.current.localizedString(forLanguageCode: "en")!]!)[indexPath.row] cell.detailTextLabel?.text = subtitle.language cell.textLabel?.text = subtitle.name cell.accessoryType = currentSubtitle?.name == subtitle.name ? .checkmark : .none currentSubtitle?.name == subtitle.name ? previousCell = cell : () return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) delegate?.didSelectSubtitle(currentSubtitle) self.currentSubtitle = Array(subtitles[currentSubtitle!.language]!)[indexPath.row] previousCell?.accessoryType = .none cell?.accessoryType = .checkmark previousCell = cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Available Subtitles".localized } }
gpl-3.0
d607af5695d5dc539ce8583365501b15
38.14
140
0.689831
5.497191
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Access/Attribute.swift
1
12839
// // Attribute.swift // ZeeQL // // Created by Helge Hess on 18/02/2017. // Copyright © 2017-2019 ZeeZide GmbH. All rights reserved. // /** * Usually represents a column in a database table. * * ## Pattern Attributes * * Attributes can be pattern attributes. Pattern attributes have a name * which is matched against the database information schema. For example * the pattern attribute could be 'name*' which would match name1, name2 and * name3 columns. * * Model example: * * <attribute columnNameLike="name*" /> * * ## Write Formats * * 'Write formats' are very useful to lower- or uppercase a value which is * you want to search case-insensitive later on. Eg: * * writeformat="LOWER(TRIM(%P))" * * This should be done at write time because if you use LOWER in a WHERE * condition the database might not be able to use the index! * (well, at least in PostgreSQL you can put an index on the LOWER * transformation, so it _can_ use an index) */ public protocol Attribute : Property, SQLValue, ExpressionEvaluation, SmartDescription { var name : String { get } var columnName : String? { get } var externalType : String? { get } var allowsNull : Bool? { get } var isAutoIncrement : Bool? { get } var width : Int? { get } var precision : Int? { get } var valueType : AttributeValue.Type? { get } // formatting (used by SQLExpression) var readFormat : String? { get } var writeFormat : String? { get } var isPattern : Bool { get } } public extension Attribute { // default imp // Note: dupe those in classes to avoid surprises! var columnName : String? { return nil } var externalType : String? { return nil } var allowsNull : Bool? { return nil } var isAutoIncrement : Bool? { return nil } var width : Int? { return nil } var precision : Int? { return nil } var valueType : AttributeValue.Type? { return nil } // formatting (used by SQLExpression) var readFormat : String? { return nil } var writeFormat : String? { return nil } var isPattern : Bool { return false } // MARK: - Property var relationshipPath : String? { // for flattened properties return nil } // MARK: - SQLValue func valueFor(SQLExpression context: SQLExpression) -> String { return context.sqlStringFor(schemaObjectName: columnName ?? name) } // MARK: - ExpressionEvaluation func valueFor(object: Any?) -> Any? { return KeyValueCoding.value(forKeyPath: name, inObject: object) } // MARK: - Description func appendToDescription(_ ms: inout String) { if isPattern { ms += " pattern" } ms += " \(name)" if let cn = columnName { ms += "[\(cn)]" } // TODO: precision let ws : String if let w = width { ws = "(\(w))" } else { ws = "" } if let vt = valueType, let et = externalType { ms += " \(vt)[\(et)\(ws)]" } else if let vt = valueType { ms += " \(vt)\(ws)" } else if let et = externalType { ms += " [\(et)\(ws)]" } if let n = allowsNull, n { ms += "?" } if let n = isAutoIncrement, n { ms += " AUTOINC" } if let f = readFormat { ms += " read='\(f)'" } if let f = writeFormat { ms += " write='\(f)'" } } } public extension Attribute { // default imp func isEqual(to object: Any?) -> Bool { guard let other = object as? Attribute else { return false } return other.isEqual(to: self) } func isEqual(to other: Attribute) -> Bool { if other === self { return true } guard name == other.name else { return false } guard columnName == other.columnName else { return false } guard externalType == other.externalType else { return false } guard allowsNull == other.allowsNull else { return false } guard isAutoIncrement == other.isAutoIncrement else { return false } guard width == other.width else { return false } guard precision == other.precision else { return false } guard valueType == other.valueType else { return false } guard readFormat == other.readFormat else { return false } guard writeFormat == other.writeFormat else { return false } guard isPattern == other.isPattern else { return false } return true } static func ==(lhs: Attribute, rhs: Attribute) -> Bool { return lhs.isEqual(to: rhs) } } /// Commonly used within the framework, but should not be public API extension Attribute { var columnNameOrName : String { return columnName ?? name } } /** * An Attribute description which stores the info as regular variables. * * Suitable for use with models loaded from XML, or models fetched from a * database. */ open class ModelAttribute : Attribute, Equatable { public final var name : String public final var columnName : String? public final var externalType : String? open var allowsNull : Bool? public final var isAutoIncrement : Bool? public final var width : Int? public final var precision : Int? open var valueType : AttributeValue.Type? public final var defaultValue : Any? // MySQL (PG 8.2 has comments on column, but no column privileges?) public final var comment : String? public final var collation : String? public final var privileges : [ String ]? // formatting (used by SQLExpression) public final var readFormat : String? public final var writeFormat : String? // patterns public final var isColumnNamePattern = false public final var userData = [ String : Any ]() /// A persistent ID used to track renaming when doing model-to-model /// migrations. public final var elementID : String? public init(name : String, column : String? = nil, externalType : String? = nil, allowsNull : Bool? = nil, width : Int? = nil, valueType : AttributeValue.Type? = nil) { self.name = name self.columnName = column self.externalType = externalType self.allowsNull = allowsNull self.width = width self.valueType = valueType } public init(attribute attr: Attribute) { self.name = attr.name self.columnName = attr.columnName self.externalType = attr.externalType self.allowsNull = attr.allowsNull self.isAutoIncrement = attr.isAutoIncrement self.width = attr.width self.precision = attr.precision self.readFormat = attr.readFormat self.writeFormat = attr.writeFormat self.valueType = attr.valueType if let ma = attr as? ModelAttribute { self.defaultValue = ma.defaultValue self.comment = ma.comment self.collation = ma.collation self.privileges = ma.privileges self.isColumnNamePattern = ma.isColumnNamePattern self.userData = ma.userData self.elementID = ma.elementID } } // MARK: - Property public var relationshipPath : String? { // for flattened properties return nil } // MARK: - Pattern Models public var isPattern : Bool { if isColumnNamePattern { return true } if externalType == nil { return true } return false } public func doesColumnNameMatchPattern(_ columnName: String) -> Bool { if !isColumnNamePattern { return columnName == self.columnName } if self.columnName == "*" { return true } // match all // TODO: fix pattern handling, properly process '*' etc return self.columnName?.contains(columnName) ?? false } public func resolvePatternWith(attribute attr: ModelAttribute) -> Attribute { guard isPattern else { return self } /* derive info */ let rAttr = ModelAttribute(attribute: self) if let v = attr.externalType { rAttr.externalType = v } if let v = attr.isAutoIncrement { rAttr.isAutoIncrement = v } if let v = attr.allowsNull { rAttr.allowsNull = v } if let v = attr.width { rAttr.width = v } if let v = attr.readFormat { rAttr.readFormat = v } if let v = attr.writeFormat { rAttr.writeFormat = v } if let v = attr.defaultValue { rAttr.defaultValue = v } if let v = attr.comment { rAttr.comment = v } if let v = attr.collation { rAttr.collation = v } if let v = attr.privileges { rAttr.privileges = v } /* construct */ rAttr.isColumnNamePattern = false // TBD: do we need to fix the colName? return rAttr } public func addAttributesMatchingAttributes(to list: inout [ Attribute ], attributes: [ Attribute ], entity: Entity? = nil) -> Bool { if !isColumnNamePattern { /* check whether we are contained */ // TODO: is this correct, could be more than 1 attribute with the same // column? for attr in attributes { if columnName == attr.columnName { list.append(self) return true } } return false } /* OK, now we need to evaluate the pattern and clone ourselves */ for attr in attributes { guard let colname = attr.columnName else { continue } guard doesColumnNameMatchPattern(colname) else { continue } /* check whether we already have an attribute for that column */ if let entity = entity { guard entity[columnName: colname] == nil else { continue } /* eg: 'name'='description' in the model (Company) vs column='name' * in the schema */ guard entity[attribute: colname] == nil else { // TBD // TBD: better keep the other attr and rename it continue } } /* clone and add */ let attrCopy = ModelAttribute(attribute: self) attrCopy.name = attr.name attrCopy.columnName = attr.columnName attrCopy.isColumnNamePattern = false list.append(attrCopy) } return true } // MARK: - SQLValue public func valueFor(SQLExpression context: SQLExpression) -> String { return context.sqlStringFor(schemaObjectName: columnName ?? name) } // MARK: - ExpressionEvaluation public func valueFor(object: Any?) -> Any? { return KeyValueCoding.value(forKeyPath: name, inObject: object) } // MARK: - Equatable public static func ==(lhs: ModelAttribute, rhs: ModelAttribute) -> Bool { return lhs.isEqual(to: rhs) } // MARK: - Own Description public func appendToDescription(_ ms: inout String) { ms += " \(name)" if let cn = columnName { ms += "[" ms += cn if isColumnNamePattern { ms += "*" } ms += "]" } // TODO: precision let ws : String if let w = width { ws = "(\(w))" } else { ws = "" } if let vt = valueType, let et = externalType { ms += " \(vt)[\(et)\(ws)]" } else if let vt = valueType { ms += " \(vt)\(ws)" } else if let et = externalType { ms += " [\(et)\(ws)]" } if let n = allowsNull, n { ms += "?" } if let n = isAutoIncrement, n { ms += " AUTOINC" } if let f = readFormat { ms += " read='\(f)'" } if let f = writeFormat { ms += " write='\(f)'" } if let v = defaultValue { ms += " default=\(v)" } if let v = comment { ms += " comment='\(v)'" } if let v = collation { ms += " collation='\(v)'" } if let v = privileges { ms += " privileges='\(v)'" } if !userData.isEmpty { ms += " ud=[" for ( key, value ) in userData { ms += " " ms += key ms += ": " ms += String(describing: value) } ms += "]" } } } // MARK: - Query Builder public extension Attribute { func eq(_ attr: Attribute) -> KeyComparisonQualifier { let key = AttributeKey(self) let otherKey = AttributeKey(attr) return KeyComparisonQualifier(key, .EqualTo, otherKey) } func eq(_ value : Any?) -> KeyValueQualifier { let key = AttributeKey(self) return KeyValueQualifier(key, .EqualTo, value) } } public extension Attribute { func like(_ pattern : String) -> KeyValueQualifier { let key = AttributeKey(self) return KeyValueQualifier(key, .Like, pattern) } }
apache-2.0
4c57785b7a5d59ceaafe83646f7fbbcb
30.542998
79
0.585372
4.216092
false
false
false
false
netyouli/SexyJson
SexyJson/ViewController.swift
1
4929
// // ViewController.swift // SexyJson // // Created by WHC on 17/5/5. // Copyright © 2017年 WHC. All rights reserved. // // Github <https://github.com/netyouli/SexyJson> import UIKit class ViewController: UIViewController { @IBOutlet private weak var sexyLab: UILabel! override func viewDidLoad() { super.viewDidLoad() /// layout sexyLab.frame = UIScreen.main.bounds let json = """ { "queryHotelObj": { "dataList": [ { "name": "酒店", "isDefault": true, "hotelListFilterItem": {}, "dataId": 1, "tagList": [] }, { "name": "公寓", "isDefault": true, "hotelListFilterItem": { "hotelStyle": "80,81" }, "dataId": 8, "tagList": [ { "type": 0, "name": "测试1", "targetUrl": "aaa" } ] }, { "name": "时租", "isDefault": true, "hotelListFilterItem": {}, "dataId": 3, "tagList": [] }, { "name": "国际", "isDefault": true, "hotelListFilterItem": {}, "dataId": 9, "tagList": [] }, { "name": "精选", "isDefault": true, "hotelListFilterItem": { "hotelStyle": "8" }, "dataId": 7, "tagList": [] } ] }, "resultType": 0, "message": "" } """ let test = BaseClass.sexy_json(json) let obj = OBject() obj.ks = "09" let jk = obj.sexy_copy() if let testjson = test?.sexy_json(format: true) { print("testJson = " + testjson) } let jsonString = try! String(contentsOfFile: Bundle.main.path(forResource: "ModelObject", ofType: "json")!, encoding: .utf8) let jsonData = jsonString.data(using: .utf8) print("***************** Model *****************\n\n") print("json -> model 对象:") let model = ModelObject.sexy_json(jsonData) print("model = \(String(describing: model))") print("\n---------------------------------------------------\n") print("model 对象 -> 字典:") let modelDict = model?.sexy_dictionary() print("modelDict = \(modelDict!)") print("\n---------------------------------------------------\n") print("model 对象 -> json字符串:") let modelJson = model?.sexy_json() print("modelJson = \(modelJson!)") print("\n***************** [Model] *****************\n\n") print("json -> [Model] 对象:") let arrayModel = [SubArray].sexy_json(modelJson,keyPath: "subArray") print("arrayModel = \(arrayModel!)") print("\n---------------------------------------------------\n") /* keyPath 用法展示 let subArrayModel = SubArray.sexy_json(modelJson,keyPath: "subArray[0]") let subNestArray = NestArray.sexy_json(modelJson,keyPath: "nestArray[0][0]") let test = String.sexy_json(modelJson, keyPath: "nestArray[0][0].test") */ print("[model] 对象 -> 数组:") let arrayModelArray = arrayModel?.sexy_array() print("arrayModelArray = \(arrayModelArray!)") print("\n---------------------------------------------------\n") print("[model] 对象 -> json字符串:") let arrayModelJson = arrayModel?.sexy_json(format: true) print("arrayModelJson = \(arrayModelJson!)") print("\n***************** Model Coding *****************\n\n") let modelCoding = Sub.sexy_json(jsonData, keyPath: "sub") if let modelCodingData = try? JSONEncoder().encode(modelCoding) { if let modelUncoding = try? JSONDecoder().decode(Sub.self, from: modelCodingData) { print("modelUncodingJson = \(modelUncoding.sexy_json()!)") } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setLayout() } private func setLayout() { sexyLab.numberOfLines = 0 sexyLab.textAlignment = .center sexyLab.font = UIFont.boldSystemFont(ofSize: 30) sexyLab.text = "SexyJson\nFast" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
21440c0768876546b549ff3af77a0587
29.89172
132
0.438351
4.627863
false
false
false
false
BridgeTheGap/KRAnimationKit
KRAnimationKit/UIViewExtension/UIView+CenterAnim.swift
1
4473
// // UIView+CenterAnim.swift // KRAnimationKit // // Created by Joshua Park on 15/10/2019. // import UIKit import KRTimingFunction // MARK: - Center public extension UIView { // MARK: - Animate @discardableResult func animate( centerX: CGFloat, duration: Double, function: FunctionType = .linear, reverses: Bool = false, repeatCount: Float = 0.0, completion: (() -> Void)? = nil) -> String { let animDesc = AnimationDescriptor( view: self, delay: 0.0, property: .centerX, endValue: centerX, duration: duration, function: function) return KRAnimation.animate( animDesc, reverses: reverses, repeatCount: repeatCount, completion: completion) } @discardableResult func animate( centerY: CGFloat, duration: Double, function: FunctionType = .linear, reverses: Bool = false, repeatCount: Float = 0.0, completion: (() -> Void)? = nil) -> String { let animDesc = AnimationDescriptor( view: self, delay: 0.0, property: .centerY, endValue: centerY, duration: duration, function: function) return KRAnimation.animate( animDesc, reverses: reverses, repeatCount: repeatCount, completion: completion) } @discardableResult func animate( centerX: CGFloat, centerY: CGFloat, duration: Double, function: FunctionType = .linear, reverses: Bool = false, repeatCount: Float = 0.0, completion: (() -> Void)? = nil) -> String { return animate( center: CGPoint(x: centerX, y: centerY), duration: duration, function: function, reverses: reverses, repeatCount: repeatCount, completion: completion) } @discardableResult func animate( center: CGPoint, duration: Double, function: FunctionType = .linear, reverses: Bool = false, repeatCount: Float = 0.0, completion: (() -> Void)? = nil) -> String { let endValue = NSValue(cgPoint: center) let animDesc = AnimationDescriptor( view: self, delay: 0.0, property: .center, endValue: endValue, duration: duration, function: function) return KRAnimation.animate( animDesc, reverses: reverses, repeatCount: repeatCount, completion: completion) } // MARK: - Chain func chain( centerX: CGFloat, duration: Double, function: FunctionType = .linear) -> [AnimationDescriptor] { return [ AnimationDescriptor( view: self, delay: 0.0, property: .centerX, endValue: centerX, duration: duration, function: function), ] } func chain( centerY: CGFloat, duration: Double, function: FunctionType = .linear) -> [AnimationDescriptor] { return [ AnimationDescriptor( view: self, delay: 0.0, property: .centerY, endValue: centerY, duration: duration, function: function), ] } func chain( centerX: CGFloat, centerY: CGFloat, duration: Double, function: FunctionType = .linear) -> [AnimationDescriptor] { return chain( center: CGPoint(x: centerX, y: centerY), duration: duration, function: function) } func chain( center: CGPoint, duration: Double, function: FunctionType = .linear) -> [AnimationDescriptor] { let endValue = NSValue(cgPoint: center) return [ AnimationDescriptor( view: self, delay: 0.0, property: .center, endValue: endValue, duration: duration, function: function), ] } }
mit
69d127a517d13377243200f786229f9a
23.576923
52
0.497429
5.243845
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Unit/Simulation/View/UnitSimulationAppealEditingCell.swift
1
7406
// // UnitSimulationAppealEditingCell.swift // DereGuide // // Created by zzk on 2017/5/16. // Copyright © 2017年 zzk. All rights reserved. // import UIKit import SnapKit protocol UnitSimulationAppealEditingCellDelegate: class { func unitSimulationAppealEditingCell(_ unitSimulationAppealEditingCell: UnitSimulationAppealEditingCell, didUpdateAt selectionIndex: Int, supportAppeal: Int, customAppeal: Int) func unitSimulationAppealEditingCell(_ unitSimulationAppealEditingCell: UnitSimulationAppealEditingCell, beginEdit textField: UITextField) } extension UnitSimulationAppealEditingCellDelegate { func unitSimulationAppealEditingCell(_ unitSimulationAppealEditingCell: UnitSimulationAppealEditingCell, beginEdit textField: UITextField) { } } class UnitSimulationAppealInputTextField: UITextField { override init(frame: CGRect) { super.init(frame: frame) autocorrectionType = .no autocapitalizationType = .none borderStyle = .roundedRect textAlignment = .right font = UIFont.systemFont(ofSize: 14) keyboardType = .numbersAndPunctuation returnKeyType = .done contentVerticalAlignment = .center } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class UnitSimulationAppealEditingCell: UITableViewCell { // var leftLabel: UILabel! var supportAppealBox: CheckBox! var customAppealBox: CheckBox! var supportAppealTextField: UnitSimulationAppealInputTextField! var customAppealTextField: UnitSimulationAppealInputTextField! weak var delegate: UnitSimulationAppealEditingCellDelegate? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // leftLabel = UILabel() // leftLabel.text = NSLocalizedString("表现值", comment: "队伍详情页面") + ": " // leftLabel.font = UIFont.systemFont(ofSize: 16) // // contentView.addSubview(leftLabel) // leftLabel.snp.makeConstraints { (make) in // make.left.equalTo(10) // make.top.equalTo(10) // } supportAppealBox = CheckBox() supportAppealBox.tintColor = Color.parade supportAppealBox.label.font = UIFont.systemFont(ofSize: 14) supportAppealBox.label.text = NSLocalizedString("使用后援表现值", comment: "队伍详情页面") + ": " supportAppealBox.label.textColor = UIColor.darkGray let tap1 = UITapGestureRecognizer.init(target: self, action: #selector(checkBox(_:))) supportAppealBox.addGestureRecognizer(tap1) contentView.addSubview(supportAppealBox) supportAppealTextField = UnitSimulationAppealInputTextField() supportAppealTextField.addTarget(self, action: #selector(beginEditAppealTextField(sender:)), for: .editingDidBegin) supportAppealTextField.addTarget(self, action: #selector(endEditAppeal), for: .editingDidEnd) supportAppealTextField.addTarget(self, action: #selector(endEditAppeal), for: .editingDidEndOnExit) contentView.addSubview(supportAppealTextField) supportAppealTextField.snp.makeConstraints { (make) in make.right.equalTo(-10) // make.top.equalTo(leftLabel.snp.bottom).offset(5) make.top.equalTo(10) make.width.equalTo(contentView.snp.width).dividedBy(2).offset(-20) make.height.equalTo(30) } supportAppealBox.snp.makeConstraints { (make) in make.left.equalTo(10) make.centerY.equalTo(supportAppealTextField) make.right.lessThanOrEqualTo(supportAppealTextField.snp.left) } customAppealBox = CheckBox() customAppealBox.tintColor = Color.parade customAppealBox.label.font = UIFont.systemFont(ofSize: 14) customAppealBox.label.text = NSLocalizedString("使用固定值", comment: "队伍详情页面") + ": " customAppealBox.label.textColor = UIColor.darkGray let tap2 = UITapGestureRecognizer.init(target: self, action: #selector(checkBox(_:))) customAppealBox.addGestureRecognizer(tap2) contentView.addSubview(customAppealBox) customAppealTextField = UnitSimulationAppealInputTextField() customAppealTextField.addTarget(self, action: #selector(beginEditAppealTextField(sender:)), for: .editingDidBegin) customAppealTextField.addTarget(self, action: #selector(endEditAppeal), for: .editingDidEnd) customAppealTextField.addTarget(self, action: #selector(endEditAppeal), for: .editingDidEndOnExit) contentView.addSubview(customAppealTextField) customAppealTextField.snp.makeConstraints { (make) in make.right.equalTo(-10) make.top.equalTo(supportAppealTextField.snp.bottom).offset(10) make.width.equalTo(contentView.snp.width).dividedBy(2).offset(-20) make.height.equalTo(30) make.bottom.equalTo(-10) } customAppealBox.snp.makeConstraints { (make) in make.left.equalTo(10) make.centerY.equalTo(customAppealTextField) make.right.lessThanOrEqualTo(customAppealTextField.snp.left) } selectionStyle = .none } @objc func beginEditAppealTextField(sender: UITextField) { delegate?.unitSimulationAppealEditingCell(self, beginEdit: sender) } private func validteInputResult() { if let value = Double(supportAppealTextField.text ?? "") { supportAppealTextField.text = String(Int(value)) } else { supportAppealTextField.text = String(CGSSGlobal.defaultSupportAppeal) } if let value = Double(customAppealTextField.text ?? "") { customAppealTextField.text = String(Int(value)) } else { customAppealTextField.text = "0" } } @objc func endEditAppeal() { validteInputResult() delegate?.unitSimulationAppealEditingCell(self, didUpdateAt: supportAppealBox.isChecked ? 0 : 1, supportAppeal: Int(supportAppealTextField.text ?? "") ?? 0, customAppeal: Int(customAppealTextField.text ?? "") ?? 0) } func endEditCheckBox() { endEditAppeal() } func setup(with unit: Unit) { supportAppealBox.setChecked(!unit.usesCustomAppeal) supportAppealTextField.isEnabled = !unit.usesCustomAppeal supportAppealTextField.text = unit.supportAppeal.description customAppealBox.setChecked(unit.usesCustomAppeal) customAppealTextField.isEnabled = unit.usesCustomAppeal customAppealTextField.text = unit.customAppeal.description } @objc func checkBox(_ tap: UITapGestureRecognizer) { supportAppealBox.setChecked(tap.view == supportAppealBox) customAppealBox.setChecked(!(tap.view == supportAppealBox)) supportAppealTextField.isEnabled = (tap.view == supportAppealBox) customAppealTextField.isEnabled = !(tap.view == supportAppealBox) endEditCheckBox() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
0625a9e50e72d990ef0efdfa6207f22d
38.659459
222
0.68175
4.773585
false
false
false
false
zzBelieve/Hello_Swift
Hello Swift/Hello Swift/ViewController.swift
1
3602
// // ViewController.swift // Hello Swift // // Created by ZZBelieve on 15/8/17. // Copyright (c) 2015年 galaxy-link. All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{ var dataList = ["列表展示(Header Footer)","tableView操作(插入,增加)","ScrollView","LOL _ Heros ","团购 XIB ","图片轮播","汽车品牌展示"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let ZZTableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain) ZZTableView.dataSource = self ZZTableView.delegate = self self.view .addSubview(ZZTableView) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier : String = "cell" var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell if (cell == nil){ cell = UITableViewCell (style: UITableViewCellStyle.Default, reuseIdentifier: identifier) } cell?.textLabel?.text = self.dataList[indexPath.row] as? String return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let titile: NSString = self.dataList[indexPath.row] switch indexPath.row { case 0 : let vc1 = ViewController1(); vc1.title = titile as String self.navigationController?.pushViewController(vc1, animated: true) case 1 : let vc2 = ViewController2(); vc2.title = titile as String self.navigationController?.pushViewController(vc2, animated: true) case 2 : let vc3 = ViewController3(); vc3.title = titile as String self.navigationController?.pushViewController(vc3, animated: true) case 3 : let vc4 = ViewController4(); vc4.title = titile as String self.navigationController?.pushViewController(vc4, animated: true) case 4 : let vc5 = ViewController5(); vc5.title = titile as String self.navigationController?.pushViewController(vc5, animated: true) case 5 : let vc6 = ViewController6(); vc6.title = titile as String self.navigationController?.pushViewController(vc6, animated: true) case 6 : let vc7 = ViewController7(); vc7.title = titile as String self.navigationController?.pushViewController(vc7, animated: true) default: println("11") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
5403605d1b4b0d406a4ef9f9debd01b0
27
117
0.539933
5.735484
false
false
false
false
FuckBoilerplate/RxCache
Examples/Pods/Gloss/Sources/Gloss.swift
1
3300
// // Gloss.swift // Gloss // // Copyright (c) 2015 Harlan Kellaway // // 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 // MARK: - Types public typealias JSON = [String : Any] // MARK: - Protocols /** Convenience protocol for objects that can be translated from and to JSON. */ public protocol Glossy: Decodable, Encodable { } /** Enables an object to be decoded from JSON. */ public protocol Decodable { /** Returns new instance created from provided JSON. - parameter: json: JSON representation of object. */ init?(json: JSON) } /** Enables an object to be encoded to JSON. */ public protocol Encodable { /** Encodes and object as JSON. - returns: JSON when encoding was successful, nil otherwise. */ func toJSON() -> JSON? } // MARK: - Global /** Date formatter used for ISO8601 dates. - returns: Date formatter. */ public private(set) var GlossDateFormatterISO8601: DateFormatter = { let dateFormatterISO8601 = DateFormatter() // WORKAROUND to ignore device configuration regarding AM/PM http://openradar.appspot.com/radar?id=1110403 dateFormatterISO8601.locale = Locale(identifier: "en_US_POSIX") dateFormatterISO8601.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" // translate to Gregorian calendar if other calendar is selected in system settings var gregorian = Calendar(identifier: .gregorian) gregorian.timeZone = TimeZone(abbreviation: "GMT")! dateFormatterISO8601.calendar = gregorian return dateFormatterISO8601 }() /** Default delimiter used for nested key paths. - returns: Default key path delimiter. */ public private(set) var GlossKeyPathDelimiter: String = { return "." }() /** Transforms an array of JSON optionals to a single optional JSON dictionary. - parameter array: Array of JSON to transform. - parameter keyPathDelimiter: Delimiter used for nested key paths. - returns: JSON when successful, nil otherwise. */ public func jsonify(_ array: [JSON?], keyPathDelimiter: String = GlossKeyPathDelimiter) -> JSON? { var json: JSON = [:] for j in array { if(j != nil) { json.add(j!, delimiter: keyPathDelimiter) } } return json }
mit
7c2ed3ffb7303b326568565457a5858b
27.205128
110
0.706061
4.459459
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/KPCafeRequest.swift
1
2670
// // KPCafeRequest.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/5/1. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit import ObjectMapper import PromiseKit import Alamofire class KPCafeRequest: NetworkRequest { typealias ResponseType = RawJsonResult private var limitedTime: NSNumber? private var socket: NSNumber? private var standingDesk: NSNumber? private var mrt: String? private var city: String? private var rightTopCoordinate: CLLocationCoordinate2D? private var leftBottomCoordinate: CLLocationCoordinate2D? private var searchText: String? var endpoint: String { return "/cafes" } var parameters: [String : Any]? { var parameters = [String : Any]() if self.limitedTime != nil { parameters["limited_time"] = self.limitedTime } if self.socket != nil { parameters["socket"] = self.socket } if self.standingDesk != nil { parameters["standing_desk"] = self.standingDesk } if self.mrt != nil { parameters["mrt"] = self.mrt } if self.city != nil { parameters["city"] = self.city } if self.rightTopCoordinate != nil { parameters["first_corner"] = "\(self.rightTopCoordinate!.latitude),\(self.rightTopCoordinate!.longitude)" } if self.leftBottomCoordinate != nil { parameters["third_corner"] = "\(self.leftBottomCoordinate!.latitude),\(self.leftBottomCoordinate!.longitude)" } if self.searchText != nil { parameters["text"] = self.searchText } return parameters } var method: Alamofire.HTTPMethod { return .get } public func perform(_ limitedTime: NSNumber? = nil, _ socket: NSNumber? = nil, _ standingDesk: NSNumber? = nil, _ mrt: String? = nil, _ city: String? = nil, _ rightTop: CLLocationCoordinate2D? = nil, _ leftBottom: CLLocationCoordinate2D? = nil, _ searchText: String? = nil) -> Promise<(ResponseType)> { self.limitedTime = limitedTime self.socket = socket self.standingDesk = standingDesk self.mrt = mrt self.city = city self.rightTopCoordinate = rightTop self.leftBottomCoordinate = leftBottom self.searchText = searchText return networkClient.performRequest(self).then(execute: responseHandler) } }
mit
43b5d44a3d2769c166c0bdfcd70c58ff
31.52439
121
0.580052
4.884615
false
false
false
false
dbart01/Rigid
Rigid/Line.swift
1
2503
// // Line.swift // Rigid // // Copyright (c) 2015 Dima Bart // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. import Foundation struct Line: Writable { let indent: Int let string: String // ---------------------------------- // MARK: - Container Init - // static func linesWithBody(body: String) -> [Line] { var lines = [Line]() let strings = body.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) for string in strings { lines += Line(indent: 0, string: string) } return lines } // ---------------------------------- // MARK: - Init - // init(indent: Int, string: String) { self.indent = indent self.string = string } // ---------------------------------- // MARK: - Writable - // func content() -> String { return "\(self.indent(self.indent))\(self.string)\n" } }
bsd-2-clause
19bc31e091e1c2ae62a3016ef09b3927
35.823529
101
0.655214
4.687266
false
false
false
false
Andgfaria/MiniGitClient-iOS
MiniGitClient/MiniGitClientTests/Scenes/Detail/RepositoryDetailViewControllerSpec.swift
1
3939
/* Copyright 2017 - André Gimenez Faria 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 Quick import Nimble import RxSwift @testable import MiniGitClient private class MockPresenter : RepositoryDetailPresenterType { var repository = Variable(Repository()) var pullRequests = Variable([PullRequest()]) var currentState = Variable(RepositoryDetailState.loading) var didReturnShareItems = false var shareItems: [Any] { didReturnShareItems = true return [] } } class RepositoryDetailViewControllerSpec: QuickSpec { override func spec() { describe("The RepositoryDetailViewController") { var viewController = RepositoryDetailViewController(nibName: nil, bundle: nil) var mockPresenter = MockPresenter() var tableView : UITableView? var headerView : RepositoryDetailHeaderView? beforeEach { viewController = RepositoryDetailViewController(nibName: nil, bundle: nil) mockPresenter = MockPresenter() viewController.presenter = mockPresenter viewController.view.layoutIfNeeded() tableView = viewController.view.subviews.flatMap { $0 as? UITableView }.first headerView = tableView?.tableHeaderView as? RepositoryDetailHeaderView } context("has", { it("a table view") { expect(tableView).toNot(beNil()) } it("a header view") { expect(headerView).toNot(beNil()) } }) context("changes", { it("the header view state to loaded when the presenter retrieved the pull requests") { mockPresenter.currentState.value = .showingPullRequests expect(headerView?.currentState.value) == .loaded } it("the header view state to showingRetryOption when the presenter failed") { mockPresenter.currentState.value = .onError expect(headerView?.currentState.value) == .showingRetryOption } }) context("shares", { it("the presenter's share items through a navigation bar right button item") { guard let shareButton = viewController.navigationItem.rightBarButtonItem else { fail(); return } viewController.share(sender: shareButton) expect(mockPresenter.didReturnShareItems).to(beTrue()) } }) } } }
mit
eb00407f899e167d6f4bf996ffe537ad
37.990099
461
0.597765
6.231013
false
false
false
false
yapmobile/ExpandingMenu
ExpandingMenu/Classes/ExpandingMenuButton.swift
1
26214
// // ExpandingMenuButton.swift // // Created by monoqlo on 2015/07/21. // Copyright (c) 2015年 monoqlo All rights reserved. // import UIKit import AudioToolbox public struct AnimationOptions : OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let MenuItemRotation = AnimationOptions(rawValue: 1) public static let MenuItemBound = AnimationOptions(rawValue: 2) public static let MenuItemMoving = AnimationOptions(rawValue: 4) public static let MenuItemFade = AnimationOptions(rawValue: 8) public static let MenuButtonRotation = AnimationOptions(rawValue: 16) public static let Default: AnimationOptions = [MenuItemRotation, MenuItemBound, MenuItemMoving, MenuButtonRotation] public static let All: AnimationOptions = [MenuItemRotation, MenuItemBound, MenuItemMoving, MenuItemFade, MenuButtonRotation] } open class ExpandingMenuButton: UIView, UIGestureRecognizerDelegate { public enum ExpandingDirection { case top case bottom } public enum MenuTitleDirection { case left case right } // MARK: Public Properties open var menuItemMargin: CGFloat = 16.0 open var shouldCloseMenuOnItemSelected = true open var shouldEnableBottomView = true { didSet { self.bottomView.frame.size.width = self.shouldEnableBottomView ? self.expandingSize.width : 0 self.bottomView.frame.size.height = self.shouldEnableBottomView ? self.expandingSize.height : 0 self.bottomView.isUserInteractionEnabled = self.shouldEnableBottomView } } open var allowSounds: Bool = true { didSet { self.configureSounds() } } open var expandingSoundPath: String = Bundle(url: Bundle(for: ExpandingMenuButton.classForCoder()).url(forResource: "ExpandingMenu", withExtension: "bundle")!)?.path(forResource: "expanding", ofType: "caf") ?? "" { didSet { self.configureSounds() } } open var foldSoundPath: String = Bundle(url: Bundle(for: ExpandingMenuButton.classForCoder()).url(forResource: "ExpandingMenu", withExtension: "bundle")!)?.path(forResource: "fold", ofType: "caf") ?? "" { didSet { self.configureSounds() } } open var selectedSoundPath: String = Bundle(url: Bundle(for: ExpandingMenuButton.classForCoder()).url(forResource: "ExpandingMenu", withExtension: "bundle")!)?.path(forResource: "selected", ofType: "caf") ?? "" { didSet { self.configureSounds() } } open var bottomViewColor: UIColor = UIColor.black { didSet { self.bottomView.backgroundColor = bottomViewColor } } open var bottomViewAlpha: CGFloat = 0.618 open var titleTappedActionEnabled: Bool = true open var expandingDirection: ExpandingDirection = ExpandingDirection.top open var menuTitleDirection: MenuTitleDirection = MenuTitleDirection.left open var enabledExpandingAnimations: AnimationOptions = .Default open var enabledFoldingAnimations: AnimationOptions = .Default open var willPresentMenuItems: ((ExpandingMenuButton) -> Void)? open var didPresentMenuItems: ((ExpandingMenuButton) -> Void)? open var willDismissMenuItems: ((ExpandingMenuButton) -> Void)? open var didDismissMenuItems: ((ExpandingMenuButton) -> Void)? // MARK: Private Properties fileprivate var defaultCenterPoint: CGPoint = CGPoint.zero fileprivate var itemButtonImages: [UIImage] = [] fileprivate var itemButtonHighlightedImages: [UIImage] = [] fileprivate var centerImage: UIImage? fileprivate var centerHighlightedImage: UIImage? fileprivate var expandingSize: CGSize = UIScreen.main.bounds.size fileprivate var foldedSize: CGSize = CGSize.zero fileprivate var bottomView: UIView = UIView() fileprivate var centerButton: UIButton = UIButton() fileprivate var menuItems: [ExpandingMenuItem] = [] fileprivate var foldSound: SystemSoundID = 0 fileprivate var expandingSound: SystemSoundID = 0 fileprivate var selectedSound: SystemSoundID = 0 fileprivate var isExpanding: Bool = false fileprivate var isAnimating: Bool = false // MARK: - Initializer public init(frame: CGRect, centerImage: UIImage, centerHighlightedImage: UIImage) { super.init(frame: frame) func configureViewsLayoutWithButtonSize(_ centerButtonSize: CGSize) { // Configure menu button frame // self.foldedSize = centerButtonSize self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.foldedSize.width, height: self.foldedSize.height); // Congifure center button // self.centerButton = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: centerButtonSize.width, height: centerButtonSize.height)) self.centerButton.setImage(self.centerImage, for: UIControlState()) self.centerButton.setImage(self.centerHighlightedImage, for: UIControlState.highlighted) self.centerButton.addTarget(self, action: #selector(centerButtonTapped), for: UIControlEvents.touchDown) self.centerButton.center = CGPoint(x: self.frame.width / 2.0, y: self.frame.height / 2.0) self.addSubview(self.centerButton) // Configure bottom view self.bottomView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.expandingSize.width, height: self.expandingSize.height)) self.bottomView.backgroundColor = self.bottomViewColor self.bottomView.alpha = 0.0 // Make bottomView's touch can delay superView witch like UIScrollView scrolling // self.bottomView.isUserInteractionEnabled = true; let tapGesture = UIGestureRecognizer() tapGesture.delegate = self self.bottomView.addGestureRecognizer(tapGesture) } // Configure enter and highlighted center image // self.centerImage = centerImage self.centerHighlightedImage = centerHighlightedImage if frame == CGRect.zero { configureViewsLayoutWithButtonSize(self.centerImage?.size ?? CGSize.zero) } else { configureViewsLayoutWithButtonSize(frame.size) self.defaultCenterPoint = self.center } self.configureSounds() } public convenience init(centerImage: UIImage, centerHighlightedImage: UIImage) { self.init(frame: CGRect.zero, centerImage: centerImage, centerHighlightedImage: centerHighlightedImage) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Configure Menu Items open func addMenuItems(_ menuItems: [ExpandingMenuItem]) { self.menuItems += menuItems } // MARK: - Menu Item Tapped Action open func menuItemTapped(_ item: ExpandingMenuItem) { guard self.shouldCloseMenuOnItemSelected else { return } self.willDismissMenuItems?(self) self.isAnimating = true let selectedIndex: Int = item.index if self.allowSounds == true { AudioServicesPlaySystemSound(self.selectedSound) } // Excute the explode animation when the item is seleted // UIView.animate(withDuration: 0.0618 * 5.0, animations: { () -> Void in item.transform = CGAffineTransform(scaleX: 3.0, y: 3.0) item.alpha = 0.0 }) // Excute the dismiss animation when the item is unselected // for (index, item) in self.menuItems.enumerated() { // Remove title button // if let titleButton = item.titleButton { UIView.animate(withDuration: 0.15, animations: { () -> Void in titleButton.alpha = 0.0 }, completion: { (finished) -> Void in titleButton.removeFromSuperview() }) } if index == selectedIndex { continue } UIView.animate(withDuration: 0.0618 * 2.0, animations: { () -> Void in item.transform = CGAffineTransform(scaleX: 0.0, y: 0.0) }) } self.resizeToFoldedFrame { () -> Void in self.isAnimating = false self.didDismissMenuItems?(self) } } // MARK: - Center Button Action @objc fileprivate func centerButtonTapped() { if self.isAnimating == false { if self.isExpanding == true { self.foldMenuItems() } else { self.expandMenuItems() } } } // MARK: - Configure Sounds fileprivate func configureSounds() { if self.allowSounds == true { let expandingSoundUrl = URL(fileURLWithPath: self.expandingSoundPath) AudioServicesCreateSystemSoundID(expandingSoundUrl as CFURL, &self.expandingSound) let foldSoundUrl = URL(fileURLWithPath: self.foldSoundPath) AudioServicesCreateSystemSoundID(foldSoundUrl as CFURL, &self.foldSound) let selectedSoundUrl = URL(fileURLWithPath: self.selectedSoundPath) AudioServicesCreateSystemSoundID(selectedSoundUrl as CFURL, &self.selectedSound) } else { AudioServicesDisposeSystemSoundID(self.expandingSound) AudioServicesDisposeSystemSoundID(self.foldSound) AudioServicesDisposeSystemSoundID(self.selectedSound) } } // MARK: - Calculate The Distance From Center Button fileprivate func makeDistanceFromCenterButton(_ itemSize: CGSize, lastDisance: CGFloat, lastItemSize: CGSize) -> CGFloat { return lastDisance + itemSize.height / 2.0 + self.menuItemMargin + lastItemSize.height / 2.0 } // MARK: - Caculate The Item's End Point fileprivate func makeEndPoint(_ itemExpandRadius: CGFloat, angle: CGFloat) -> CGPoint { switch self.expandingDirection { case .top: return CGPoint( x: self.centerButton.center.x + CGFloat(cosf((Float(angle) + 1.0) * Float.pi)) * itemExpandRadius, y: self.centerButton.center.y + CGFloat(sinf((Float(angle) + 1.0) * Float.pi)) * itemExpandRadius ) case .bottom: return CGPoint( x: self.centerButton.center.x + CGFloat(cosf(Float(angle) * Float.pi)) * itemExpandRadius, y: self.centerButton.center.y + CGFloat(sinf(Float(angle) * Float.pi)) * itemExpandRadius ) } } // MARK: - Fold Menu Items fileprivate func foldMenuItems() { self.willDismissMenuItems?(self) self.isAnimating = true if self.allowSounds == true { AudioServicesPlaySystemSound(self.foldSound) } let currentAngle: CGFloat = 90.0 var lastDistance: CGFloat = 0.0 var lastItemSize: CGSize = self.centerButton.bounds.size for item in self.menuItems { let distance: CGFloat = self.makeDistanceFromCenterButton(item.bounds.size, lastDisance: lastDistance, lastItemSize: lastItemSize) lastDistance = distance lastItemSize = item.bounds.size let backwardPoint: CGPoint = self.makeEndPoint(distance + 5.0, angle: currentAngle / 180.0) let foldAnimation: CAAnimationGroup = self.makeFoldAnimation(startingPoint: item.center, backwardPoint: backwardPoint, endPoint: self.centerButton.center) item.layer.add(foldAnimation, forKey: "foldAnimation") item.center = self.centerButton.center // Remove title button // if let titleButton = item.titleButton { UIView.animate(withDuration: 0.15, animations: { () -> Void in titleButton.alpha = 0.0 }, completion: { (finished) -> Void in titleButton.removeFromSuperview() }) } } self.bringSubview(toFront: self.centerButton) // Resize the ExpandingMenuButton's frame to the foled frame and remove the item buttons // self.resizeToFoldedFrame { () -> Void in self.isAnimating = false self.didDismissMenuItems?(self) } } fileprivate func resizeToFoldedFrame(completion: (() -> Void)?) { if self.enabledFoldingAnimations.contains(.MenuButtonRotation) == true { UIView.animate(withDuration: 0.0618 * 3, delay: 0.0618 * 2, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in self.centerButton.transform = CGAffineTransform(rotationAngle: 0.0) }, completion: nil) } else { self.centerButton.transform = CGAffineTransform(rotationAngle: 0.0) } UIView.animate(withDuration: 0.15, delay: 0.35, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.bottomView.alpha = 0.0 }, completion: { (finished) -> Void in // Remove the items from the superview // for item in self.menuItems { item.removeFromSuperview() } self.frame = CGRect(x: 0.0, y: 0.0, width: self.foldedSize.width, height: self.foldedSize.height) self.center = self.defaultCenterPoint self.centerButton.center = CGPoint(x: self.frame.width / 2.0, y: self.frame.height / 2.0) self.bottomView.removeFromSuperview() completion?() }) self.isExpanding = false } fileprivate func makeFoldAnimation(startingPoint: CGPoint, backwardPoint: CGPoint, endPoint: CGPoint) -> CAAnimationGroup { let animationGroup: CAAnimationGroup = CAAnimationGroup() animationGroup.animations = [] animationGroup.duration = 0.35 // 1.Configure rotation animation // if self.enabledFoldingAnimations.contains(.MenuItemRotation) == true { let rotationAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotationAnimation.values = [0.0, Double.pi, Double.pi * 2.0] rotationAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) rotationAnimation.duration = 0.35 animationGroup.animations?.append(rotationAnimation) } // 2.Configure moving animation // let movingAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position") // Create moving path // let path: CGMutablePath = CGMutablePath() if self.enabledFoldingAnimations.contains([.MenuItemMoving, .MenuItemBound]) == true { path.move(to: CGPoint(x: startingPoint.x, y: startingPoint.y)) path.addLine(to: CGPoint(x: backwardPoint.x, y: backwardPoint.y)) path.addLine(to: CGPoint(x: endPoint.x, y: endPoint.y)) movingAnimation.keyTimes = [0.0, 0.75, 1.0] } else if self.enabledFoldingAnimations.contains(.MenuItemMoving) == true { path.move(to: CGPoint(x: startingPoint.x, y: startingPoint.y)) path.addLine(to: CGPoint(x: endPoint.x, y: endPoint.y)) movingAnimation.keyTimes = [0.0, 0.75, 1.0] } else if self.enabledFoldingAnimations.contains(.MenuItemBound) == true { path.move(to: CGPoint(x: startingPoint.x, y: startingPoint.y)) path.addLine(to: CGPoint(x: backwardPoint.x, y: backwardPoint.y)) path.addLine(to: CGPoint(x: startingPoint.x, y: startingPoint.y)) movingAnimation.keyTimes = [0.0, 0.3, 0.5, 1.0] } else if self.enabledFoldingAnimations.contains(.MenuItemFade) { path.move(to: CGPoint(x: startingPoint.x, y: startingPoint.y)) path.addLine(to: CGPoint(x: startingPoint.x, y: startingPoint.y)) } movingAnimation.path = path movingAnimation.duration = 0.35 animationGroup.animations?.append(movingAnimation) // 3.Configure fade animation // if self.enabledFoldingAnimations.contains(.MenuItemFade) { let fadeAnimation = CAKeyframeAnimation(keyPath: "opacity") fadeAnimation.values = [1.0, 0.0] fadeAnimation.keyTimes = [0.0, 0.75, 1.0] fadeAnimation.duration = 0.35 animationGroup.animations?.append(fadeAnimation) } return animationGroup } // MARK: - Expand Menu Items open func expandMenuItems() { self.willPresentMenuItems?(self) self.isAnimating = false if self.allowSounds == true { AudioServicesPlaySystemSound(self.expandingSound) } self.defaultCenterPoint = self.center // Configure center button expanding // // 1. Copy the current center point and backup default center point // // 2. Resize the frame // if self.shouldEnableBottomView { self.centerButton.center = self.center self.frame = CGRect(x: 0.0, y: 0.0, width: self.expandingSize.width, height: self.expandingSize.height) self.center = CGPoint(x: self.expandingSize.width / 2.0, y: self.expandingSize.height / 2.0) } else { // so ugly, need to precalculate item last distance to adjust self.height var lastDistance: CGFloat = 0.0 var lastItemSize: CGSize = self.centerButton.bounds.size for (_, item) in self.menuItems.enumerated() { let distance: CGFloat = self.makeDistanceFromCenterButton(item.bounds.size, lastDisance: lastDistance, lastItemSize: lastItemSize) lastDistance = distance lastItemSize = item.bounds.size } self.frame.origin.y -= lastDistance self.frame.size.height = lastDistance + self.foldedSize.height self.centerButton.frame.origin.y = self.frame.height - self.foldedSize.height } self.insertSubview(self.bottomView, belowSubview: self.centerButton) // 3. Excute the bottom view alpha animation // UIView.animate(withDuration: 0.0618 * 3, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in self.bottomView.alpha = self.bottomViewAlpha }, completion: nil) // 4. Excute the center button rotation animation // if self.enabledExpandingAnimations.contains(.MenuButtonRotation) == true { UIView.animate(withDuration: 0.1575, animations: { () -> Void in self.centerButton.transform = CGAffineTransform(rotationAngle: CGFloat(-0.5 * Float.pi)) }) } else { self.centerButton.transform = CGAffineTransform(rotationAngle: CGFloat(-0.5 * Float.pi)) } // 5. Excute the expanding animation // let currentAngle: CGFloat = 90.0 var lastDistance: CGFloat = 0.0 var lastItemSize: CGSize = self.centerButton.bounds.size for (index, item) in self.menuItems.enumerated() { item.delegate = self item.index = index item.transform = CGAffineTransform(translationX: 1.0, y: 1.0) item.alpha = 1.0 // 1. Add item to the view // item.center = self.centerButton.center self.insertSubview(item, belowSubview: self.centerButton) // 2. Excute expand animation // let distance: CGFloat = self.makeDistanceFromCenterButton(item.bounds.size, lastDisance: lastDistance, lastItemSize: lastItemSize) lastDistance = distance lastItemSize = item.bounds.size let endPoint: CGPoint = self.makeEndPoint(distance, angle: currentAngle / 180.0) let farPoint: CGPoint = self.makeEndPoint(distance + 10.0, angle: currentAngle / 180.0) let nearPoint: CGPoint = self.makeEndPoint(distance - 5.0, angle: currentAngle / 180.0) let expandingAnimation: CAAnimationGroup = self.makeExpandingAnimation(startingPoint: item.center, farPoint: farPoint, nearPoint: nearPoint, endPoint: endPoint) item.layer.add(expandingAnimation, forKey: "expandingAnimation") item.center = endPoint // 3. Add Title Button // item.titleTappedActionEnabled = self.titleTappedActionEnabled if let titleButton = item.titleButton { titleButton.center = endPoint let margin: CGFloat = item.titleMargin let originX: CGFloat switch self.menuTitleDirection { case .left: originX = endPoint.x - item.bounds.width / 2.0 - margin - titleButton.bounds.width case .right: originX = endPoint.x + item.bounds.width / 2.0 + margin; } var titleButtonFrame: CGRect = titleButton.frame titleButtonFrame.origin.x = originX titleButton.frame = titleButtonFrame titleButton.alpha = 0.0 self.insertSubview(titleButton, belowSubview: self.centerButton) UIView.animate(withDuration: 0.3, animations: { () -> Void in titleButton.alpha = 1.0 }) } } // Configure the expanding status // self.isExpanding = true self.isAnimating = false self.didPresentMenuItems?(self) } fileprivate func makeExpandingAnimation(startingPoint: CGPoint, farPoint: CGPoint, nearPoint: CGPoint, endPoint: CGPoint) -> CAAnimationGroup { let animationGroup: CAAnimationGroup = CAAnimationGroup() animationGroup.animations = [] animationGroup.duration = 0.3 // 1.Configure rotation animation // if self.enabledExpandingAnimations.contains(.MenuItemRotation) == true { let rotationAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotationAnimation.values = [0.0, -Double.pi, -Double.pi * 1.5, -Double.pi * 2.0] rotationAnimation.duration = 0.3 rotationAnimation.keyTimes = [0.0, 0.3, 0.6, 1.0] animationGroup.animations?.append(rotationAnimation) } // 2.Configure moving animation // let movingAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position") // Create moving path // let path: CGMutablePath = CGMutablePath() if self.enabledExpandingAnimations.contains([.MenuItemMoving, .MenuItemBound]) == true { path.move(to: CGPoint(x: startingPoint.x, y: startingPoint.y)) path.addLine(to: CGPoint(x: farPoint.x, y: farPoint.y)) path.addLine(to: CGPoint(x: nearPoint.x, y: nearPoint.y)) path.addLine(to: CGPoint(x: endPoint.x, y: endPoint.y)) movingAnimation.keyTimes = [0.0, 0.5, 0.7, 1.0] } else if self.enabledExpandingAnimations.contains(.MenuItemMoving) == true { path.move(to: CGPoint(x: startingPoint.x, y: startingPoint.y)) path.addLine(to: CGPoint(x: endPoint.x, y: endPoint.y)) movingAnimation.keyTimes = [0.0, 0.5, 1.0] } else if self.enabledExpandingAnimations.contains(.MenuItemBound) == true { path.move(to: CGPoint(x: farPoint.x, y: farPoint.y)) path.addLine(to: CGPoint(x: nearPoint.x, y: nearPoint.y)) path.addLine(to: CGPoint(x: endPoint.x, y: endPoint.y)) movingAnimation.keyTimes = [0.0, 0.3, 0.5, 1.0] } else if self.enabledExpandingAnimations.contains(.MenuItemFade) { path.move(to: CGPoint(x: endPoint.x, y: endPoint.y)) path.addLine(to: CGPoint(x: endPoint.x, y: endPoint.y)) } movingAnimation.path = path movingAnimation.duration = 0.3 animationGroup.animations?.append(movingAnimation) // 3.Configure fade animation // if self.enabledExpandingAnimations.contains(.MenuItemFade) { let fadeAnimation = CAKeyframeAnimation(keyPath: "opacity") fadeAnimation.values = [0.0, 1.0] fadeAnimation.duration = 0.3 animationGroup.animations?.append(fadeAnimation) } return animationGroup } // MARK: - Touch Event override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // Tap the bottom area, excute the fold animation self.foldMenuItems() } // MARK: - UIGestureRecognizer Delegate override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
mit
e7014553e28ec5a3aab38f668d8cfad6
40.872204
218
0.609454
4.927994
false
false
false
false
thecodershub/algorithms
swift/sort/insertion_sort.swift
1
1022
// Insertion sort implementation in Swift // https://en.wikipedia.org/wiki/Insertion_sort func insertionSort(inputArray: Array<Int>) -> Array<Int> { //Implementation of iterative insertion sort. var inputArray = inputArray; let n = inputArray.count; for i in 0..<n { var j = i; while (j > 0) && (inputArray[j-1] > inputArray[j]) { swap(&inputArray[j], &inputArray[j-1]); j -= 1; } } return inputArray; } func main() { let lis1 = [4, 1, 2, 3, 9]; let lis2 = [1]; let lis3 = [2, 2, 1, -1, 0, 4, 5, 2]; let lis4 = [Int](); let sorted_lis1 = insertionSort(inputArray: lis1); assert(sorted_lis1 == [1, 2, 3, 4, 9]); let sorted_lis2 = insertionSort(inputArray: lis2); assert(sorted_lis2 == [1]); let sorted_lis3 = insertionSort(inputArray: lis3); assert(sorted_lis3 == [-1, 0, 1, 2, 2, 2, 4, 5]); let sorted_lis4 = insertionSort(inputArray: lis4); assert(sorted_lis4 == []); } main();
gpl-3.0
950eb818194e0e5281dad7e0c537e858
25.921053
60
0.563601
3.203762
false
false
false
false
cuappdev/eatery
Eatery/Controllers/Eateries/Campus/CampusEateriesViewController.swift
1
9332
// // CampusEateriesViewController.swift // Eatery // // Created by William Ma on 3/14/19. // Copyright © 2019 CUAppDev. All rights reserved. // import os.log import CoreLocation import UIKit class CampusEateriesViewController: EateriesViewController { private var allEateries: [CampusEatery]? private var preselectedEateryName: String? override func viewDidLoad() { super.viewDidLoad() dataSource = self delegate = self availableFilters = [ .nearest, .north, .west, .central, .swipes, .brb ] queryCampusEateries() } private func queryCampusEateries() { NetworkManager.shared.getCampusEateries { [weak self] (eateries, error) in guard let `self` = self else { return } guard let eateries = eateries else { if let error = error { self.updateState(.failedToLoad(error), animated: true) } return } os_log("Successfully loaded %d campus eateries", eateries.count) self.allEateries = eateries self.updateState(.presenting, animated: true) self.pushPreselectedEateryIfPossible() } } func preselectEatery(withName name: String) { preselectedEateryName = name pushPreselectedEateryIfPossible() } private func pushPreselectedEateryIfPossible() { guard let name = preselectedEateryName else { return } guard let eatery = allEateries?.first(where: { $0.name == name }) else { return } showMenu(of: eatery, animated: false) preselectedEateryName = nil } private func showMenu(of eatery: CampusEatery, animated: Bool) { let menuViewController = CampusMenuViewController(eatery: eatery, userLocation: userLocation) navigationController?.popToRootViewController(animated: animated) navigationController?.pushViewController(menuViewController, animated: animated) let payload: Payload if eatery.eateryType == .dining { payload = CampusDiningCellPressPayload(diningHallName: eatery.displayName) } else { payload = CampusCafeCellPressPayload(cafeName: eatery.displayName) } AppDevAnalytics.shared.logFirebase(payload) } override func filterBar(_ filterBar: FilterBar, filterWasSelected filter: Filter) { switch filter { case .nearest: AppDevAnalytics.shared.logFirebase(NearestFilterPressPayload()) case .north: AppDevAnalytics.shared.logFirebase(NorthFilterPressPayload()) case .west: AppDevAnalytics.shared.logFirebase(WestFilterPressPayload()) case .central: AppDevAnalytics.shared.logFirebase(CentralFilterPressPayload()) case .swipes: AppDevAnalytics.shared.logFirebase(SwipesFilterPressPayload()) case .brb: AppDevAnalytics.shared.logFirebase(BRBFilterPressPayload()) default: break } } } // MARK: - Eateries View Controller Data Source extension CampusEateriesViewController: EateriesViewControllerDataSource { func eateriesViewController(_ evc: EateriesViewController, eateriesToPresentWithSearchText searchText: String, filters: Set<Filter>) -> [Eatery] { guard let eateries = allEateries else { return [] } var filteredEateries = eateries if !searchText.isEmpty { filteredEateries = filter(eateries: filteredEateries, withSearchText: searchText) } filteredEateries = filter(eateries: filteredEateries, withFilters: filters) return filteredEateries } private func filter(eateries: [CampusEatery], withSearchText searchText: String) -> [CampusEatery] { return eateries.filter { eatery in if search(searchText, matches: eatery.name) || eatery.allNicknames.contains(where: { search(searchText, matches: $0) }) { return true } if let area = eatery.area, search(searchText, matches: area.rawValue) { return true } if eatery.diningItems(onDayOf: Date()).contains(where: { search(searchText, matches: $0.name) }) { return true } if let activeEvent = eatery.activeEvent(atExactly: Date()), activeEvent.menu.stringRepresentation.flatMap({ $0.1 }).contains(where: { search(searchText, matches: $0) }) { return true } return false } } private func filter(eateries: [CampusEatery], withFilters filters: Set<Filter>) -> [CampusEatery] { var filteredEateries = eateries filteredEateries = filteredEateries.filter { if filters.contains(.swipes) { return $0.paymentMethods.contains(.swipes) } if filters.contains(.brb) { return $0.paymentMethods.contains(.brb) } return true } if !filters.intersection(Filter.areaFilters).isEmpty { filteredEateries = filteredEateries.filter { guard let area = $0.area else { return false } switch area { case .north: return filters.contains(.north) case .west: return filters.contains(.west) case .central: return filters.contains(.central) } } } return filteredEateries } func eateriesViewController(_ evc: EateriesViewController, sortMethodWithSearchText searchText: String, filters: Set<Filter>) -> EateriesViewController.SortMethod { if filters.contains(.nearest), let userLocation = userLocation { return .nearest(userLocation) } else { return .alphabetical } } func eateriesViewController(_ evc: EateriesViewController, highlightedSearchDescriptionForEatery eatery: Eatery, searchText: String, filters: Set<Filter>) -> NSAttributedString? { guard !searchText.isEmpty, let eatery = eatery as? CampusEatery else { return nil } let string = NSMutableAttributedString() for itemText in eatery.diningItems(onDayOf: Date()).map({ $0.name }) { if let range = matchRange(of: searchText, in: itemText) { string.append(highlighted(text: itemText + "\n", range: range)) } } if let activeEvent = eatery.activeEvent(atExactly: Date()) { for itemText in activeEvent.menu.stringRepresentation.flatMap({ $0.1 }) { if let range = matchRange(of: searchText, in: itemText) { string.append(highlighted(text: itemText + "\n", range: range)) } } } return (string.length == 0) ? nil : string } private func matchRange(of searchText: String, in text: String) -> Range<String.Index>? { return text.range(of: searchText, options: [.caseInsensitive]) } private func search(_ searchText: String, matches text: String) -> Bool { return matchRange(of: searchText, in: text) != nil } private func highlighted(text: String, range: Range<String.Index>) -> NSAttributedString { let string = NSMutableAttributedString(string: text, attributes: [ .foregroundColor : UIColor.gray, .font : UIFont.systemFont(ofSize: 11) ]) string.addAttributes([ .foregroundColor: UIColor.darkGray, .font: UIFont.systemFont(ofSize: 11, weight: .bold) ], range: NSRange(range, in: text)) return string } } // MARK: - Eateries View Controller Delegate extension CampusEateriesViewController: EateriesViewControllerDelegate { func eateriesViewController(_ evc: EateriesViewController, didSelectEatery eatery: Eatery) { guard let campusEatery = eatery as? CampusEatery else { return } showMenu(of: campusEatery, animated: true) } func eateriesViewControllerDidPressRetryButton(_ evc: EateriesViewController) { updateState(.loading, animated: true) // Delay the reload to give the impression that the app is querying Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in self.queryCampusEateries() } } func eateriesViewControllerDidPushMapViewController(_ evc: EateriesViewController) { guard let eateries = allEateries else { return } let mapViewController = MapViewController(eateries: eateries) navigationController?.pushViewController(mapViewController, animated: true) } func eateriesViewControllerDidRefreshEateries(_ evc: EateriesViewController) { updateState(.loading, animated: true) Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { _ in self.queryCampusEateries() } } }
mit
2637012533d8d486490ff659f70e5e02
32.564748
126
0.61226
5.076714
false
false
false
false
tise/SwipeableViewController
SwipeableViewController/Source/SwipeableViewController.swift
1
17586
// // ViewController.swift // SwipingViewController // // Created by Oscar Apeland on 11.10.2017. // Copyright © 2017 Tise. All rights reserved. // import UIKit enum PanDirection { case rightToLeft, leftToRight static func directionFor(velocity: CGPoint) -> PanDirection { return velocity.x < 0 ? .rightToLeft : leftToRight } } open class SwipeableViewController: UIViewController { // MARK: Swipeable properties open var swipeableItems: [SwipeableItem] = [] open var selectedIndex: Int! // MARK: UI properties private lazy var panGestureRecognizer: UIPanGestureRecognizer = { $0.delegate = self return $0 }(UIPanGestureRecognizer(target: self, action: #selector(viewPanned(_:)))) private var navigationBar: SwipeableNavigationBar! { return navigationController!.navigationBar as! SwipeableNavigationBar } var collectionView: SwipeableCollectionView? { if #available(iOS 11, *) { return navigationBar.collectionView } else { return swipeableCollectionView } } lazy var swipeableCollectionView: SwipeableCollectionView = { return SwipeableCollectionView(frame: CGRect(x: 0, y: 64.0, width: self.view.bounds.width, height: 52.0), collectionViewLayout: SwipeableCollectionViewFlowLayout()) }() // MARK: Life cycle override open func viewDidLoad() { super.viewDidLoad() // Safeguards guard !swipeableItems.isEmpty else { fatalError("swipableItems is empty.") } guard 0...swipeableItems.count ~= selectedIndex else { fatalError("startIndex out of range.") } // Setup - Custom transitions let initialItem = swipeableItems[selectedIndex] view.addGestureRecognizer(panGestureRecognizer) // Setup - Navigation bar navigationItem.title = initialItem.title if #available(iOS 11.0, *) { navigationItem.largeTitleDisplayMode = .always } // Setup - View view.backgroundColor = .white // On iOS <11 we add the collectionView underneath the navigation bar instead of inside. // Negative OS check currently impossible if #available(iOS 11, *) {} else { swipeableCollectionView.translatesAutoresizingMaskIntoConstraints = false automaticallyAdjustsScrollViewInsets = false view.addSubview(swipeableCollectionView) NSLayoutConstraint.activate([collectionView!.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 64.0), collectionView!.heightAnchor.constraint(equalToConstant: 52.1), collectionView!.trailingAnchor.constraint(equalTo: view.trailingAnchor), collectionView!.leadingAnchor.constraint(equalTo: view.leadingAnchor)]) } add(childViewController: initialItem.viewController) } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if #available(iOS 11, *) { if let titleView = navigationBar.largeTitleView, titleView.subviews.filter ({ $0 is UICollectionView }).isEmpty { navigationBar.largeTitleView!.addSubview(navigationBar.collectionView) } } collectionView?.controller = self } // MARK: Convenience /// Convenience methods for swapping out two child view controllers without animation. private func switchChildViewController(from fromVc: UIViewController, to toVc: UIViewController) { remove(childViewController: fromVc) add(childViewController: toVc) } private func remove(childViewController: UIViewController) { childViewController.willMove(toParentViewController: nil) childViewController.view.removeFromSuperview() childViewController.removeFromParentViewController() } /** Do all the required UIKit calls for adding a child view controller. - parameter childViewController: The controller to add. - returns: The view of the added view controller. */ @discardableResult private func add(childViewController: UIViewController) -> UIView { childViewController.willMove(toParentViewController: self) addChildViewController(childViewController) view.addSubview(childViewController.view) childViewController.didMove(toParentViewController: self) if #available(iOS 11, *) {} else { childViewController.view.translatesAutoresizingMaskIntoConstraints = false childViewController.view.setContentCompressionResistancePriority(.defaultLow, for: .vertical) NSLayoutConstraint.activate([childViewController.view.topAnchor.constraint(equalTo: collectionView!.bottomAnchor), childViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), childViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), childViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor)]) } return childViewController.view } /// The view controller after the current child view controller, if there is any. func nextViewController() -> UIViewController? { let nextIndex = selectedIndex + 1 return swipeableItems.indices.contains(nextIndex) ? swipeableItems[nextIndex].viewController : nil } /// The view controller before the current child view controller, if there is any. func previousViewController() -> UIViewController? { let previousIndex = selectedIndex - 1 return swipeableItems.indices.contains(previousIndex) ? swipeableItems[previousIndex].viewController : nil } // MARK: Animation private var startPoint: CGPoint? private var startDirection: PanDirection? private var animationProgress: CGFloat = 0.0 private weak var animatingViewController: UIViewController? private var didForceCancel = false @objc func viewPanned(_ gesture: UIPanGestureRecognizer) { let velocity = gesture.velocity(in: gesture.view) let direction = PanDirection.directionFor(velocity: velocity) // Animate switch gesture.state { case .began: // If there's nothing to show, cancel the gesture guard let viewController = (direction == .rightToLeft) ? nextViewController() : previousViewController() else { didForceCancel = true gesture.isEnabled = false; gesture.isEnabled = true return } // Add the view offscreen add(childViewController: viewController) // Keep for animation startPoint = gesture.location(in: view!) startDirection = direction animatingViewController = viewController // Render the layer offscreen switch startDirection! { case .leftToRight: viewController.view.transform = CGAffineTransform(translationX: -view.bounds.width, y: 0) case .rightToLeft: viewController.view.transform = CGAffineTransform(translationX: view.bounds.width, y: 0) } case .changed: let location = gesture.location(in: view!) let relativeLocation = location.x - startPoint!.x // If we have swiped beyond the initial touch point, cancel the animation. // Switching isEnabled calls .cancelled which resets the transition before it calls .began which will restart it in the other direction if (location.x > startPoint!.x && startDirection! == .rightToLeft) || (location.x < startPoint!.x && startDirection! == .leftToRight) { self.endAnimation() gesture.isEnabled = false; gesture.isEnabled = true return } switch startDirection! { case .leftToRight: animatingViewController!.view.transform = CGAffineTransform(translationX: relativeLocation - view.frame.width, y: 0) swipeableItems[selectedIndex].viewController.view.transform = CGAffineTransform(translationX: relativeLocation, y: 0) case .rightToLeft: animatingViewController!.view.transform = CGAffineTransform(translationX: relativeLocation + view.frame.width, y: 0) swipeableItems[selectedIndex].viewController.view.transform = CGAffineTransform(translationX: relativeLocation, y: 0) } case .ended, .cancelled: // If we cancel the gesture in .began, return because all ivars are nil and there's nothing to cancel. guard !didForceCancel else { didForceCancel = false return } guard let startPoint = startPoint, let startDirection = startDirection, let animatingViewController = animatingViewController else { return } let location = gesture.location(in: view!) let relativeLocation = location.x - startPoint.x let completionTreshold: CGFloat = 0.7 let velocityTreshold: CGFloat = 1000.0 var isDone = false var swipeDistance: CGFloat = 0.0 // Decide if we are done switch startDirection { case .leftToRight: swipeDistance = view.frame.width - startPoint.x let progress = relativeLocation / swipeDistance // 0...1, not 1...100 isDone = progress > completionTreshold || velocity.x > velocityTreshold case .rightToLeft: swipeDistance = startPoint.x let progress = relativeLocation / swipeDistance isDone = fabs(progress) > completionTreshold || velocity.x < -velocityTreshold } // Complete animation and clean up if isDone { // Complete the animation UIView.animate(withDuration: 0.25, delay: 0.0, options: [.curveEaseOut, .beginFromCurrentState, .allowAnimatedContent], animations: { animatingViewController.view.transform = .identity let previousView = self.swipeableItems[self.selectedIndex].viewController.view! let translationX = (self.startDirection == .leftToRight) ? previousView.frame.width : -previousView.frame.width previousView.transform = CGAffineTransform(translationX: translationX, y: 0) }, completion: { (isFinished) in self.remove(childViewController: self.swipeableItems[self.selectedIndex].viewController) self.endAnimation() let nextIndex = self.selectedIndex + (direction == .leftToRight ? -1 : +1) let previousIndexPath = IndexPath(item: self.selectedIndex, section: 0) let nextIndexPath = IndexPath(item: nextIndex, section: 0) (self.collectionView?.cellForItem(at: previousIndexPath) as? SwipeableCell)?.label.textColor = #colorLiteral(red: 0.1490196078, green: 0.1490196078, blue: 0.1490196078, alpha: 0.5) (self.collectionView?.cellForItem(at: nextIndexPath) as? SwipeableCell)?.label.textColor = #colorLiteral(red: 0.9098039216, green: 0.4156862745, blue: 0.3764705882, alpha: 1) self.selectedIndex = nextIndex self.navigationItem.title = self.swipeableItems[self.selectedIndex].title self.collectionView!.selectItem(at: IndexPath(item: self.selectedIndex, section: 0), animated: true, scrollPosition: .centeredHorizontally) }) } else { //Cancel the animation UIView.animate(withDuration: 0.25, delay: 0.0, options: [.curveEaseOut, .beginFromCurrentState, .allowAnimatedContent], animations: { self.swipeableItems[self.selectedIndex].viewController.view!.transform = .identity let previousView = self.animatingViewController!.view! let translationX = (self.startDirection! == .leftToRight) ? -previousView.frame.width : previousView.frame.width previousView.transform = CGAffineTransform(translationX: translationX, y: 0) }, completion: { (isFinished) in self.remove(childViewController: self.animatingViewController!) self.endAnimation() }) } default: break } } private func endAnimation() { startPoint = nil startDirection = nil animationProgress = 0 } open func swipeTo(index nextIndex: Int) { guard swipeableItems.indices.contains(nextIndex) else { return } let direction: PanDirection = nextIndex > selectedIndex ? .leftToRight : .rightToLeft let lowerBound = min(selectedIndex, nextIndex) let upperBound = max(selectedIndex, nextIndex) var viewControllers = swipeableItems[lowerBound...upperBound].map { $0.viewController } if direction == .rightToLeft { viewControllers.reverse() } for (index, viewController) in viewControllers.enumerated() { self.add(childViewController: viewController) let offsetX: CGFloat = (direction == .leftToRight) ? viewController.view.frame.width : -viewController.view.frame.width viewController.view.transform = CGAffineTransform(translationX: CGFloat(index) * offsetX, y: 0) } UIView.animate(withDuration: 0.25, delay: 0.0, options: [.curveEaseOut, .beginFromCurrentState, .allowAnimatedContent], animations: { for (reversedIndex, viewController) in viewControllers.reversed().enumerated() { let offsetX: CGFloat = (direction == .leftToRight) ? -viewController.view.frame.width : viewController.view.frame.width viewController.view.transform = CGAffineTransform(translationX: CGFloat(reversedIndex) * offsetX, y: 0) } }) { (isFinished) in viewControllers.dropLast().forEach(self.remove) let previousIndexPath = IndexPath(item: self.selectedIndex, section: 0) let nextIndexPath = IndexPath(item: nextIndex, section: 0) (self.collectionView?.cellForItem(at: previousIndexPath) as? SwipeableCell)?.label.textColor = #colorLiteral(red: 0.1490196078, green: 0.1490196078, blue: 0.1490196078, alpha: 0.5) (self.collectionView?.cellForItem(at: nextIndexPath) as? SwipeableCell)?.label.textColor = #colorLiteral(red: 0.9098039216, green: 0.4156862745, blue: 0.3764705882, alpha: 1) self.selectedIndex = nextIndex self.navigationItem.title = self.swipeableItems[self.selectedIndex].title self.collectionView!.selectItem(at: IndexPath(item: self.selectedIndex, section: 0), animated: true, scrollPosition: .centeredHorizontally) } } } extension SwipeableViewController: UICollectionViewDataSource, UICollectionViewDelegate { open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return swipeableItems.count } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SwipeableCell.id, for: indexPath) as? SwipeableCell else { fatalError() } cell.label.text = swipeableItems[indexPath.row].title cell.label.textColor = indexPath.row == selectedIndex ? #colorLiteral(red: 0.9098039216, green: 0.4156862745, blue: 0.3764705882, alpha: 1) : #colorLiteral(red: 0.1490196078, green: 0.1490196078, blue: 0.1490196078, alpha: 0.5) return cell } open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { swipeTo(index: indexPath.row) } } extension SwipeableViewController: UIGestureRecognizerDelegate { open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if let pan = gestureRecognizer as? UIPanGestureRecognizer { let velocity = pan.velocity(in: view) return fabs(velocity.x) > fabs(velocity.y) } return true } }
mit
5415d7305f165ce9c124c4da54980661
46.018717
235
0.620643
5.784539
false
false
false
false
vanshg/MacAssistant
Pods/SwiftProtobuf/Sources/SwiftProtobuf/Message.swift
2
8725
// Sources/SwiftProtobuf/Message.swift - Message support // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // /// The protocol which all generated protobuf messages implement. /// `Message` is the protocol type you should use whenever /// you need an argument or variable which holds "some message". /// /// Generated messages also implement `Hashable`, and thus `Equatable`. /// However, the protocol conformance is declared on a different protocol. /// This allows you to use `Message` as a type directly: /// /// func consume(message: Message) { ... } /// /// Instead of needing to use it as a type constraint on a generic declaration: /// /// func consume<M: Message>(message: M) { ... } /// /// If you need to convince the compiler that your message is `Hashable` so /// you can insert it into a `Set` or use it as a `Dictionary` key, use /// a generic declaration with a type constraint: /// /// func insertIntoSet<M: Message & Hashable>(message: M) { /// mySet.insert(message) /// } /// /// The actual functionality is implemented either in the generated code or in /// default implementations of the below methods and properties. public protocol Message: CustomDebugStringConvertible { /// Creates a new message with all of its fields initialized to their default /// values. init() // Metadata // Basic facts about this class and the proto message it was generated from // Used by various encoders and decoders /// The fully-scoped name of the message from the original .proto file, /// including any relevant package name. static var protoMessageName: String { get } /// True if all required fields (if any) on this message and any nested /// messages (recursively) have values set; otherwise, false. var isInitialized: Bool { get } /// Some formats include enough information to transport fields that were /// not known at generation time. When encountered, they are stored here. var unknownFields: UnknownStorage { get set } // // General serialization/deserialization machinery // /// Decode all of the fields from the given decoder. /// /// This is a simple loop that repeatedly gets the next field number /// from `decoder.nextFieldNumber()` and then uses the number returned /// and the type information from the original .proto file to decide /// what type of data should be decoded for that field. The corresponding /// method on the decoder is then called to get the field value. /// /// This is the core method used by the deserialization machinery. It is /// `public` to enable users to implement their own encoding formats by /// conforming to `Decoder`; it should not be called otherwise. /// /// Note that this is not specific to binary encodng; formats that use /// textual identifiers translate those to field numbers and also go /// through this to decode messages. /// /// - Parameters: /// - decoder: a `Decoder`; the `Message` will call the method /// corresponding to the type of this field. /// - Throws: an error on failure or type mismatch. The type of error /// thrown depends on which decoder is used. mutating func decodeMessage<D: Decoder>(decoder: inout D) throws /// Traverses the fields of the message, calling the appropriate methods /// of the passed `Visitor` object. /// /// This is used internally by: /// /// * Protobuf binary serialization /// * JSON serialization (with some twists to account for specialty JSON) /// * Protobuf Text serialization /// * `Hashable` computation /// /// Conceptually, serializers create visitor objects that are /// then passed recursively to every message and field via generated /// `traverse` methods. The details get a little involved due to /// the need to allow particular messages to override particular /// behaviors for specific encodings, but the general idea is quite simple. func traverse<V: Visitor>(visitor: inout V) throws // Standard utility properties and methods. // Most of these are simple wrappers on top of the visitor machinery. // They are implemented in the protocol, not in the generated structs, // so can be overridden in user code by defining custom extensions to // the generated struct. #if swift(>=4.2) /// An implementation of hash(into:) to provide conformance with the /// `Hashable` protocol. func hash(into hasher: inout Hasher) #else // swift(>=4.2) /// The hash value generated from this message's contents, for conformance /// with the `Hashable` protocol. var hashValue: Int { get } #endif // swift(>=4.2) /// Helper to compare `Message`s when not having a specific type to use /// normal `Equatable`. `Equatable` is provided with specific generated /// types. func isEqualTo(message: Message) -> Bool } public extension Message { /// Generated proto2 messages that contain required fields, nested messages /// that contain required fields, and/or extensions will provide their own /// implementation of this property that tests that all required fields are /// set. Users of the generated code SHOULD NOT override this property. var isInitialized: Bool { // The generated code will include a specialization as needed. return true } /// A hash based on the message's full contents. #if swift(>=4.2) func hash(into hasher: inout Hasher) { var visitor = HashVisitor(hasher) try? traverse(visitor: &visitor) hasher = visitor.hasher } #else // swift(>=4.2) var hashValue: Int { var visitor = HashVisitor() try? traverse(visitor: &visitor) return visitor.hashValue } #endif // swift(>=4.2) /// A description generated by recursively visiting all fields in the message, /// including messages. var debugDescription: String { // TODO Ideally there would be something like serializeText() that can // take a prefix so we could do something like: // [class name]( // [text format] // ) let className = String(reflecting: type(of: self)) let header = "\(className):\n" return header + textFormatString() } /// Creates an instance of the message type on which this method is called, /// executes the given block passing the message in as its sole `inout` /// argument, and then returns the message. /// /// This method acts essentially as a "builder" in that the initialization of /// the message is captured within the block, allowing the returned value to /// be set in an immutable variable. For example, /// /// let msg = MyMessage.with { $0.myField = "foo" } /// msg.myOtherField = 5 // error: msg is immutable /// /// - Parameter populator: A block or function that populates the new message, /// which is passed into the block as an `inout` argument. /// - Returns: The message after execution of the block. public static func with( _ populator: (inout Self) throws -> () ) rethrows -> Self { var message = Self() try populator(&message) return message } } /// Implementation base for all messages; not intended for client use. /// /// In general, use `SwiftProtobuf.Message` instead when you need a variable or /// argument that can hold any type of message. Occasionally, you can use /// `SwiftProtobuf.Message & Equatable` or `SwiftProtobuf.Message & Hashable` as /// generic constraints if you need to write generic code that can be applied to /// multiple message types that uses equality tests, puts messages in a `Set`, /// or uses them as `Dictionary` keys. public protocol _MessageImplementationBase: Message, Hashable { // Legacy function; no longer used, but left to maintain source compatibility. func _protobuf_generated_isEqualTo(other: Self) -> Bool } public extension _MessageImplementationBase { public func isEqualTo(message: Message) -> Bool { guard let other = message as? Self else { return false } return self == other } // Legacy default implementation that is used by old generated code, current // versions of the plugin/generator provide this directly, but this is here // just to avoid breaking source compatibility. public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs._protobuf_generated_isEqualTo(other: rhs) } // Legacy function that is generated by old versions of the plugin/generator, // defaulted to keep things simple without changing the api surface. public func _protobuf_generated_isEqualTo(other: Self) -> Bool { return self == other } }
mit
5c0dc25504091daaca50d204368b25d4
39.393519
80
0.705215
4.472066
false
false
false
false
sammyd/Concurrency-VideoSeries
projects/004_Dependencies/004_ChallengeComplete/LoadAndFilter.playground/Contents.swift
1
3694
import Compressor import UIKit //: # Compressor Operation //: Continuing from the challenge in the previous video, your challenge for this video is to use an `NSOperationQueue` to decompress a collection of compressed images. //: Input and output variables let compressedFilePaths = ["01", "02", "03", "04", "05"].map { NSBundle.mainBundle().URLForResource("sample_\($0)_small", withExtension: "compressed") } var filteredImages = [UIImage]() //: `ImageDecompressionOperation` is familiar class ImageDecompressionOperation: NSOperation { var inputData: NSData? var outputImage: UIImage? override func main() { if let dependencyData = dependencies .filter({ $0 is ImageDecompressionOperationDataProvider }) .first as? ImageDecompressionOperationDataProvider where inputData == .None { inputData = dependencyData.compressedData } guard let inputData = inputData else { return } if let decompressedData = Compressor.decompressData(inputData) { outputImage = UIImage(data: decompressedData) } } } //: `DataLoadOperation` is also familiar class DataLoadOperation: ConcurrentOperation { private let url: NSURL var loadedData: NSData? init(url: NSURL) { self.url = url super.init() } override func main() { NetworkSimulator.asyncLoadDataAtURL(url) { data in self.loadedData = data self.state = .Finished } } } //: Dependency data transfer protocol ImageDecompressionOperationDataProvider { var compressedData: NSData? { get } } extension DataLoadOperation: ImageDecompressionOperationDataProvider { var compressedData: NSData? { return loadedData } } //: `TiltShiftOperation` is another familiar operation class TiltShiftOperation : NSOperation { var inputImage: UIImage? var outputImage: UIImage? override func main() { if let imageProvider = dependencies .filter({ $0 is ImageFilterDataProvider }) .first as? ImageFilterDataProvider where inputImage == .None { inputImage = imageProvider.image } guard let inputImage = inputImage else { return } let mask = topAndBottomGradient(inputImage.size) outputImage = inputImage.applyBlurWithRadius(4, maskImage: mask) } } //: Image filter input data transfer protocol ImageFilterDataProvider { var image: UIImage? { get } } extension ImageDecompressionOperation: ImageFilterDataProvider { var image: UIImage? { return outputImage } } //: Showing off with custom operators infix operator |> { associativity left precedence 160 } func |>(lhs: NSOperation, rhs: NSOperation) -> NSOperation { rhs.addDependency(lhs) return rhs } //: Create the queue with the default constructor let queue = NSOperationQueue() let appendQueue = NSOperationQueue() appendQueue.maxConcurrentOperationCount = 1 //: Create a filter operations for each of the iamges, adding a completionBlock for compressedFile in compressedFilePaths { guard let inputURL = compressedFile else { continue } let loadingOperation = DataLoadOperation(url: inputURL) let decompressionOp = ImageDecompressionOperation() let filterOperation = TiltShiftOperation() filterOperation.completionBlock = { guard let output = filterOperation.outputImage else { return } appendQueue.addOperationWithBlock { filteredImages.append(output) } } loadingOperation |> decompressionOp |> filterOperation queue.addOperations([loadingOperation, decompressionOp, filterOperation], waitUntilFinished: false) } //: Need to wait for the queue to finish before checking the results queue.waitUntilAllOperationsAreFinished() //: Inspect the filtered images filteredImages
mit
4addf34a2c0379a9c6ccd41536a286a4
27.859375
167
0.737953
4.835079
false
false
false
false
zvonler/PasswordElephant
external/github.com/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift
8
1919
// // AEAD.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // // https://www.iana.org/assignments/aead-parameters/aead-parameters.xhtml /// Authenticated Encryption with Associated Data (AEAD) public protocol AEAD { static var kLen: Int { get } // key length static var ivRange: Range<Int> { get } // nonce length } extension AEAD { static func calculateAuthenticationTag(authenticator: Authenticator, cipherText: Array<UInt8>, authenticationHeader: Array<UInt8>) throws -> Array<UInt8> { let headerPadding = ((16 - (authenticationHeader.count & 0xf)) & 0xf) let cipherPadding = ((16 - (cipherText.count & 0xf)) & 0xf) var mac = authenticationHeader mac += Array<UInt8>(repeating: 0, count: headerPadding) mac += cipherText mac += Array<UInt8>(repeating: 0, count: cipherPadding) mac += UInt64(bigEndian: UInt64(authenticationHeader.count)).bytes() mac += UInt64(bigEndian: UInt64(cipherText.count)).bytes() return try authenticator.authenticate(mac) } }
gpl-3.0
10168666c4541618d67d5de650bd880d
46.95
217
0.721585
4.215385
false
false
false
false
xlexi/Textual-Inline-Media
Textual Inline Media/PreferencesTableView.swift
1
2903
/* Copyright (c) 2015, Alex S. Glomsaas All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation class PreferencesTableView: NSViewController, NSTableViewDataSource, NSTableViewDelegate { @IBOutlet var tableView: NSTableView? override func viewDidLoad() { super.viewDidLoad() self.tableView?.selectRowIndexes(NSIndexSet(index: 0), byExtendingSelection: false) } func numberOfRowsInTableView(tableView: NSTableView) -> Int { return InlineMedia.mediaHandlers.count } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { var result = tableView.makeViewWithIdentifier("mediahandler", owner: self) as? NSTableCellView if result == nil { result = NSTableCellView(frame: NSRect(x: 0, y: 0, width: 170, height: 20)) result?.identifier = "mediahandler" } guard let mediaHandler = InlineMedia.mediaHandlers[row] as? InlineMediaHandler.Type else { return nil } result?.objectValue = mediaHandler result?.textField?.stringValue = mediaHandler.name() result?.imageView?.image = mediaHandler.icon?() return result } func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 20.0 } }
bsd-3-clause
b4b57f2d7a42edcaccc2010f3f6cdf12
42.984848
113
0.709955
5.326606
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/OpenTelemetrySdk/Metrics/Aggregators/LastValueAggregator.swift
1
935
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation /// Simple aggregator that only keeps the last value. public class LastValueAggregator<T: SignedNumeric>: Aggregator<T> { var value: T = 0 var pointCheck: T = 0 private let lock = Lock() public override func update(value: T) { lock.withLockVoid { self.value = value } } public override func checkpoint() { lock.withLockVoid { super.checkpoint() self.pointCheck = self.value } } public override func toMetricData() -> MetricData { return SumData<T>(startTimestamp: lastStart, timestamp: lastEnd, sum: pointCheck) } public override func getAggregationType() -> AggregationType { if T.self == Double.Type.self { return .doubleSum } else { return .intSum } } }
apache-2.0
027f06104f7752cfd74bdd1efa917eb9
22.974359
89
0.606417
4.348837
false
false
false
false
space150/spaceLock
ios/spacelab WatchKit Extension/InterfaceController.swift
3
6370
// // InterfaceController.swift // spacelab WatchKit Extension // // Created by Shawn Roske on 3/25/15. // Copyright (c) 2015 space150, Inc. // // 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 WatchKit import Foundation import LockKit class InterfaceController: WKInterfaceController, NSFetchedResultsControllerDelegate { @IBOutlet weak var table: WKInterfaceTable! private var discoveryManager: LKLockDiscoveryManager! private var fetchedResultsController : NSFetchedResultsController! private var security: LKSecurityManager! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) discoveryManager = LKLockDiscoveryManager(context: "watchkit-ext") security = LKSecurityManager() fetchedResultsController = getFetchedResultsController() fetchedResultsController.delegate = self fetchedResultsController.performFetch(nil) configureTableWithLocks() } func configureTableWithLocks() { var count: Int! = fetchedResultsController.fetchedObjects?.count table.setNumberOfRows(count, withRowType: "lockRowController") if ( count > 0 ) { for i in 0...(count-1) { configureTableRow(i) } } } func configureTableRow(index: Int!) { var row = table.rowControllerAtIndex(index) as! SLLockRowType var objects: NSArray = fetchedResultsController.fetchedObjects! var lock: LKLock = objects.objectAtIndex(index) as! LKLock row.setLock(lock) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() discoveryManager.startDiscovery() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() discoveryManager.stopDiscovery() } // MARK: - NSFetchedResultsController methods func getFetchedResultsController() -> NSFetchedResultsController { let fetchedResultsController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: LKLockRepository.sharedInstance().managedObjectContext!!, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultsController } func taskFetchRequest() -> NSFetchRequest { let fetchRequest = NSFetchRequest(entityName: "LKLock") let sortDescriptor = NSSortDescriptor(key: "proximity", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] return fetchRequest } func controllerWillChangeContent(controller: NSFetchedResultsController) { // nothing } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: table.insertRowsAtIndexes(NSIndexSet(index: newIndexPath!.row), withRowType: "lockRowController") configureTableRow(newIndexPath!.row) case .Update: configureTableRow(indexPath!.row) case .Move: table.removeRowsAtIndexes(NSIndexSet(index: indexPath!.row)) table.insertRowsAtIndexes(NSIndexSet(index: newIndexPath!.row), withRowType: "lockRowController") configureTableRow(newIndexPath!.row) case .Delete: table.removeRowsAtIndexes(NSIndexSet(index: indexPath!.row)) default: return } } func controllerDidChangeContent(controller: NSFetchedResultsController) { // nothing } override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) { var objects: NSArray = fetchedResultsController.fetchedObjects! var lock: LKLock = objects.objectAtIndex(rowIndex) as! LKLock var row = table.rowControllerAtIndex(rowIndex) as! SLLockRowType if ( row.unlockable == true ) { row.showInProgress() var keyData = security.findKey(lock.lockId) if keyData != nil { self.discoveryManager.openLock(lock, withKey:keyData, complete: { (success, error) -> Void in if ( success ) { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) row.showUnlocked() } else { println("Error opening lock: \(error.localizedDescription)") row.resetUnlocked() self.presentControllerWithName("Error", context: ["segue": "modal", "data": error]) } }) } else { println("error: unable to find key") row.resetUnlocked() } } } }
mit
d5ccae9135149489cf4e969bef03d34d
34.988701
220
0.636578
5.692583
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Apps/Parking/model/Registration/ParkingCompletePaymentWrapper.swift
2
705
// // ParkingCompletePaymentWrapper.swift // byuSuite // // Created by Erik Brady on 12/5/17. // Copyright © 2017 Brigham Young University. All rights reserved. // class ParkingCompletePaymentWrapper { var paymentType: AccountType? var paymentTypeId: String? init(paymentType: AccountType, paymentTypeId: String) { self.paymentType = paymentType self.paymentTypeId = paymentTypeId } func toDictionary() -> [String: Any] { var dict = [String: Any]() if let paymentType = paymentType { dict["paymentType"] = paymentType == .bankAccount ? "BANK_ACCOUNT" : "CREDIT_CARD" } if let paymentTypeId = paymentTypeId { dict["paymentTypeId"] = paymentTypeId } return dict } }
apache-2.0
06d9ed8efc7d8af8975f434df82b1d63
22.466667
85
0.707386
3.705263
false
false
false
false
machelix/DSFacebookImagePicker
Source/AlbumCell.swift
2
906
// // AlbumCell.swift // DSFacebookImagePicker // // Created by Home on 2014-10-14. // Copyright (c) 2014 Sanche. All rights reserved. // import UIKit class AlbumCell: UITableViewCell { @IBOutlet weak var coverImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! override func prepareForReuse() { coverImageView?.image = UIImage(named:"albumPlaceholder") } func setUpWithAlbum(album:PhotoAlbum){ titleLabel?.text = album.name setImage(album) } private func setImage(album:PhotoAlbum){ if let foundPhoto = album.coverPhoto{ coverImageView?.image = foundPhoto } else if !album.imageLoadFailed { let delay = 0.1 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { () in self.setImage(album) }) } } }
mit
33f6ef4b0fc90fd551ebb037385be59d
21.097561
63
0.656733
3.973684
false
false
false
false
smartystreets/smartystreets-ios-sdk
samples/Sources/swiftExamples/InternationalAutocompleteExample.swift
1
1933
import Foundation import SmartyStreets class InternationalAutocompleteExample { func run() -> String { let id = "ID" let hostname = "Hostname" // The appropriate license values to be used for your subscriptions // can be found on the Subscriptions page of the account dashboard. // https://www.smartystreets.com/docs/cloud/licensing let client = ClientBuilder(id: id, hostname: hostname).withLicenses(licenses: ["international-autocomplete-cloud"]).buildInternationalAutocompleteApiClient() // Documentation for input fields can be found at: // https://smartystreets.com/docs/cloud/international-address-autocomplete-api#http-input-fields var lookup = InternationalAutocompleteLookup() lookup.country = "FRA" lookup.locality = "Paris" lookup.search = "Louis" var error: NSError! = nil _ = client.sendLookup(lookup: &lookup, error:&error) if let error = error { let output = """ Domain: \(error.domain) Error Code: \(error.code) Description:\n\(error.userInfo[NSLocalizedDescriptionKey] as! NSString) """ NSLog(output) return output } let results:InternationalAutocompleteResult = lookup.result ?? InternationalAutocompleteResult(dictionary: NSDictionary()) let candidates:[InternationalAutocompleteCandidate] = results.candidates ?? [] var output = "Results:\n" if candidates.count == 0 { return "Error. Address is not valid" } for candidate in candidates { output.append("\(candidate.street ?? "") \(candidate.locality ?? "") \(candidate.administrativeArea ?? ""), \(candidate.countryISO3 ?? "")") } return output } }
apache-2.0
2c55f158a3d7d1cb3cd839e57128e9ed
39.270833
165
0.600621
5.182306
false
false
false
false
apple/swift
test/Concurrency/task_local.swift
9
1067
// RUN: %target-typecheck-verify-swift -disable-availability-checking // REQUIRES: concurrency @available(SwiftStdlib 5.1, *) struct TL { @TaskLocal static var number: Int = 0 @TaskLocal static var someNil: Int? @TaskLocal static var noValue: Int // expected-error{{'static var' declaration requires an initializer expression or an explicitly stated getter}} // expected-note@-1{{add an initializer to silence this error}} @TaskLocal var notStatic: String? // expected-error{{property 'notStatic', must be static because property wrapper 'TaskLocal<String?>' can only be applied to static properties}} } @TaskLocal // expected-error{{property wrappers are not yet supported in top-level code}} var global: Int = 0 class NotSendable {} @available(SwiftStdlib 5.1, *) func test () async { TL.number = 10 // expected-error{{cannot assign to property: 'number' is a get-only property}} TL.$number = 10 // expected-error{{cannot assign value of type 'Int' to type 'TaskLocal<Int>'}} let _: Int = TL.number let _: Int = TL.$number.get() }
apache-2.0
5f692b43811dde4adcce0e1c6c96bab1
33.419355
169
0.718838
3.966543
false
false
false
false
xu6148152/binea_project_for_ios
StarWarsDemo/StarWarsDemo/StarWars/StarWarsUIDynamicAnimator/StarWarsUIDynamicAnimator.swift
1
3303
// // StarWarsUIDynamicAnimator.swift // StarWarsDemo // // Created by Binea Xu on 11/6/15. // Copyright © 2015 Binea Xu. All rights reserved. // import UIKit public class StarWarsUIDynamicAnimator: NSObject, UIViewControllerAnimatedTransitioning { public var duration: NSTimeInterval = 2 public var spriteWidth: CGFloat = 20 var transitionContext: UIViewControllerContextTransitioning! // This is used for percent driven interactive transitions, as well as for container controllers that have companion animations that might need to // synchronize with the main animation. public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return self.duration } var animator: UIDynamicAnimator! // This method can only be a nop if the transition is interactive and not a percentDriven interactive transition. public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView()! let fromView = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!.view let toView = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!.view container.addSubview(toView) container.sendSubviewToBack(toView) var snapshots: [UIView] = []; let size = fromView.frame.size func randomFloatBetween(smallNumber: CGFloat, and bigNumber: CGFloat) -> CGFloat { let diff = bigNumber - smallNumber return CGFloat(arc4random()) / 100.0 % diff + smallNumber } let fromViewSnapshot = fromView.snapshotViewAfterScreenUpdates(false) let width = spriteWidth let height = width animator = UIDynamicAnimator(referenceView: container) for x in CGFloat(0).stride(through: size.width, by: width) { for y in CGFloat(0).stride(through: size.height, by: size.height) { let snapshotRegion = CGRect(x: x, y: y, width: width, height: height) let snapshot = fromViewSnapshot.resizableSnapshotViewFromRect(snapshotRegion, afterScreenUpdates: false, withCapInsets: UIEdgeInsetsZero) container.addSubview(snapshot) snapshot.frame = snapshotRegion snapshots.append(snapshot) let push = UIPushBehavior(items: [snapshot], mode: .Instantaneous) push.pushDirection = CGVector(dx: randomFloatBetween(-0.15, and: 0.15), dy: randomFloatBetween(-0.15, and: 0)) push.active = true animator.addBehavior(push) } } let gravity = UIGravityBehavior(items: snapshots) animator.addBehavior(gravity) fromView.removeFromSuperview() NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: "completeTransition", userInfo: nil, repeats: false) self.transitionContext = transitionContext } func completeTransition() { self.transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } }
mit
3876857e6f9c49aed261ac0a74438a56
41.333333
153
0.672017
5.833922
false
false
false
false
russellbstephens/VolumeOverlay
VolumeOverlay/VolumeOverlay.swift
1
4350
// Copyright © 2017 russellbstephens. All rights reserved. import UIKit import MediaPlayer public class VolumeOverlay { public static var shared = VolumeOverlay() private let volumeWindow: UIWindow private static let statusBarHeight: CGFloat = 20.0 private var overlay: VolumeOverlayView? private var overlayTopConstraint: NSLayoutConstraint? private var displayTimer: Timer? public var backgroundColor: UIColor = .white { didSet { overlay?.backgroundColor = backgroundColor } } public var trackTintColor: UIColor = .gray { didSet { overlay?.volumeProgress.trackTintColor = trackTintColor } } public var progressTintColor: UIColor = .black { didSet { overlay?.volumeProgress.progressTintColor = progressTintColor } } init() { volumeWindow = UIWindow(frame: .zero) volumeWindow.windowLevel = UIWindowLevelStatusBar volumeWindow.rootViewController = VolumeOverlayController() let volumeView = MPVolumeView(frame: .zero) volumeView.alpha = 0.01 volumeView.showsRouteButton = false volumeView.isUserInteractionEnabled = false UIApplication.shared.windows.first?.addSubview(volumeView) NotificationCenter.default.addObserver(self, selector: #selector(VolumeOverlay.volumeChanged(_:)), name: NSNotification.Name(rawValue: AVSystemControllerNotifications.systemVolumeDidChangeNotification), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(VolumeOverlay.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc func volumeChanged(_ notification: Notification) { if let volume = notification.userInfo?[AVSystemControllerNotifications.audioVolumeNotificationParameter] as? Float { overlay?.volumeProgress.progress = volume show() } } public func load(style: Style = .full) { let overlay = VolumeOverlayView(style: style) overlay.backgroundColor = backgroundColor overlay.volumeProgress.trackTintColor = trackTintColor overlay.volumeProgress.progressTintColor = progressTintColor overlay.translatesAutoresizingMaskIntoConstraints = false self.overlay = overlay volumeWindow.addSubview(overlay) let overlayLeftConstraint = NSLayoutConstraint(item: overlay, attribute: .left, relatedBy: .equal, toItem: volumeWindow, attribute: .left, multiplier: 1, constant: 0) let overlayRightConstraint = NSLayoutConstraint(item: overlay, attribute: .right, relatedBy: .equal, toItem: volumeWindow, attribute: .right, multiplier: 1, constant: 0) let overlayTopConstraint = NSLayoutConstraint(item: overlay, attribute: .top, relatedBy: .equal, toItem: volumeWindow, attribute: .top, multiplier: 1, constant: 0) self.overlayTopConstraint = overlayTopConstraint NSLayoutConstraint.activate([overlayLeftConstraint, overlayRightConstraint, overlayTopConstraint]) } func show() { displayTimer?.invalidate() displayTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(VolumeOverlay.hide), userInfo: nil, repeats: false) volumeWindow.isHidden = false volumeWindow.makeKeyAndVisible() volumeWindow.layer.removeAllAnimations() overlayTopConstraint?.constant = VolumeOverlay.statusBarHeight UIView.animate(withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.volumeWindow.layoutIfNeeded() }) } @objc func hide() { volumeWindow.layer.removeAllAnimations() overlayTopConstraint?.constant = 0 UIView.animate(withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.volumeWindow.layoutIfNeeded() }, completion: { [weak self] _ in self?.volumeWindow.isHidden = true }) } @objc func rotated() { var frame = UIScreen.main.bounds frame.origin.y -= VolumeOverlay.statusBarHeight volumeWindow.frame = frame } }
mit
9041ba4f6e89e4109e50bb84c8e4848d
41.637255
223
0.693033
5.323133
false
false
false
false
lwg123/swift_LWGWB
LWGWB/LWGWB/classes/Compose/PicPicker/PicPickerViewCell.swift
1
1354
// // PicPickerViewCell.swift // LWGWB // // Created by weiguang on 2017/5/4. // Copyright © 2017年 weiguang. All rights reserved. // import UIKit class PicPickerViewCell: UICollectionViewCell { @IBOutlet weak var addPhoneBtn: UIButton! @IBOutlet weak var removePhoneBtn: UIButton! @IBOutlet weak var imageView: UIImageView! // 监听外界传过来的image值 var image: UIImage? { didSet { if image != nil { // 直接在cell的image上设置图片 imageView.image = image // 展示图片时,不让button点击 addPhoneBtn.isUserInteractionEnabled = false // 展示删除按钮 removePhoneBtn.isHidden = false }else { // 防止循环利用 imageView.image = nil addPhoneBtn.isUserInteractionEnabled = true removePhoneBtn.isHidden = true } } } @IBAction func addPictureClick() { NotificationCenter.default.post(name: NSNotification.Name(rawValue: addPicNotification), object: nil) } @IBAction func removePictureClick() { NotificationCenter.default.post(name: NSNotification.Name(rawValue: removePicNotification), object: imageView.image) } }
mit
168b39c852d5f2d623f6fc03b244a0a7
26.630435
124
0.59402
4.672794
false
false
false
false
lorentey/swift
test/SILOptimizer/outliner.swift
3
12216
// RUN: %target-swift-frontend -Osize -import-objc-header %S/Inputs/Outliner.h %s -emit-sil -enforce-exclusivity=unchecked | %FileCheck %s // RUN: %target-swift-frontend -Osize -g -import-objc-header %S/Inputs/Outliner.h %s -emit-sil -enforce-exclusivity=unchecked | %FileCheck %s // REQUIRES: objc_interop import Foundation public class MyGizmo { private var gizmo : Gizmo private var optionalGizmo : Gizmo? init() { gizmo = Gizmo() } // CHECK-LABEL: sil @$s8outliner7MyGizmoC11usePropertyyyF : // CHECK: [[A_FUN:%.*]] = function_ref @$sSo5GizmoC14stringPropertySSSgvgToTeab_ // CHECK: apply [[A_FUN]]({{.*}}) : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String> // CHECK-NOT: return // CHECK: [[P_FUN:%.*]] = function_ref @$sSo5GizmoC14stringPropertySSSgvgToTepb_ // CHECK: apply [[P_FUN]]({{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: return // CHECK: } // end sil function '$s8outliner7MyGizmoC11usePropertyyyF' public func useProperty() { print(gizmo.stringProperty) print(optionalGizmo!.stringProperty) } } // CHECK-LABEL: sil @$s8outliner13testOutliningyyF : // CHECK: [[FUN:%.*]] = function_ref @$sSo5GizmoC14stringPropertySSSgvgToTepb_ // CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: [[FUN:%.*]] = function_ref @$sSo5GizmoC14stringPropertySSSgvsToTembnn_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> () // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> () // CHECK: [[FUN:%.*]] = function_ref @$sSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> // CHECK: [[FUN:%.*]] = function_ref @$sSo5GizmoC11doSomethingyypSgSaySSGSgFToTembgnn_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@guaranteed Array<String>, Gizmo) -> @owned Optional<AnyObject> // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@guaranteed Array<String>, Gizmo) -> @owned Optional<AnyObject> // CHECK: return // CHECK: } // end sil function '$s8outliner13testOutliningyyF' public func testOutlining() { let gizmo = Gizmo() let foobar = Gizmo() print(gizmo.stringProperty) print(gizmo.stringProperty) gizmo.stringProperty = "foobar" gizmo.stringProperty = "foobar2" gizmo.modifyString("hello", withNumber:1, withFoobar: foobar) gizmo.modifyString("hello", withNumber:1, withFoobar: foobar) let arr = [ "foo", "bar"] gizmo.doSomething(arr) gizmo.doSomething(arr) } // CHECK-LABEL: sil @$s8outliner9dontCrash1ayyp_tF : $@convention(thin) (@in_guaranteed Any) -> () { // CHECK: [[OBJ:%.*]] = open_existential_ref {{.*}} : $AnyObject to $@opened("{{.*}}") (AnyObject) // CHECK: [[METH:%.*]] = objc_method [[OBJ]] : $@opened("{{.*}}") (AnyObject), #Treeish.treeishChildren!1.foreign : <Self where Self : Treeish> (Self) -> () -> [Any]? // CHECK: [[RES:%.*]] = apply [[METH]]([[OBJ]]) : $@convention(objc_method) // CHECK: switch_enum [[RES]] // CHECK: } // end sil function '$s8outliner9dontCrash1ayyp_tF' // CHECK-LABEL: sil shared [noinline] @$sSo5GizmoC14stringPropertySSSgvgToTeab_ : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String> // CHECK: bb0(%0 : $*Gizmo): // CHECK: %1 = load %0 : $*Gizmo // CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String? // CHECK: %3 = apply %2(%1) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString> // CHECK: switch_enum %3 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2 // CHECK: bb1(%5 : $NSString): // CHECK: %6 = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %7 = metatype $@thin String.Type // CHECK: %8 = apply %6(%3, %7) : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String // CHECK: release_value %3 : $Optional<NSString> // CHECK: %10 = enum $Optional<String>, #Optional.some!enumelt.1, %8 : $String // CHECK: br bb3(%10 : $Optional<String>) // CHECK: bb2: // CHECK: %12 = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb3(%12 : $Optional<String>) // CHECK: bb3(%14 : $Optional<String>): // CHECK: return %14 : $Optional<String> // CHECK: } // end sil function '$sSo5GizmoC14stringPropertySSSgvgToTeab_' // CHECK-LABEL: sil shared [noinline] @$sSo5GizmoC14stringPropertySSSgvgToTepb_ : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: bb0(%0 : $Gizmo): // CHECK: %1 = objc_method %0 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String? // CHECK: %2 = apply %1(%0) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString> // CHECK: switch_enum %2 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2 // CHECK:bb1(%4 : $NSString): // CHECK: %5 = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %6 = metatype $@thin String.Type // CHECK: %7 = apply %5(%2, %6) : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String // CHECK: release_value %2 : $Optional<NSString> // CHECK: %9 = enum $Optional<String>, #Optional.some!enumelt.1, %7 : $String // CHECK: br bb3(%9 : $Optional<String>) // CHECK:bb2: // CHECK: %11 = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb3(%11 : $Optional<String>) // CHECK:bb3(%13 : $Optional<String>): // CHECK: return %13 : $Optional<String> // CHECK: } // end sil function '$sSo5GizmoC14stringPropertySSSgvgToTepb_' // CHECK-LABEL: sil shared [noinline] @$sSo5GizmoC14stringPropertySSSgvsToTembnn_ : $@convention(thin) (@owned String, Gizmo) -> () { // CHECK: bb0(%0 : $String, %1 : $Gizmo): // CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!setter.1.foreign : (Gizmo) -> (String?) -> () // CHECK: %3 = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: %4 = apply %3(%0) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: release_value %0 : $String // CHECK: %6 = enum $Optional<NSString>, #Optional.some!enumelt.1, %4 : $NSString // CHECK: %7 = apply %2(%6, %1) : $@convention(objc_method) (Optional<NSString>, Gizmo) -> () // CHECK: strong_release %4 : $NSString // CHECK: return %7 : $() // CHECK: } // end sil function '$sSo5GizmoC14stringPropertySSSgvsToTembnn_' // CHECK-LABEL: sil shared [noinline] @$sSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_ : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> { // CHECK: bb0(%0 : $String, %1 : $Int, %2 : $Optional<AnyObject>, %3 : $Gizmo): // CHECK: %4 = objc_method %3 : $Gizmo, #Gizmo.modifyString!1.foreign : (Gizmo) -> (String?, Int, Any?) -> String? // CHECK: %5 = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: %6 = apply %5(%0) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: release_value %0 : $String // CHECK: %8 = enum $Optional<NSString>, #Optional.some!enumelt.1, %6 : $NSString // CHECK: %9 = apply %4(%8, %1, %2, %3) : $@convention(objc_method) (Optional<NSString>, Int, Optional<AnyObject>, Gizmo) -> @autoreleased Optional<NSString> // CHECK: strong_release %6 : $NSString // CHECK: switch_enum %9 : $Optional<NSString>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1 // // CHECK: bb1: // CHECK: %12 = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb3(%12 : $Optional<String>) // // CHECK: bb2(%14 : $NSString): // CHECK: %15 = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %16 = metatype $@thin String.Type // CHECK: %17 = apply %15(%9, %16) : $@convention(method) (@guaranteed Optional<NSString>, @thin String.Type) -> @owned String // CHECK: release_value %9 : $Optional<NSString> // id: %18 // CHECK: %19 = enum $Optional<String>, #Optional.some!enumelt.1, %17 : $String // CHECK: br bb3(%19 : $Optional<String>) // // CHECK: bb3(%21 : $Optional<String>): // CHECK: return %21 : $Optional<String> // CHECK: } // end sil function '$sSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_' // CHECK-LABEL: sil shared [noinline] @$sSo5GizmoC11doSomethingyypSgSaySSGSgFToTembgnn_ : $@convention(thin) (@guaranteed Array<String>, Gizmo) -> @owned Optional<AnyObject> { // CHECK: bb0(%0 : $Array<String>, %1 : $Gizmo): // CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.doSomething!1.foreign : (Gizmo) -> ([String]?) -> Any? // CHECK: %3 = function_ref @$sSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray // CHECK: %4 = apply %3<String>(%0) : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray // CHECK-NOT: release_value // CHECK: %5 = enum $Optional<NSArray>, #Optional.some!enumelt.1, %4 : $NSArray // CHECK: %6 = apply %2(%5, %1) : $@convention(objc_method) (Optional<NSArray>, Gizmo) -> @autoreleased Optional<AnyObject> // CHECK: strong_release %4 : $NSArray // CHECK: return %6 : $Optional<AnyObject> // CHECK: } // end sil function '$sSo5GizmoC11doSomethingyypSgSaySSGSgFToTembgnn_' public func dontCrash<T: Proto>(x : Gizmo2<T>) { let s = x.doSomething() print(s) } public func dontCrash2(_ c: SomeGenericClass) -> Bool { guard let str = c.version else { return false } guard let str2 = c.doSomething() else { return false } let arr = [ "foo", "bar"] c.doSomething2(arr) return true } func dontCrash3() -> String? { let bundle = Bundle.main let resource = "common parameter" return bundle.path(forResource: resource, ofType: "png") ?? bundle.path(forResource: resource, ofType: "apng") } extension Operation { func dontCrash4() { if completionBlock != nil { completionBlock = { } } } } public func dontCrash(a: Any) { (a as AnyObject).treeishChildren() } public class Foo : NSObject { var x: MyView? = nil public func dontCrash(_ pt: MyPoint) -> Bool { guard let somView = x, let window = somView.window else { return false } guard let event = MyEvent.mouseEvent(with: .A, location: pt, windowNumber: window.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure:1) else { print("failure") return false } print(event) return true } } public func testCalendar() { let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .gregorian) } open class Test { @inline(never) public func getWindow() -> MyWindow { return MyWindow() } public func testDontCrash() -> MyView { let view = MyView() view.window2 = getWindow() return view } } internal extension NSError { convenience init(myError code: Int) { self.init(domain: "error", code: code, userInfo: [:]) } } public class AnotherTest { public let obj: MyObject public init(obj: MyObject) { self.obj = obj } public func dontCrash() { self.obj.error = NSError(myError: 10) } }
apache-2.0
8abdffe60ced4c2f4da60a42bef0ec3e
46.348837
211
0.647675
3.39522
false
false
false
false
lorentey/swift
test/expr/cast/dictionary_bridge.swift
28
6464
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop // FIXME: Should go into the standard library. public extension _ObjectiveCBridgeable { static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> Self { var result: Self? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } class Root : Hashable { func hash(into hasher: inout Hasher) {} } func ==(x: Root, y: Root) -> Bool { return true } class ObjC : Root { var x = 0 } class DerivesObjC : ObjC { } struct BridgedToObjC : Hashable, _ObjectiveCBridgeable { func _bridgeToObjectiveC() -> ObjC { return ObjC() } static func _forceBridgeFromObjectiveC( _ x: ObjC, result: inout BridgedToObjC? ) { } static func _conditionallyBridgeFromObjectiveC( _ x: ObjC, result: inout BridgedToObjC? ) -> Bool { return true } func hash(into hasher: inout Hasher) {} } func ==(x: BridgedToObjC, y: BridgedToObjC) -> Bool { return true } func testUpcastBridge() { var dictRR = Dictionary<Root, Root>() var dictRO = Dictionary<Root, ObjC>() var dictOR = Dictionary<ObjC, Root>() var dictOO = Dictionary<ObjC, ObjC>() var dictOD = Dictionary<ObjC, DerivesObjC>() var dictDO = Dictionary<DerivesObjC, ObjC>() var dictDD = Dictionary<DerivesObjC, DerivesObjC>() var dictBB = Dictionary<BridgedToObjC, BridgedToObjC>() var dictBO = Dictionary<BridgedToObjC, ObjC>() var dictOB = Dictionary<ObjC, BridgedToObjC>() // Upcast to object types. dictRR = dictBB as [Root: Root] dictRR = dictBO as [Root: Root] dictRR = dictOB as [Root: Root] dictRO = dictBB as [Root: ObjC] dictRO = dictBO as [Root: ObjC] dictRO = dictOB as [Root: ObjC] dictOR = dictBB as [ObjC: Root] dictOR = dictBO as [ObjC: Root] dictOR = dictOB as [ObjC: Root] dictOO = dictBB as [ObjC: ObjC] dictOO = dictBO as [ObjC: ObjC] dictOO = dictOB as [ObjC: ObjC] // Upcast key or value to object type (but not both) dictBO = dictBB as [BridgedToObjC: ObjC] dictOB = dictBB as [ObjC: BridgedToObjC] dictBB = dictBO // expected-error{{cannot assign value of type '[BridgedToObjC : ObjC]' to type '[BridgedToObjC : BridgedToObjC]'}} // expected-note@-1 {{arguments to generic parameter 'Value' ('ObjC' and 'BridgedToObjC') are expected to be equal}} dictBB = dictOB // expected-error{{cannot assign value of type '[ObjC : BridgedToObjC]' to type '[BridgedToObjC : BridgedToObjC]'}} // expected-note@-1 {{arguments to generic parameter 'Key' ('ObjC' and 'BridgedToObjC') are expected to be equal}} dictDO = dictBB // expected-error{{cannot assign value of type '[BridgedToObjC : BridgedToObjC]' to type '[DerivesObjC : ObjC]'}} //expected-note@-1 {{arguments to generic parameter 'Key' ('BridgedToObjC' and 'DerivesObjC') are expected to be equal}} //expected-note@-2 {{arguments to generic parameter 'Value' ('BridgedToObjC' and 'ObjC') are expected to be equal}} dictOD = dictBB // expected-error {{cannot assign value of type '[BridgedToObjC : BridgedToObjC]' to type '[ObjC : DerivesObjC]'}} //expected-note@-1 {{arguments to generic parameter 'Key' ('BridgedToObjC' and 'ObjC') are expected to be equal}} //expected-note@-2 {{arguments to generic parameter 'Value' ('BridgedToObjC' and 'DerivesObjC') are expected to be equal}} dictDD = dictBB // expected-error {{cannot assign value of type '[BridgedToObjC : BridgedToObjC]' to type '[DerivesObjC : DerivesObjC]'}} //expected-note@-1 {{arguments to generic parameter 'Key' ('BridgedToObjC' and 'DerivesObjC') are expected to be equal}} //expected-note@-2 {{arguments to generic parameter 'Value' ('BridgedToObjC' and 'DerivesObjC') are expected to be equal}} _ = dictDD; _ = dictDO; _ = dictOD; _ = dictOO; _ = dictOR; _ = dictOR; _ = dictRR; _ = dictRO } func testDowncastBridge() { let dictRR = Dictionary<Root, Root>() let dictRO = Dictionary<Root, ObjC>() _ = Dictionary<ObjC, Root>() _ = Dictionary<ObjC, ObjC>() _ = Dictionary<ObjC, DerivesObjC>() let dictDO = Dictionary<DerivesObjC, ObjC>() _ = Dictionary<DerivesObjC, DerivesObjC>() _ = Dictionary<BridgedToObjC, BridgedToObjC>() let dictBO = Dictionary<BridgedToObjC, ObjC>() let dictOB = Dictionary<ObjC, BridgedToObjC>() // Downcast to bridged value types. _ = dictRR as! Dictionary<BridgedToObjC, BridgedToObjC> _ = dictRR as! Dictionary<BridgedToObjC, ObjC> _ = dictRR as! Dictionary<ObjC, BridgedToObjC> _ = dictRO as! Dictionary<BridgedToObjC, BridgedToObjC> _ = dictRO as! Dictionary<BridgedToObjC, ObjC> _ = dictRO as! Dictionary<ObjC, BridgedToObjC> _ = dictBO as Dictionary<BridgedToObjC, BridgedToObjC> _ = dictOB as Dictionary<BridgedToObjC, BridgedToObjC> // We don't do mixed down/upcasts. _ = dictDO as! Dictionary<BridgedToObjC, BridgedToObjC> // expected-warning{{forced cast from '[DerivesObjC : ObjC]' to 'Dictionary<BridgedToObjC, BridgedToObjC>' always succeeds; did you mean to use 'as'?}} } func testConditionalDowncastBridge() { let dictRR = Dictionary<Root, Root>() let dictRO = Dictionary<Root, ObjC>() let dictOR = Dictionary<ObjC, Root>() let dictOO = Dictionary<ObjC, ObjC>() let dictOD = Dictionary<ObjC, DerivesObjC>() let dictDO = Dictionary<DerivesObjC, ObjC>() let dictDD = Dictionary<DerivesObjC, DerivesObjC>() let dictBB = Dictionary<BridgedToObjC, BridgedToObjC>() let dictBO = Dictionary<BridgedToObjC, ObjC>() let dictOB = Dictionary<ObjC, BridgedToObjC>() // Downcast to bridged value types. if let d = dictRR as? Dictionary<BridgedToObjC, BridgedToObjC> { _ = d } if let d = dictRR as? Dictionary<BridgedToObjC, ObjC> { _ = d } if let d = dictRR as? Dictionary<ObjC, BridgedToObjC> { _ = d } if let d = dictRO as? Dictionary<BridgedToObjC, BridgedToObjC> { _ = d } if let d = dictRO as? Dictionary<BridgedToObjC, ObjC> { _ = d } if let d = dictRO as? Dictionary<ObjC, BridgedToObjC> { _ = d } let d1 = dictBO as Dictionary<BridgedToObjC, BridgedToObjC> let d2 = dictOB as Dictionary<BridgedToObjC, BridgedToObjC> // Mixed down/upcasts. if let d = dictDO as? Dictionary<BridgedToObjC, BridgedToObjC> { _ = d } // expected-warning@-1{{conditional cast from '[DerivesObjC : ObjC]' to 'Dictionary<BridgedToObjC, BridgedToObjC>' always succeeds}} _ = dictRR _ = dictRO _ = dictOR _ = dictOO _ = dictOD _ = dictDO _ = dictDD _ = dictBB _ = dictBO _ = dictOB _ = d1 _ = d2 }
apache-2.0
c426f273c7f316f617aaecd1c999a50f
35.937143
209
0.69245
3.782329
false
false
false
false
hooman/swift
stdlib/public/core/Policy.swift
2
17456
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Swift Standard Prolog Library. //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Standardized uninhabited type //===----------------------------------------------------------------------===// /// The return type of functions that do not return normally, that is, a type /// with no values. /// /// Use `Never` as the return type when declaring a closure, function, or /// method that unconditionally throws an error, traps, or otherwise does /// not terminate. /// /// func crashAndBurn() -> Never { /// fatalError("Something very, very bad happened") /// } @frozen public enum Never {} extension Never: Sendable { } extension Never: Error {} extension Never: Equatable, Comparable, Hashable {} @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) extension Never: Identifiable { @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) public var id: Never { switch self {} } } //===----------------------------------------------------------------------===// // Standardized aliases //===----------------------------------------------------------------------===// /// The return type of functions that don't explicitly specify a return type, /// that is, an empty tuple `()`. /// /// When declaring a function or method, you don't need to specify a return /// type if no value will be returned. However, the type of a function, /// method, or closure always includes a return type, which is `Void` if /// otherwise unspecified. /// /// Use `Void` or an empty tuple as the return type when declaring a closure, /// function, or method that doesn't return a value. /// /// // No return type declared: /// func logMessage(_ s: String) { /// print("Message: \(s)") /// } /// /// let logger: (String) -> Void = logMessage /// logger("This is a void function") /// // Prints "Message: This is a void function" public typealias Void = () //===----------------------------------------------------------------------===// // Aliases for floating point types //===----------------------------------------------------------------------===// // FIXME: it should be the other way round, Float = Float32, Double = Float64, // but the type checker loses sugar currently, and ends up displaying 'FloatXX' // in diagnostics. /// A 32-bit floating point type. public typealias Float32 = Float /// A 64-bit floating point type. public typealias Float64 = Double //===----------------------------------------------------------------------===// // Default types for unconstrained literals //===----------------------------------------------------------------------===// /// The default type for an otherwise-unconstrained integer literal. public typealias IntegerLiteralType = Int /// The default type for an otherwise-unconstrained floating point literal. public typealias FloatLiteralType = Double /// The default type for an otherwise-unconstrained Boolean literal. /// /// When you create a constant or variable using one of the Boolean literals /// `true` or `false`, the resulting type is determined by the /// `BooleanLiteralType` alias. For example: /// /// let isBool = true /// print("isBool is a '\(type(of: isBool))'") /// // Prints "isBool is a 'Bool'" /// /// The type aliased by `BooleanLiteralType` must conform to the /// `ExpressibleByBooleanLiteral` protocol. public typealias BooleanLiteralType = Bool /// The default type for an otherwise-unconstrained unicode scalar literal. public typealias UnicodeScalarType = String /// The default type for an otherwise-unconstrained Unicode extended /// grapheme cluster literal. public typealias ExtendedGraphemeClusterType = String /// The default type for an otherwise-unconstrained string literal. public typealias StringLiteralType = String //===----------------------------------------------------------------------===// // Default types for unconstrained number literals //===----------------------------------------------------------------------===// #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80 #else public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64 #endif //===----------------------------------------------------------------------===// // Standard protocols //===----------------------------------------------------------------------===// #if _runtime(_ObjC) /// The protocol to which all classes implicitly conform. /// /// You use `AnyObject` when you need the flexibility of an untyped object or /// when you use bridged Objective-C methods and properties that return an /// untyped result. `AnyObject` can be used as the concrete type for an /// instance of any class, class type, or class-only protocol. For example: /// /// class FloatRef { /// let value: Float /// init(_ value: Float) { /// self.value = value /// } /// } /// /// let x = FloatRef(2.3) /// let y: AnyObject = x /// let z: AnyObject = FloatRef.self /// /// `AnyObject` can also be used as the concrete type for an instance of a type /// that bridges to an Objective-C class. Many value types in Swift bridge to /// Objective-C counterparts, like `String` and `Int`. /// /// let s: AnyObject = "This is a bridged string." as NSString /// print(s is NSString) /// // Prints "true" /// /// let v: AnyObject = 100 as NSNumber /// print(type(of: v)) /// // Prints "__NSCFNumber" /// /// The flexible behavior of the `AnyObject` protocol is similar to /// Objective-C's `id` type. For this reason, imported Objective-C types /// frequently use `AnyObject` as the type for properties, method parameters, /// and return values. /// /// Casting AnyObject Instances to a Known Type /// =========================================== /// /// Objects with a concrete type of `AnyObject` maintain a specific dynamic /// type and can be cast to that type using one of the type-cast operators /// (`as`, `as?`, or `as!`). /// /// This example uses the conditional downcast operator (`as?`) to /// conditionally cast the `s` constant declared above to an instance of /// Swift's `String` type. /// /// if let message = s as? String { /// print("Successful cast to String: \(message)") /// } /// // Prints "Successful cast to String: This is a bridged string." /// /// If you have prior knowledge that an `AnyObject` instance has a particular /// type, you can use the unconditional downcast operator (`as!`). Performing /// an invalid cast triggers a runtime error. /// /// let message = s as! String /// print("Successful cast to String: \(message)") /// // Prints "Successful cast to String: This is a bridged string." /// /// let badCase = v as! String /// // Runtime error /// /// Casting is always safe in the context of a `switch` statement. /// /// let mixedArray: [AnyObject] = [s, v] /// for object in mixedArray { /// switch object { /// case let x as String: /// print("'\(x)' is a String") /// default: /// print("'\(object)' is not a String") /// } /// } /// // Prints "'This is a bridged string.' is a String" /// // Prints "'100' is not a String" /// /// Accessing Objective-C Methods and Properties /// ============================================ /// /// When you use `AnyObject` as a concrete type, you have at your disposal /// every `@objc` method and property---that is, methods and properties /// imported from Objective-C or marked with the `@objc` attribute. Because /// Swift can't guarantee at compile time that these methods and properties /// are actually available on an `AnyObject` instance's underlying type, these /// `@objc` symbols are available as implicitly unwrapped optional methods and /// properties, respectively. /// /// This example defines an `IntegerRef` type with an `@objc` method named /// `getIntegerValue()`. /// /// class IntegerRef { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// /// @objc func getIntegerValue() -> Int { /// return value /// } /// } /// /// func getObject() -> AnyObject { /// return IntegerRef(100) /// } /// /// let obj: AnyObject = getObject() /// /// In the example, `obj` has a static type of `AnyObject` and a dynamic type /// of `IntegerRef`. You can use optional chaining to call the `@objc` method /// `getIntegerValue()` on `obj` safely. If you're sure of the dynamic type of /// `obj`, you can call `getIntegerValue()` directly. /// /// let possibleValue = obj.getIntegerValue?() /// print(possibleValue) /// // Prints "Optional(100)" /// /// let certainValue = obj.getIntegerValue() /// print(certainValue) /// // Prints "100" /// /// If the dynamic type of `obj` doesn't implement a `getIntegerValue()` /// method, the system returns a runtime error when you initialize /// `certainValue`. /// /// Alternatively, if you need to test whether `obj.getIntegerValue()` exists, /// use optional binding before calling the method. /// /// if let f = obj.getIntegerValue { /// print("The value of 'obj' is \(f())") /// } else { /// print("'obj' does not have a 'getIntegerValue()' method") /// } /// // Prints "The value of 'obj' is 100" public typealias AnyObject = Builtin.AnyObject #else /// The protocol to which all classes implicitly conform. public typealias AnyObject = Builtin.AnyObject #endif /// The protocol to which all class types implicitly conform. /// /// You can use the `AnyClass` protocol as the concrete type for an instance of /// any class. When you do, all known `@objc` class methods and properties are /// available as implicitly unwrapped optional methods and properties, /// respectively. For example: /// /// class IntegerRef { /// @objc class func getDefaultValue() -> Int { /// return 42 /// } /// } /// /// func getDefaultValue(_ c: AnyClass) -> Int? { /// return c.getDefaultValue?() /// } /// /// The `getDefaultValue(_:)` function uses optional chaining to safely call /// the implicitly unwrapped class method on `c`. Calling the function with /// different class types shows how the `getDefaultValue()` class method is /// only conditionally available. /// /// print(getDefaultValue(IntegerRef.self)) /// // Prints "Optional(42)" /// /// print(getDefaultValue(NSString.self)) /// // Prints "nil" public typealias AnyClass = AnyObject.Type //===----------------------------------------------------------------------===// // Standard pattern matching forms //===----------------------------------------------------------------------===// /// Returns a Boolean value indicating whether two arguments match by value /// equality. /// /// The pattern-matching operator (`~=`) is used internally in `case` /// statements for pattern matching. When you match against an `Equatable` /// value in a `case` statement, this operator is called behind the scenes. /// /// let weekday = 3 /// let lunch: String /// switch weekday { /// case 3: /// lunch = "Taco Tuesday!" /// default: /// lunch = "Pizza again." /// } /// // lunch == "Taco Tuesday!" /// /// In this example, the `case 3` expression uses this pattern-matching /// operator to test whether `weekday` is equal to the value `3`. /// /// - Note: In most cases, you should use the equal-to operator (`==`) to test /// whether two instances are equal. The pattern-matching operator is /// primarily intended to enable `case` statement pattern matching. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @_transparent public func ~= <T: Equatable>(a: T, b: T) -> Bool { return a == b } //===----------------------------------------------------------------------===// // Standard precedence groups //===----------------------------------------------------------------------===// precedencegroup AssignmentPrecedence { assignment: true associativity: right } precedencegroup FunctionArrowPrecedence { associativity: right higherThan: AssignmentPrecedence } precedencegroup TernaryPrecedence { associativity: right higherThan: FunctionArrowPrecedence } precedencegroup DefaultPrecedence { higherThan: TernaryPrecedence } precedencegroup LogicalDisjunctionPrecedence { associativity: left higherThan: TernaryPrecedence } precedencegroup LogicalConjunctionPrecedence { associativity: left higherThan: LogicalDisjunctionPrecedence } precedencegroup ComparisonPrecedence { higherThan: LogicalConjunctionPrecedence } precedencegroup NilCoalescingPrecedence { associativity: right higherThan: ComparisonPrecedence } precedencegroup CastingPrecedence { higherThan: NilCoalescingPrecedence } precedencegroup RangeFormationPrecedence { higherThan: CastingPrecedence } precedencegroup AdditionPrecedence { associativity: left higherThan: RangeFormationPrecedence } precedencegroup MultiplicationPrecedence { associativity: left higherThan: AdditionPrecedence } precedencegroup BitwiseShiftPrecedence { higherThan: MultiplicationPrecedence } //===----------------------------------------------------------------------===// // Standard operators //===----------------------------------------------------------------------===// // Standard postfix operators. postfix operator ++ postfix operator -- postfix operator ... // Optional<T> unwrapping operator is built into the compiler as a part of // postfix expression grammar. // // postfix operator ! // Standard prefix operators. prefix operator ++ prefix operator -- prefix operator ! prefix operator ~ prefix operator + prefix operator - prefix operator ... prefix operator ..< // Standard infix operators. // "Exponentiative" infix operator <<: BitwiseShiftPrecedence infix operator &<<: BitwiseShiftPrecedence infix operator >>: BitwiseShiftPrecedence infix operator &>>: BitwiseShiftPrecedence // "Multiplicative" infix operator *: MultiplicationPrecedence infix operator &*: MultiplicationPrecedence infix operator /: MultiplicationPrecedence infix operator %: MultiplicationPrecedence infix operator &: MultiplicationPrecedence // "Additive" infix operator +: AdditionPrecedence infix operator &+: AdditionPrecedence infix operator -: AdditionPrecedence infix operator &-: AdditionPrecedence infix operator |: AdditionPrecedence infix operator ^: AdditionPrecedence // FIXME: is this the right precedence level for "..." ? infix operator ...: RangeFormationPrecedence infix operator ..<: RangeFormationPrecedence // The cast operators 'as' and 'is' are hardcoded as if they had the // following attributes: // infix operator as: CastingPrecedence // "Coalescing" infix operator ??: NilCoalescingPrecedence // "Comparative" infix operator <: ComparisonPrecedence infix operator <=: ComparisonPrecedence infix operator >: ComparisonPrecedence infix operator >=: ComparisonPrecedence infix operator ==: ComparisonPrecedence infix operator !=: ComparisonPrecedence infix operator ===: ComparisonPrecedence infix operator !==: ComparisonPrecedence // FIXME: ~= will be built into the compiler. infix operator ~=: ComparisonPrecedence // "Conjunctive" infix operator &&: LogicalConjunctionPrecedence // "Disjunctive" infix operator ||: LogicalDisjunctionPrecedence // User-defined ternary operators are not supported. The ? : operator is // hardcoded as if it had the following attributes: // operator ternary ? : : TernaryPrecedence // User-defined assignment operators are not supported. The = operator is // hardcoded as if it had the following attributes: // infix operator =: AssignmentPrecedence // Compound infix operator *=: AssignmentPrecedence infix operator &*=: AssignmentPrecedence infix operator /=: AssignmentPrecedence infix operator %=: AssignmentPrecedence infix operator +=: AssignmentPrecedence infix operator &+=: AssignmentPrecedence infix operator -=: AssignmentPrecedence infix operator &-=: AssignmentPrecedence infix operator <<=: AssignmentPrecedence infix operator &<<=: AssignmentPrecedence infix operator >>=: AssignmentPrecedence infix operator &>>=: AssignmentPrecedence infix operator &=: AssignmentPrecedence infix operator ^=: AssignmentPrecedence infix operator |=: AssignmentPrecedence // Workaround for <rdar://problem/14011860> SubTLF: Default // implementations in protocols. Library authors should ensure // that this operator never needs to be seen by end-users. See // test/Prototypes/GenericDispatch.swift for a fully documented // example of how this operator is used, and how its use can be hidden // from users. infix operator ~>
apache-2.0
1e617796a4d97e654f1b47d943c2b787
34.193548
80
0.625974
4.933861
false
false
false
false
Rapid-SDK/ios
Examples/RapiDO - ToDo list/RapiDO tvOS/TaskViewController.swift
1
3586
// // AddTaskViewController.swift // ExampleApp // // Created by Jan on 08/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import UIKit import Rapid class TaskViewController: UITableViewController { @IBOutlet weak var cancelButton: UIBarButtonItem! @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var descriptionTextView: UITextField! @IBOutlet weak var priorityControl: UISegmentedControl! @IBOutlet weak var tagsTableView: TagsTableView! @IBOutlet weak var actionButton: UIButton! @IBOutlet weak var completedCheckbox: BEMCheckBox! var task: Task? override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } deinit { NotificationCenter.default.removeObserver(self) } // MARK: Actions @IBAction func saveTask(_ sender: Any) { let title: String if let text = titleTextField.text, !text.isEmpty { title = text } else { title = "Task" } let description: Any if let text = descriptionTextView.text, !text.isEmpty { description = text } else { description = NSNull() } let priority = Priority.allValues[priorityControl.selectedSegmentIndex].rawValue let tags = tagsTableView.selectedTags.map({$0.rawValue}) // Create task dictionary let task: [String: Any] = [ Task.titleAttributeName: title, Task.descriptionAttributeName: description, Task.createdAttributeName: self.task?.createdAt.isoString ?? Date().isoString, Task.priorityAttributeName: priority, Task.tagsAttributeName: tags, Task.completedAttributeName: completedCheckbox.on ] if let existingTask = self.task { // Update an existing task existingTask.update(withValue: task) } else { // Create a new task Task.create(withValue: task) } dismiss(animated: true, completion: nil) } @objc func cancel(_ sender: AnyObject) { dismiss(animated: true, completion: nil) } override func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { return false } } fileprivate extension TaskViewController { func setupUI() { cancelButton.target = self cancelButton.action = #selector(self.cancel(_:)) descriptionTextView.layer.borderColor = UIColor(red: 0.783922, green: 0.780392, blue: 0.8, alpha: 1).cgColor descriptionTextView.layer.borderWidth = 0.5 if let task = task { title = "Edit task" actionButton.setTitle("Save", for: .normal) completedCheckbox.isHidden = false completedCheckbox.on = task.completed titleTextField.text = task.title descriptionTextView.text = task.description priorityControl.selectedSegmentIndex = task.priority.rawValue tagsTableView.selectTags(task.tags) } else { title = "New task" actionButton.setTitle("Create", for: .normal) completedCheckbox.isHidden = true completedCheckbox.on = false tagsTableView.selectTags([]) } } }
mit
fd5a713993f2015d9e60891132d68484
28.385246
116
0.596932
5.17316
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/InputBar/TypingIndicatorView.swift
1
8212
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import WireDataModel final class AnimatedPenView: UIView { private let WritingAnimationKey = "writing" private let dots = UIImageView() private let pen = UIImageView() var isAnimating: Bool = false { didSet { pen.layer.speed = isAnimating ? 1 : 0 pen.layer.beginTime = pen.layer.convertTime(CACurrentMediaTime(), from: nil) } } override init(frame: CGRect) { super.init(frame: frame) let iconColor = SemanticColors.Icon.foregroundDefault let backgroundColor = SemanticColors.View.backgroundConversationView dots.setIcon(.typingDots, size: 8, color: iconColor) pen.setIcon(.pencil, size: 8, color: iconColor) pen.backgroundColor = backgroundColor pen.contentMode = .center addSubview(dots) addSubview(pen) setupConstraints() startWritingAnimation() pen.layer.speed = 0 pen.layer.timeOffset = 2 NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToWindow() { super.didMoveToWindow() startWritingAnimation() } private func setupConstraints() { [dots, pen].prepareForLayout() let distributeConstraint = pen.leftAnchor.constraint(equalTo: dots.rightAnchor, constant: 2) // Lower the priority to prevent this breaks when TypingIndicatorView's width = 0 distributeConstraint.priority = .defaultHigh NSLayoutConstraint.activate([ distributeConstraint, dots.leftAnchor.constraint(equalTo: leftAnchor), dots.topAnchor.constraint(equalTo: topAnchor), dots.bottomAnchor.constraint(equalTo: bottomAnchor), pen.rightAnchor.constraint(equalTo: rightAnchor), pen.topAnchor.constraint(equalTo: topAnchor), pen.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } func startWritingAnimation() { let p1 = 7 let p2 = 10 let p3 = 13 let moveX = CAKeyframeAnimation(keyPath: "position.x") moveX.values = [p1, p2, p2, p3, p3, p1] moveX.keyTimes = [0, 0.25, 0.35, 0.50, 0.75, 0.85] moveX.duration = 2 moveX.repeatCount = Float.infinity pen.layer.add(moveX, forKey: WritingAnimationKey) } func stopWritingAnimation() { pen.layer.removeAnimation(forKey: WritingAnimationKey) } @objc func applicationDidBecomeActive(_ notification: Notification) { startWritingAnimation() } } final class TypingIndicatorView: UIView { let nameLabel: UILabel = { let label = UILabel() label.font = .smallLightFont label.textColor = SemanticColors.Label.textDefault return label }() let animatedPen = AnimatedPenView() let container: UIView = { let view = UIView() view.backgroundColor = SemanticColors.View.backgroundConversationView return view }() let expandingLine: UIView = { let view = UIView() view.backgroundColor = SemanticColors.View.backgroundConversationView return view }() private lazy var expandingLineWidth: NSLayoutConstraint = expandingLine.widthAnchor.constraint(equalToConstant: 0) var typingUsers: [UserType] = [] { didSet { updateNameLabel() } } override init(frame: CGRect) { super.init(frame: frame) addSubview(expandingLine) addSubview(container) container.addSubview(nameLabel) container.addSubview(animatedPen) setupConstraints() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() container.layer.cornerRadius = container.bounds.size.height / 2 } private func setupConstraints() { [nameLabel, container, animatedPen, expandingLine].prepareForLayout() // Lower the priority to prevent this breaks when container's height = 0 let nameLabelBottomConstraint = container.bottomAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 4) nameLabelBottomConstraint.priority = .defaultHigh let distributeConstraint = nameLabel.leftAnchor.constraint(equalTo: animatedPen.rightAnchor, constant: 4) distributeConstraint.priority = .defaultHigh NSLayoutConstraint.activate([ container.topAnchor.constraint(equalTo: topAnchor), container.bottomAnchor.constraint(equalTo: bottomAnchor), container.leftAnchor.constraint(equalTo: leftAnchor), container.rightAnchor.constraint(equalTo: rightAnchor), distributeConstraint, animatedPen.leftAnchor.constraint(equalTo: container.leftAnchor, constant: 8), animatedPen.centerYAnchor.constraint(equalTo: container.centerYAnchor), nameLabel.topAnchor.constraint(equalTo: container.topAnchor, constant: 4), nameLabelBottomConstraint, nameLabel.rightAnchor.constraint(equalTo: container.rightAnchor, constant: -8), expandingLine.centerXAnchor.constraint(equalTo: centerXAnchor), expandingLine.centerYAnchor.constraint(equalTo: centerYAnchor), expandingLine.heightAnchor.constraint(equalToConstant: 1), expandingLineWidth ]) } func updateNameLabel() { nameLabel.text = typingUsers.compactMap { $0.name?.uppercased(with: Locale.current) }.joined(separator: ", ") } func setHidden(_ hidden: Bool, animated: Bool, completion: Completion? = nil) { let collapseLine = { () -> Void in self.expandingLineWidth.constant = 0 self.layoutIfNeeded() } let expandLine = { () -> Void in self.expandingLineWidth.constant = self.bounds.width self.layoutIfNeeded() } let showContainer = { self.container.alpha = 1 } let hideContainer = { self.container.alpha = 0 } if animated { if hidden { collapseLine() UIView.animate(withDuration: 0.15, animations: hideContainer) { _ in completion?() } } else { animatedPen.isAnimating = false self.layoutSubviews() UIView.animate(easing: .easeInOutQuad, duration: 0.35, animations: expandLine) UIView.animate(easing: .easeInQuad, duration: 0.15, delayTime: 0.15, animations: showContainer, completion: { _ in self.animatedPen.isAnimating = true completion?() }) } } else { if hidden { collapseLine() self.container.alpha = 0 } else { expandLine() showContainer() } completion?() } } }
gpl-3.0
b0c1ec3e7d14c39fda19281efa282b52
30.829457
163
0.624452
5.155053
false
false
false
false
benlangmuir/swift
validation-test/Reflection/reflect_UInt32.swift
19
1784
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_UInt32 // RUN: %target-codesign %t/reflect_UInt32 // RUN: %target-run %target-swift-reflection-test %t/reflect_UInt32 | %FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: reflection_test_support // REQUIRES: executable_test // UNSUPPORTED: use_os_stdlib import SwiftReflectionTest class TestClass { var t: UInt32 init(t: UInt32) { 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_UInt32.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=t offset=16 // CHECK-64: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) // 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_UInt32.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=12 alignment=4 stride=12 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=t offset=8 // CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
3136998f159a29183715d66e43e56448
33.307692
120
0.695067
3.113438
false
true
false
false
royratcliffe/HypertextApplicationLanguage
Sources/Link+Equatable.swift
1
1730
// HypertextApplicationLanguage Link+Equatable.swift // // Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom // // 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, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO // EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES // OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //------------------------------------------------------------------------------ extension Link: Equatable { /// - returns: Answers `true` if this `Link` compares equal to another. public static func == (lhs: Link, rhs: Link) -> Bool { return lhs.rel == rhs.rel && lhs.href == rhs.href && lhs.name == rhs.name && lhs.title == rhs.title && lhs.hreflang == rhs.hreflang && lhs.profile == rhs.profile } }
mit
21e24c79b07f216820e41fc4043b1157
45.513514
80
0.665892
4.577128
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Swift Note/CS193p/iOS11/EmojiArtForDocument/DocumentInfoViewController.swift
1
2654
// // DocumentInfoViewController.swift // EmojiArtForDocument // // Created by 朱双泉 on 2018/5/17. // Copyright © 2018 Castie!. All rights reserved. // import UIKit class DocumentInfoViewController: UIViewController { var document: EmojiArtDocument? { didSet { updateUI() } } override func viewDidLoad() { super.viewDidLoad() updateUI() } private let shortDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .short return formatter }() private func updateUI() { if sizeLabel != nil, createdLabel != nil, let url = document?.fileURL, let attributes = try? FileManager.default.attributesOfItem(atPath: url.path) { sizeLabel.text = "\(attributes[.size] ?? 0) bytes" if let created = attributes[.creationDate] as? Date { createdLabel.text = shortDateFormatter.string(from: created) } } if thumbnailImageView != nil, thumbnailAspectRetio != nil, let thumbnail = document?.thumbnail { thumbnailImageView.image = thumbnail thumbnailImageView.removeConstraint(thumbnailAspectRetio) thumbnailAspectRetio = NSLayoutConstraint( item: thumbnailImageView, attribute: .width, relatedBy: .equal, toItem: thumbnailImageView, attribute: .height, multiplier: thumbnail.size.width / thumbnail.size.height, constant: 0 ) thumbnailImageView.addConstraint(thumbnailAspectRetio) } if presentationController is UIPopoverPresentationController { thumbnailImageView?.isHidden = true returnToDocumentButton?.isHidden = true view.backgroundColor = .clear } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let fittedSize = topLevelView?.sizeThatFits(UILayoutFittingCompressedSize) { preferredContentSize = CGSize(width: fittedSize.width + 30, height: fittedSize.height + 30) } } @IBAction func done() { presentingViewController?.dismiss(animated: true) } @IBOutlet weak var returnToDocumentButton: UIButton! @IBOutlet weak var topLevelView: UIStackView! @IBOutlet weak var thumbnailAspectRetio: NSLayoutConstraint! @IBOutlet weak var thumbnailImageView: UIImageView! @IBOutlet weak var sizeLabel: UILabel! @IBOutlet weak var createdLabel: UILabel! }
mit
7d2691fba49ff1bf8ca52a53e5c8f99f
33.828947
104
0.634303
5.435318
false
false
false
false
grafiti-io/SwiftCharts
SwiftCharts/Chart.swift
1
27068
// // Chart.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit /// ChartSettings allows configuration of the visual layout of a chart open class ChartSettings { /// Empty space in points added to the leading edge of the chart open var leading: CGFloat = 0 /// Empty space in points added to the top edge of the chart open var top: CGFloat = 0 /// Empty space in points added to the trailing edge of the chart open var trailing: CGFloat = 0 /// Empty space in points added to the bottom edge of the chart open var bottom: CGFloat = 0 /// The spacing in points between axis labels when using multiple labels for each axis value. This is currently only supported with an X axis. open var labelsSpacing: CGFloat = 5 /// The spacing in points between X axis labels and the X axis line open var labelsToAxisSpacingX: CGFloat = 5 /// The spacing in points between Y axis labels and the Y axis line open var labelsToAxisSpacingY: CGFloat = 5 open var spacingBetweenAxesX: CGFloat = 15 open var spacingBetweenAxesY: CGFloat = 15 /// The spacing in points between axis title labels and axis labels open var axisTitleLabelsToLabelsSpacing: CGFloat = 5 /// The stroke width in points of the axis lines open var axisStrokeWidth: CGFloat = 1.0 open var zoomPan = ChartSettingsZoomPan() public init() {} } open class ChartSettingsZoomPan { open var panEnabled = false open var zoomEnabled = false open var minZoomX: CGFloat? open var minZoomY: CGFloat? open var maxZoomX: CGFloat? open var maxZoomY: CGFloat? open var gestureMode: ChartZoomPanGestureMode = .max open var elastic: Bool = false } public enum ChartZoomPanGestureMode { case onlyX // Only X axis is zoomed/panned case onlyY // Only Y axis is zoomed/panned case max // Only axis corresponding to dimension with max zoom/pan delta is zoomed/panned case both // Both axes are zoomed/panned } public protocol ChartDelegate { func onZoom(scaleX: CGFloat, scaleY: CGFloat, deltaX: CGFloat, deltaY: CGFloat, centerX: CGFloat, centerY: CGFloat, isGesture: Bool) func onPan(transX: CGFloat, transY: CGFloat, deltaX: CGFloat, deltaY: CGFloat, isGesture: Bool, isDeceleration: Bool) func onTap(_ models: [TappedChartPointLayerModels<ChartPoint>]) } /// A Chart object is the highest level access to your chart. It has the view where all of the chart layers are drawn, which you can provide (useful if you want to position it as part of a storyboard or XIB), or it can be created for you. open class Chart: Pannable, Zoomable { /// The view that the chart is drawn in open let view: ChartView open let containerView: UIView open let contentView: UIView open let drawersContentView: UIView /// The layers of the chart that are drawn in the view fileprivate let layers: [ChartLayer] open var delegate: ChartDelegate? open var transX: CGFloat { return contentFrame.minX } open var transY: CGFloat { return contentFrame.minY } open var scaleX: CGFloat { return contentFrame.width / containerFrame.width } open var scaleY: CGFloat { return contentFrame.height / containerFrame.height } open var maxScaleX: CGFloat? { return settings.zoomPan.maxZoomX } open var minScaleX: CGFloat? { return settings.zoomPan.minZoomX } open var maxScaleY: CGFloat? { return settings.zoomPan.maxZoomY } open var minScaleY: CGFloat? { return settings.zoomPan.minZoomY } fileprivate let settings: ChartSettings open var zoomPanSettings: ChartSettingsZoomPan { set { settings.zoomPan = zoomPanSettings configZoomPan(zoomPanSettings) } get { return settings.zoomPan } } /** Create a new Chart with a frame and layers. A new ChartBaseView will be created for you. - parameter innerFrame: Frame comprised by axes, where the chart displays content - parameter settings: Chart settings - parameter frame: The frame used for the ChartBaseView - parameter layers: The layers that are drawn in the chart - returns: The new Chart */ convenience public init(frame: CGRect, innerFrame: CGRect? = nil, settings: ChartSettings, layers: [ChartLayer]) { self.init(view: ChartBaseView(frame: frame), innerFrame: innerFrame, settings: settings, layers: layers) } /** Create a new Chart with a view and layers. - parameter innerFrame: Frame comprised by axes, where the chart displays content - parameter settings: Chart settings - parameter view: The view that the chart will be drawn in - parameter layers: The layers that are drawn in the chart - returns: The new Chart */ public init(view: ChartView, innerFrame: CGRect? = nil, settings: ChartSettings, layers: [ChartLayer]) { self.layers = layers self.view = view self.settings = settings let containerView = UIView(frame: innerFrame ?? view.bounds) let drawersContentView = ChartContentView(frame: containerView.bounds) drawersContentView.backgroundColor = UIColor.clear containerView.addSubview(drawersContentView) let contentView = ChartContentView(frame: containerView.bounds) contentView.backgroundColor = UIColor.clear containerView.addSubview(contentView) containerView.clipsToBounds = true view.addSubview(containerView) self.contentView = contentView self.drawersContentView = drawersContentView self.containerView = containerView contentView.chart = self drawersContentView.chart = self self.view.chart = self for layer in self.layers { layer.chartInitialized(chart: self) } self.view.setNeedsDisplay() view.initRecognizers(settings) configZoomPan(settings.zoomPan) } fileprivate func configZoomPan(_ settings: ChartSettingsZoomPan) { if settings.minZoomX != nil || settings.minZoomY != nil { zoom(scaleX: settings.minZoomX ?? 1, scaleY: settings.minZoomY ?? 1, anchorX: 0, anchorY: 0) } } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Adds a subview to the chart's content view - parameter view: The subview to add to the chart's content view */ open func addSubview(_ view: UIView) { contentView.addSubview(view) } open func addSubviewNoTransform(_ view: UIView) { containerView.addSubview(view) } /// The frame of the chart's view open var frame: CGRect { return view.frame } open var containerFrame: CGRect { return containerView.frame } open var contentFrame: CGRect { return contentView.frame } /// The bounds of the chart's view open var bounds: CGRect { return view.bounds } /** Removes the chart's view from its superview */ open func clearView() { view.removeFromSuperview() } open func update() { for layer in layers { layer.update() } self.view.setNeedsDisplay() } func notifyAxisInnerFrameChange(xLow: ChartAxisLayerWithFrameDelta? = nil, yLow: ChartAxisLayerWithFrameDelta? = nil, xHigh: ChartAxisLayerWithFrameDelta? = nil, yHigh: ChartAxisLayerWithFrameDelta? = nil) { for layer in layers { layer.handleAxisInnerFrameChange(xLow, yLow: yLow, xHigh: xHigh, yHigh: yHigh) } handleAxisInnerFrameChange(xLow, yLow: yLow, xHigh: xHigh, yHigh: yHigh) } fileprivate func handleAxisInnerFrameChange(_ xLow: ChartAxisLayerWithFrameDelta?, yLow: ChartAxisLayerWithFrameDelta?, xHigh: ChartAxisLayerWithFrameDelta?, yHigh: ChartAxisLayerWithFrameDelta?) { let previousContentFrame = contentView.frame // Resize container view containerView.frame = containerView.frame.insetBy(dx: yLow.deltaDefault0, dy: xHigh.deltaDefault0, dw: yHigh.deltaDefault0, dh: xLow.deltaDefault0) // Change dimensions of content view by total delta of container view contentView.frame = CGRect(x: contentView.frame.origin.x, y: contentView.frame.origin.y, width: contentView.frame.width - (yLow.deltaDefault0 + yHigh.deltaDefault0), height: contentView.frame.height - (xLow.deltaDefault0 + xHigh.deltaDefault0)) // Scale contents of content view let widthChangeFactor = contentView.frame.width / previousContentFrame.width let heightChangeFactor = contentView.frame.height / previousContentFrame.height let frameBeforeScale = contentView.frame contentView.transform = CGAffineTransform(scaleX: contentView.transform.a * widthChangeFactor, y: contentView.transform.d * heightChangeFactor) contentView.frame = frameBeforeScale } open func onZoomStart(deltaX: CGFloat, deltaY: CGFloat, centerX: CGFloat, centerY: CGFloat) { for layer in layers { layer.zoom(deltaX, y: deltaY, centerX: centerX, centerY: centerY) } } open func onZoomStart(scaleX: CGFloat, scaleY: CGFloat, centerX: CGFloat, centerY: CGFloat) { for layer in layers { layer.zoom(scaleX, scaleY: scaleY, centerX: centerX, centerY: centerY) } } open func onZoomFinish(scaleX: CGFloat, scaleY: CGFloat, deltaX: CGFloat, deltaY: CGFloat, centerX: CGFloat, centerY: CGFloat, isGesture: Bool) { for layer in layers { layer.handleZoomFinish() } delegate?.onZoom(scaleX: scaleX, scaleY: scaleY, deltaX: deltaX, deltaY: deltaY, centerX: centerX, centerY: centerY, isGesture: isGesture) } open func onPanStart(deltaX: CGFloat, deltaY: CGFloat) { for layer in layers { layer.pan(deltaX, deltaY: deltaY) } } open func onPanStart(location: CGPoint) { for layer in layers { layer.handlePanStart(location) } } open func onPanEnd() { for layer in layers { layer.handlePanEnd() } } open func onZoomEnd() { for layer in layers { layer.handleZoomEnd() } } open func onPanFinish(transX: CGFloat, transY: CGFloat, deltaX: CGFloat, deltaY: CGFloat, isGesture: Bool, isDeceleration: Bool) { for layer in layers { layer.handlePanFinish() } delegate?.onPan(transX: transX, transY: transY, deltaX: deltaX, deltaY: deltaY, isGesture: isGesture, isDeceleration: isDeceleration) } func onTap(_ location: CGPoint) { var models = [TappedChartPointLayerModels<ChartPoint>]() for layer in layers { if let chartPointsLayer = layer as? ChartPointsLayer { if let tappedModels = chartPointsLayer.handleGlobalTap(location) as? TappedChartPointLayerModels<ChartPoint> { models.append(tappedModels) } } else { layer.handleGlobalTap(location) } } delegate?.onTap(models) } open func resetPanZoom() { zoom(scaleX: minScaleX ?? 1, scaleY: minScaleY ?? 1, anchorX: 0, anchorY: 0) pan(deltaX: 10000, deltaY: 10000, isGesture: false, isDeceleration: false, elastic: false) keepInBoundaries() for layer in layers { layer.keepInBoundaries() } } /** Draws the chart's layers in the chart view - parameter rect: The rect that needs to be drawn */ fileprivate func drawRect(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else {return} for layer in self.layers { layer.chartViewDrawing(context: context, chart: self) } } fileprivate func drawContentViewRect(_ rect: CGRect, sender: ChartContentView) { guard let context = UIGraphicsGetCurrentContext() else {return} if sender == drawersContentView { for layer in layers { layer.chartDrawersContentViewDrawing(context: context, chart: self, view: sender) } } else if sender == contentView { for layer in layers { layer.chartContentViewDrawing(context: context, chart: self) } drawersContentView.setNeedsDisplay() } } func allowPan(location: CGPoint, deltaX: CGFloat, deltaY: CGFloat, isGesture: Bool, isDeceleration: Bool) -> Bool { var someLayerProcessedPan = false for layer in layers { if layer.processPan(location: location, deltaX: deltaX, deltaY: deltaY, isGesture: isGesture, isDeceleration: isDeceleration) { someLayerProcessedPan = true } } return !someLayerProcessedPan } func allowZoom(deltaX: CGFloat, deltaY: CGFloat, anchorX: CGFloat, anchorY: CGFloat) -> Bool { var someLayerProcessedZoom = false for layer in layers { if layer.processZoom(deltaX: deltaX, deltaY: deltaY, anchorX: anchorX, anchorY: anchorY) { someLayerProcessedZoom = true } } return !someLayerProcessedZoom } } open class ChartContentView: UIView { weak var chart: Chart? override open func draw(_ rect: CGRect) { self.chart?.drawContentViewRect(rect, sender: self) } } /// A UIView subclass for drawing charts open class ChartBaseView: ChartView { override open func draw(_ rect: CGRect) { self.chart?.drawRect(rect) } } open class ChartView: UIView, UIGestureRecognizerDelegate { /// The chart that will be drawn in this view weak var chart: Chart? fileprivate var lastPanTranslation: CGPoint? fileprivate var isPanningX: Bool? // true: x, false: y fileprivate var pinchRecognizer: UIPinchGestureRecognizer? fileprivate var panRecognizer: UIPanGestureRecognizer? fileprivate var tapRecognizer: UITapGestureRecognizer? override public init(frame: CGRect) { super.init(frame: frame) sharedInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInit() } func initRecognizers(_ settings: ChartSettings) { if settings.zoomPan.zoomEnabled { let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(ChartView.onPinch(_:))) pinchRecognizer.delegate = self addGestureRecognizer(pinchRecognizer) self.pinchRecognizer = pinchRecognizer } if settings.zoomPan.panEnabled { let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ChartView.onPan(_:))) panRecognizer.delegate = self addGestureRecognizer(panRecognizer) self.panRecognizer = panRecognizer } let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ChartView.onTap(_:))) tapRecognizer.delegate = self tapRecognizer.cancelsTouchesInView = false addGestureRecognizer(tapRecognizer) self.tapRecognizer = tapRecognizer } /** Initialization code shared between all initializers */ func sharedInit() { backgroundColor = UIColor.clear } fileprivate var zoomCenter: CGPoint? @objc func onPinch(_ sender: UIPinchGestureRecognizer) { guard let chartSettings = chart?.settings, chartSettings.zoomPan.zoomEnabled else {return} switch sender.state { case .began: zoomCenter = nil fallthrough case .changed: guard sender.numberOfTouches > 1 else {return} let center = zoomCenter ?? { let center = sender.location(in: self) zoomCenter = center return center }() let x = abs(sender.location(in: self).x - sender.location(ofTouch: 1, in: self).x) let y = abs(sender.location(in: self).y - sender.location(ofTouch: 1, in: self).y) let (deltaX, deltaY): (CGFloat, CGFloat) = { switch chartSettings.zoomPan.gestureMode { case .onlyX: return (sender.scale, 1) case .onlyY: return (1, sender.scale) case .max: return x > y ? (sender.scale, 1) : (1, sender.scale) case .both: // calculate scale x and scale y let (absMax, absMin) = x > y ? (abs(x), abs(y)) : (abs(y), abs(x)) let minScale = (absMin * (sender.scale - 1) / absMax) + 1 return x > y ? (sender.scale, minScale) : (minScale, sender.scale) } }() chart?.zoom(deltaX: deltaX, deltaY: deltaY, centerX: center.x, centerY: center.y, isGesture: true) case .ended: guard let center = zoomCenter, let chart = chart else {print("No center or chart"); return} let adjustBoundsVelocity: CGFloat = 0.2 let minScaleX = chart.settings.zoomPan.minZoomX ?? 1 let minScaleY = chart.settings.zoomPan.minZoomY ?? 1 func outOfBoundsOffsets(_ limit: Bool) -> (x: CGFloat, y: CGFloat) { let scaleX = chart.scaleX var x: CGFloat? if scaleX < minScaleX { x = limit ? min(1 + adjustBoundsVelocity, minScaleX / scaleX) : minScaleX / scaleX } if x == minScaleX { x = nil } let scaleY = chart.scaleY var y: CGFloat? if scaleY < minScaleY { y = limit ? min(1 + adjustBoundsVelocity, minScaleY / scaleY) : minScaleY / scaleY } if y == minScaleY { y = nil } return (x ?? 1, y ?? 1) } func adjustBoundsRec(_ counter: Int) { // FIXME if counter > 400 { let (xOffset, yOffset) = outOfBoundsOffsets(false) chart.zoom(deltaX: xOffset, deltaY: yOffset, centerX: center.x, centerY: center.y, isGesture: true) return } DispatchQueue.main.async { let (xOffset, yOffset) = outOfBoundsOffsets(true) if xOffset != 1 || yOffset != 1 { chart.zoom(deltaX: xOffset, deltaY: yOffset, centerX: center.x, centerY: center.y, isGesture: true) adjustBoundsRec(counter + 1) } } } func adjustBounds() -> Bool { let (xOffset, yOffset) = outOfBoundsOffsets(true) guard (xOffset != 1 || yOffset != 1) else { if chart.scaleX =~ minScaleX || chart.scaleY =~ minScaleY { chart.pan(deltaX: chart.scaleX =~ minScaleY ? -chart.contentView.frame.minX : 0, deltaY: chart.scaleY =~ minScaleY ? -chart.contentView.frame.minY : 0, isGesture: false, isDeceleration: false, elastic: chart.zoomPanSettings.elastic) } return false } adjustBoundsRec(0) return true } if chart.zoomPanSettings.elastic { adjustBounds() } chart.onZoomEnd() case .cancelled: chart?.onZoomEnd() case .failed: fallthrough case .possible: break } sender.scale = 1.0 } @objc func onPan(_ sender: UIPanGestureRecognizer) { guard let chartSettings = chart?.settings , chartSettings.zoomPan.panEnabled else {return} func finalPanDelta(deltaX: CGFloat, deltaY: CGFloat) -> (deltaX: CGFloat, deltaY: CGFloat) { switch chartSettings.zoomPan.gestureMode { case .onlyX: return (deltaX, 0) case .onlyY: return (0, deltaY) case .max: if isPanningX == nil { isPanningX = abs(deltaX) > abs(deltaY) } return isPanningX! ? (deltaX, 0) : (0, deltaY) case .both: return (deltaX, deltaY) } } switch sender.state { case .began: lastPanTranslation = nil isPanningX = nil chart?.onPanStart(location: sender.location(in: self)) case .changed: let trans = sender.translation(in: self) let location = sender.location(in: self) var deltaX = lastPanTranslation.map{trans.x - $0.x} ?? trans.x let deltaY = lastPanTranslation.map{trans.y - $0.y} ?? trans.y var (finalDeltaX, finalDeltaY) = finalPanDelta(deltaX: deltaX, deltaY: deltaY) lastPanTranslation = trans if (chart?.allowPan(location: location, deltaX: finalDeltaX, deltaY: finalDeltaY, isGesture: true, isDeceleration: false)) ?? false { chart?.pan(deltaX: finalDeltaX, deltaY: finalDeltaY, isGesture: true, isDeceleration: false, elastic: chart?.zoomPanSettings.elastic ?? false) } case .ended: guard let view = sender.view, let chart = chart else {print("No view or chart"); return} let velocityX = sender.velocity(in: sender.view).x let velocityY = sender.velocity(in: sender.view).y let (finalDeltaX, finalDeltaY) = finalPanDelta(deltaX: velocityX, deltaY: velocityY) let location = sender.location(in: self) func next(_ velocityX: CGFloat, velocityY: CGFloat) { DispatchQueue.main.async { chart.pan(deltaX: velocityX, deltaY: velocityY, isGesture: true, isDeceleration: true, elastic: chart.zoomPanSettings.elastic) if abs(velocityX) > 0.1 || abs(velocityY) > 0.1 { let friction: CGFloat = 0.9 next(velocityX * friction, velocityY: velocityY * friction) } else { if chart.zoomPanSettings.elastic { adjustBounds() } } } } let adjustBoundsVelocity: CGFloat = 20 func outOfBoundsOffsets(_ limit: Bool) -> (x: CGFloat, y: CGFloat) { var x: CGFloat? if chart.contentView.frame.minX > 0 { x = limit ? max(-adjustBoundsVelocity, -chart.contentView.frame.minX) : -chart.contentView.frame.minX } else { let offset = chart.contentView.frame.maxX - chart.containerView.frame.width if offset < 0 { x = limit ? min(adjustBoundsVelocity, -offset) : -offset } } var y: CGFloat? if chart.contentView.frame.minY > 0 { y = limit ? max(-adjustBoundsVelocity, -chart.contentView.frame.minY) : -chart.contentView.frame.minY } else { let offset = chart.contentView.frame.maxY - chart.containerView.frame.height if offset < 0 { y = limit ? min(adjustBoundsVelocity, -offset) : -offset } } // Drop possile values < epsilon, this causes endless loop since adding them to the view translation apparently is a no-op let roundDecimals: CGFloat = 1000000000 x = x.map{($0 * roundDecimals) / roundDecimals}.flatMap{$0 =~ 0 ? 0 : x} y = y.map{($0 * roundDecimals) / roundDecimals}.flatMap{$0 =~ 0 ? 0 : y} return (x ?? 0, y ?? 0) } func adjustBoundsRec(_ counter: Int) { // FIXME if counter > 400 { let (xOffset, yOffset) = outOfBoundsOffsets(false) chart.pan(deltaX: xOffset, deltaY: yOffset, isGesture: true, isDeceleration: false, elastic: chart.zoomPanSettings.elastic) return } DispatchQueue.main.async { let (xOffset, yOffset) = outOfBoundsOffsets(true) if xOffset != 0 || yOffset != 0 { chart.pan(deltaX: xOffset, deltaY: yOffset, isGesture: true, isDeceleration: false, elastic: chart.zoomPanSettings.elastic) adjustBoundsRec(counter + 1) } } } func adjustBounds() -> Bool { let (xOffset, yOffset) = outOfBoundsOffsets(true) guard (xOffset != 0 || yOffset != 0) else {return false} adjustBoundsRec(0) return true } let initFriction: CGFloat = 50 if (chart.allowPan(location: location, deltaX: finalDeltaX, deltaY: finalDeltaY, isGesture: true, isDeceleration: false)) ?? false { if (chart.zoomPanSettings.elastic && !adjustBounds()) || !chart.zoomPanSettings.elastic { next(finalDeltaX / initFriction, velocityY: finalDeltaY / initFriction) } } chart.onPanEnd() case .cancelled: break; case .failed: break; case .possible: // sender.state = UIGestureRecognizerState.Changed break; } } @objc func onTap(_ sender: UITapGestureRecognizer) { chart?.onTap(sender.location(in: self)) } }
apache-2.0
9cf4d616212c6784e1200d0360721497
35.235609
256
0.580168
4.895641
false
false
false
false
li1024316925/Swift-TimeMovie
Swift-TimeMovie/Swift-TimeMovie/MyInfoView.swift
1
3509
// // MyInfoView.swift // SwiftTimeMovie // // Created by DahaiZhang on 16/10/24. // Copyright © 2016年 LLQ. All rights reserved. // import UIKit class MyInfoView: UIView { var dataList:NSArray? //重写初始化方法 override init(frame: CGRect) { super.init(frame: frame) //数据 loadData() //表视图 createTableView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //加载数据 func loadData() -> Void { dataList = NSArray(contentsOfFile: Bundle.main.path(forResource: "MyInfoDataList", ofType: "plist")!) } //创建表视图 func createTableView() -> Void { let myinfoTableView = UITableView(frame: bounds, style: UITableViewStyle.plain) myinfoTableView.delegate = self myinfoTableView.dataSource = self myinfoTableView.sectionHeaderHeight = 30 let headerView = Bundle.main.loadNibNamed("MyInfoTableHeaderView", owner: nil, options: nil)![0] as? MyInfoTableHeaderView headerView?.view.backgroundColor = UIColor(patternImage: UIImage(named: "cinema_head_bg")!) myinfoTableView.tableHeaderView = headerView addSubview(myinfoTableView) } } extension MyInfoView:UITableViewDelegate,UITableViewDataSource{ //组数 func numberOfSections(in tableView: UITableView) -> Int { return (dataList?.count)! } //每组单元格数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let arr = dataList?[section] as? NSArray return arr!.count } //单元格 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell1 = tableView.dequeueReusableCell(withIdentifier: "cell1") var cell2 = tableView.dequeueReusableCell(withIdentifier: "cell2") if indexPath.section == 0 { //数据 let array = dataList?[indexPath.section] as? NSArray let dic = array![indexPath.row] as? NSDictionary if cell1 == nil { cell1 = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell1") cell1?.accessoryType = UITableViewCellAccessoryType.disclosureIndicator } cell1?.textLabel?.text = dic?.object(forKey: "title") as? String cell1?.imageView?.image = UIImage(named: (dic?.object(forKey: "image") as? String)!) return cell1! }else { let array = dataList?[indexPath.section] as? NSArray if cell2 == nil { cell2 = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell2") cell2?.accessoryType = UITableViewCellAccessoryType.disclosureIndicator } cell2?.textLabel?.text = array?[indexPath.row] as? String return cell2! } } //组头视图 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 30)) view.backgroundColor = UIColor.gray return view } }
apache-2.0
20cc1fa765877d0674c77bf238ffb902
29.087719
130
0.591545
5.007299
false
false
false
false
caicai0/ios_demo
load/thirdpart/SwiftKuery/Having.swift
1
3561
/** Copyright IBM Corporation 2016 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. */ // MARK: Having /// An SQL HAVING clause. public struct Having: ConditionalClause, QueryHavingProtocol { public typealias ClauseType = Having public typealias ColumnExpressionType = AggregateColumnExpression /// The left hand side of the conditional clause. public let lhs: Predicate<Having, AggregateColumnExpression>? /// The right hand side of the conditional clause. public let rhs: Predicate<Having, AggregateColumnExpression>? /// The operator of the conditional clause. public let condition: Condition init(lhs: Predicate<Having, AggregateColumnExpression>?=nil, rhs: Predicate<Having, AggregateColumnExpression>?=nil, condition: Condition) { self.lhs = lhs self.rhs = rhs self.condition = condition } } // MARK: QueryHavingProtocol /// Defines the protocol which should be used for all HAVING clauses. /// Represents a HAVING clause as String value. public protocol QueryHavingProtocol: Buildable { } // MARK Global functions /// Create a `Having` clause using the OR operator. /// /// - Parameter lhs: A `Having` - the left hand side of the clause. /// - Parameter rhs: A `Having` - the right hand side of the clause. /// - Returns: A `Having` containing the clause. public func || (lhs: Having, rhs: Having) -> Having { return Having(lhs: .clause(lhs), rhs: .clause(rhs), condition: .or) } /// Create a `Having` clause using the AND operator. /// /// - Parameter lhs: A `Having` - the left hand side of the clause. /// - Parameter rhs: A `Having` - the right hand side of the clause. /// - Returns: A `Having` containing the clause. public func && (lhs: Having, rhs: Having) -> Having { return Having(lhs: .clause(lhs), rhs: .clause(rhs), condition: .and) } /// Create a `Having` clause using the EXISTS operator. /// /// - Parameter query: The `Select` query to apply EXISTS on. /// - Returns: A `Having` containing the clause. public func exists(_ query: Select) -> Having { return Having(rhs: .select(query), condition: .exists) } /// Create a `Having` clause using the NOT EXISTS operator. /// /// - Parameter query: The `Select` query to apply NOT EXISTS on. /// - Returns: A `Having` containing the clause. public func notExists(_ query: Select) -> Having { return Having(rhs: .select(query), condition: .notExists) } /// Create a `HavingPredicate` using the ANY operator. /// /// - Parameter query: The `Select` query to apply ANY on. /// - Returns: A `Predicate<Having, AggregateColumnExpression>` containing the anySubquery. public func any(_ query: Select) -> Predicate<Having, AggregateColumnExpression> { return .anySubquery(query) } /// Create a `HavingPredicate` using the ALL operator. /// /// - Parameter query: The `Select` query to apply ALL on. /// - Returns: A `Predicate<Having, AggregateColumnExpression>` containing the allSubquery. public func all(_ query: Select) -> Predicate<Having, AggregateColumnExpression> { return .allSubquery(query) }
mit
44b13265fbf9dbcbfdeb1f438e5d7e0b
36.484211
144
0.713844
4.093103
false
false
false
false
Ehrippura/firefox-ios
Client/Frontend/Settings/SettingsTableViewController.swift
2
28539
/* 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 Account import Shared import UIKit // A base setting class that shows a title. You probably want to subclass this, not use it directly. class Setting: NSObject { fileprivate var _title: NSAttributedString? fileprivate var _footerTitle: NSAttributedString? fileprivate var _cellHeight: CGFloat? fileprivate var _image: UIImage? weak var delegate: SettingsDelegate? // The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy. var url: URL? { return nil } // The title shown on the pref. var title: NSAttributedString? { return _title } var footerTitle: NSAttributedString? { return _footerTitle } var cellHeight: CGFloat? { return _cellHeight} fileprivate(set) var accessibilityIdentifier: String? // An optional second line of text shown on the pref. var status: NSAttributedString? { return nil } // Whether or not to show this pref. var hidden: Bool { return false } var style: UITableViewCellStyle { return .subtitle } var accessoryType: UITableViewCellAccessoryType { return .none } var textAlignment: NSTextAlignment { return .natural } var image: UIImage? { return _image } fileprivate(set) var enabled: Bool = true // Called when the cell is setup. Call if you need the default behaviour. func onConfigureCell(_ cell: UITableViewCell) { cell.detailTextLabel?.attributedText = status cell.detailTextLabel?.numberOfLines = 0 cell.textLabel?.attributedText = title cell.textLabel?.textAlignment = textAlignment cell.textLabel?.numberOfLines = 0 cell.accessoryType = accessoryType cell.accessoryView = nil cell.selectionStyle = enabled ? .default : .none cell.accessibilityIdentifier = accessibilityIdentifier cell.imageView?.image = _image if let title = title?.string { if let detailText = cell.detailTextLabel?.text { cell.accessibilityLabel = "\(title), \(detailText)" } else if let status = status?.string { cell.accessibilityLabel = "\(title), \(status)" } else { cell.accessibilityLabel = title } } cell.accessibilityTraits = UIAccessibilityTraitButton cell.indentationWidth = 0 cell.layoutMargins = UIEdgeInsets.zero // So that the separator line goes all the way to the left edge. cell.separatorInset = UIEdgeInsets.zero } // Called when the pref is tapped. func onClick(_ navigationController: UINavigationController?) { return } // Helper method to set up and push a SettingsContentViewController func setUpAndPushSettingsContentViewController(_ navigationController: UINavigationController?) { if let url = self.url { let viewController = SettingsContentViewController() viewController.settingsTitle = self.title viewController.url = url navigationController?.pushViewController(viewController, animated: true) } } init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) { self._title = title self._footerTitle = footerTitle self._cellHeight = cellHeight self.delegate = delegate self.enabled = enabled ?? true } } // A setting in the sections panel. Contains a sublist of Settings class SettingSection: Setting { fileprivate let children: [Setting] init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, children: [Setting]) { self.children = children super.init(title: title, footerTitle: footerTitle, cellHeight: cellHeight) } var count: Int { var count = 0 for setting in children where !setting.hidden { count += 1 } return count } subscript(val: Int) -> Setting? { var i = 0 for setting in children where !setting.hidden { if i == val { return setting } i += 1 } return nil } } private class PaddedSwitch: UIView { fileprivate static let Padding: CGFloat = 8 init(switchView: UISwitch) { super.init(frame: CGRect.zero) addSubview(switchView) frame.size = CGSize(width: switchView.frame.width + PaddedSwitch.Padding, height: switchView.frame.height) switchView.frame.origin = CGPoint(x: PaddedSwitch.Padding, y: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // A helper class for settings with a UISwitch. // Takes and optional settingsDidChange callback and status text. class BoolSetting: Setting { let prefKey: String? // Sometimes a subclass will manage its own pref setting. In that case the prefkey will be nil fileprivate let prefs: Prefs fileprivate let defaultValue: Bool fileprivate let settingDidChange: ((Bool) -> Void)? fileprivate let statusText: NSAttributedString? init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, attributedTitleText: NSAttributedString, attributedStatusText: NSAttributedString? = nil, settingDidChange: ((Bool) -> Void)? = nil) { self.prefs = prefs self.prefKey = prefKey self.defaultValue = defaultValue self.settingDidChange = settingDidChange self.statusText = attributedStatusText super.init(title: attributedTitleText) } convenience init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) { var statusTextAttributedString: NSAttributedString? if let statusTextString = statusText { statusTextAttributedString = NSAttributedString(string: statusTextString, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewHeaderTextColor]) } self.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, attributedTitleText: NSAttributedString(string: titleText, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]), attributedStatusText: statusTextAttributedString, settingDidChange: settingDidChange) } override var status: NSAttributedString? { return statusText } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) let control = UISwitch() control.onTintColor = UIConstants.SystemBlueColor control.addTarget(self, action: #selector(BoolSetting.switchValueChanged(_:)), for: UIControlEvents.valueChanged) displayBool(control) if let title = title { if let status = status { control.accessibilityLabel = "\(title.string), \(status.string)" } else { control.accessibilityLabel = title.string } cell.accessibilityLabel = nil } cell.accessoryView = PaddedSwitch(switchView: control) cell.selectionStyle = .none } @objc func switchValueChanged(_ control: UISwitch) { writeBool(control) settingDidChange?(control.isOn) } // These methods allow a subclass to control how the pref is saved func displayBool(_ control: UISwitch) { guard let key = prefKey else { return } control.isOn = prefs.boolForKey(key) ?? defaultValue } func writeBool(_ control: UISwitch) { guard let key = prefKey else { return } prefs.setBool(control.isOn, forKey: key) } } /// A helper class for a setting backed by a UITextField. /// This takes an optional settingIsValid and settingDidChange callback /// If settingIsValid returns false, the Setting will not change and the text remains red. class StringSetting: Setting, UITextFieldDelegate { let prefKey: String fileprivate let Padding: CGFloat = 8 fileprivate let prefs: Prefs fileprivate let defaultValue: String? fileprivate let placeholder: String fileprivate let settingDidChange: ((String?) -> Void)? fileprivate let settingIsValid: ((String?) -> Bool)? let textField = UITextField() init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) { self.prefs = prefs self.prefKey = prefKey self.defaultValue = defaultValue self.settingDidChange = settingDidChange self.settingIsValid = isValueValid self.placeholder = placeholder super.init() self.accessibilityIdentifier = accessibilityIdentifier } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if let id = accessibilityIdentifier { textField.accessibilityIdentifier = id + "TextField" } textField.placeholder = placeholder textField.textAlignment = .center textField.delegate = self textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) cell.isUserInteractionEnabled = true cell.accessibilityTraits = UIAccessibilityTraitNone cell.contentView.addSubview(textField) textField.snp.makeConstraints { make in make.height.equalTo(44) make.trailing.equalTo(cell.contentView).offset(-Padding) make.leading.equalTo(cell.contentView).offset(Padding) } textField.text = prefs.stringForKey(prefKey) ?? defaultValue textFieldDidChange(textField) } override func onClick(_ navigationController: UINavigationController?) { textField.becomeFirstResponder() } fileprivate func isValid(_ value: String?) -> Bool { guard let test = settingIsValid else { return true } return test(prepareValidValue(userInput: value)) } /// This gives subclasses an opportunity to treat the user input string /// before it is saved or tested. /// Default implementation does nothing. func prepareValidValue(userInput value: String?) -> String? { return value } @objc func textFieldDidChange(_ textField: UITextField) { let color = isValid(textField.text) ? UIConstants.TableViewRowTextColor : UIConstants.DestructiveRed textField.textColor = color } @objc func textFieldShouldReturn(_ textField: UITextField) -> Bool { return isValid(textField.text) } @objc func textFieldDidEndEditing(_ textField: UITextField) { let text = textField.text if !isValid(text) { return } if let text = prepareValidValue(userInput: text) { prefs.setString(text, forKey: prefKey) } else { prefs.removeObjectForKey(prefKey) } // Call settingDidChange with text or nil. settingDidChange?(text) } } class CheckmarkSetting: Setting { let onChanged: () -> Void let isEnabled: () -> Bool private let subtitle: NSAttributedString? override var status: NSAttributedString? { return subtitle } init(title: NSAttributedString, subtitle: NSAttributedString?, accessibilityIdentifier: String? = nil, isEnabled: @escaping () -> Bool, onChanged: @escaping () -> Void) { self.subtitle = subtitle self.onChanged = onChanged self.isEnabled = isEnabled super.init(title: title) self.accessibilityIdentifier = accessibilityIdentifier } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.accessoryType = isEnabled() ? .checkmark : .none cell.selectionStyle = .none } override func onClick(_ navigationController: UINavigationController?) { // Force editing to end for any focused text fields so they can finish up validation first. navigationController?.view.endEditing(true) if !isEnabled() { onChanged() } } } /// A helper class for a setting backed by a UITextField. /// This takes an optional isEnabled and mandatory onClick callback /// isEnabled is called on each tableview.reloadData. If it returns /// false then the 'button' appears disabled. class ButtonSetting: Setting { let onButtonClick: (UINavigationController?) -> Void let destructive: Bool let isEnabled: (() -> Bool)? init(title: NSAttributedString?, destructive: Bool = false, accessibilityIdentifier: String, isEnabled: (() -> Bool)? = nil, onClick: @escaping (UINavigationController?) -> Void) { self.onButtonClick = onClick self.destructive = destructive self.isEnabled = isEnabled super.init(title: title) self.accessibilityIdentifier = accessibilityIdentifier } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if isEnabled?() ?? true { cell.textLabel?.textColor = destructive ? UIConstants.DestructiveRed : UIConstants.HighlightBlue } else { cell.textLabel?.textColor = UIConstants.TableViewDisabledRowTextColor } cell.textLabel?.textAlignment = NSTextAlignment.center cell.accessibilityTraits = UIAccessibilityTraitButton cell.selectionStyle = .none } override func onClick(_ navigationController: UINavigationController?) { // Force editing to end for any focused text fields so they can finish up validation first. navigationController?.view.endEditing(true) if isEnabled?() ?? true { onButtonClick(navigationController) } } } // A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to // the fxAccount happen. class AccountSetting: Setting, FxAContentViewControllerDelegate { unowned var settings: SettingsTableViewController var profile: Profile { return settings.profile } override var title: NSAttributedString? { return nil } init(settings: SettingsTableViewController) { self.settings = settings super.init(title: nil) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) if settings.profile.getAccount() != nil { cell.selectionStyle = .none } } override var accessoryType: UITableViewCellAccessoryType { return .none } func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) { // This method will get called twice: once when the user signs in, and once // when the account is verified by email – on this device or another. // If the user hasn't dismissed the fxa content view controller, // then we should only do that (thus finishing the sign in/verification process) // once the account is verified. // By the time we get to here, we should be syncing or just about to sync in the // background, most likely from FxALoginHelper. if flags.verified { _ = settings.navigationController?.popToRootViewController(animated: true) // Reload the data to reflect the new Account immediately. settings.tableView.reloadData() // And start advancing the Account state in the background as well. settings.SELrefresh() } } func contentViewControllerDidCancel(_ viewController: FxAContentViewController) { NSLog("didCancel") _ = settings.navigationController?.popToRootViewController(animated: true) } } class WithAccountSetting: AccountSetting { override var hidden: Bool { return !profile.hasAccount() } } class WithoutAccountSetting: AccountSetting { override var hidden: Bool { return profile.hasAccount() } } @objc protocol SettingsDelegate: class { func settingsOpenURLInNewTab(_ url: URL) } // The base settings view controller. class SettingsTableViewController: UITableViewController { typealias SettingsGenerator = (SettingsTableViewController, SettingsDelegate?) -> [SettingSection] fileprivate let Identifier = "CellIdentifier" fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier" var settings = [SettingSection]() weak var settingsDelegate: SettingsDelegate? var profile: Profile! var tabManager: TabManager! var hasSectionSeparatorLine = true /// Used to calculate cell heights. fileprivate lazy var dummyToggleCell: UITableViewCell = { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "dummyCell") cell.accessoryView = UISwitch() return cell }() override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier) tableView.register(SettingsTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier) tableView.separatorColor = UIConstants.TableViewSeparatorColor tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 30)) tableView.estimatedRowHeight = 44 tableView.estimatedSectionHeaderHeight = 44 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) settings = generateSettings() NotificationCenter.default.addObserver(self, selector: #selector(SettingsTableViewController.SELsyncDidChangeState), name: NotificationProfileDidStartSyncing, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SettingsTableViewController.SELsyncDidChangeState), name: NotificationProfileDidFinishSyncing, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SettingsTableViewController.SELfirefoxAccountDidChange), name: NotificationFirefoxAccountChanged, object: nil) tableView.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) SELrefresh() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: NotificationProfileDidStartSyncing, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) } // Override to provide settings in subclasses func generateSettings() -> [SettingSection] { return [] } @objc fileprivate func SELsyncDidChangeState() { DispatchQueue.main.async { self.tableView.reloadData() } } @objc fileprivate func SELrefresh() { // Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app. if let account = self.profile.getAccount() { account.advance().upon { state in DispatchQueue.main.async { () -> Void in self.tableView.reloadData() } } } else { self.tableView.reloadData() } } @objc func SELfirefoxAccountDidChange() { self.tableView.reloadData() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = settings[indexPath.section] if let setting = section[indexPath.row] { var cell: UITableViewCell! if let _ = setting.status { // Work around http://stackoverflow.com/a/9999821 and http://stackoverflow.com/a/25901083 by using a new cell. // I could not make any setNeedsLayout solution work in the case where we disconnect and then connect a new account. // Be aware that dequeing and then ignoring a cell appears to cause issues; only deque a cell if you're going to return it. cell = UITableViewCell(style: setting.style, reuseIdentifier: nil) } else { cell = tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath) } setting.onConfigureCell(cell) return cell } return tableView.dequeueReusableCell(withIdentifier: Identifier, for: indexPath) } override func numberOfSections(in tableView: UITableView) -> Int { return settings.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let section = settings[section] return section.count } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView let sectionSetting = settings[section] if let sectionTitle = sectionSetting.title?.string { headerView.titleLabel.text = sectionTitle.uppercased() } // Hide the top border for the top section to avoid having a double line at the top if section == 0 || !hasSectionSeparatorLine { headerView.showTopBorder = false } else { headerView.showTopBorder = true } return headerView } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let sectionSetting = settings[section] guard let sectionFooter = sectionSetting.footerTitle?.string else { return nil } let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView footerView.titleLabel.text = sectionFooter footerView.titleAlignment = .top footerView.showBottomBorder = false return footerView } // To hide a footer dynamically requires returning nil from viewForFooterInSection // and setting the height to zero. // However, we also want the height dynamically calculated, there is a magic constant // for that: `UITableViewAutomaticDimension`. override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let sectionSetting = settings[section] if let _ = sectionSetting.footerTitle?.string { return UITableViewAutomaticDimension } return 0 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let section = settings[indexPath.section] // Workaround for calculating the height of default UITableViewCell cells with a subtitle under // the title text label. if let setting = section[indexPath.row], setting is BoolSetting && setting.status != nil { return calculateStatusCellHeightForSetting(setting) } if let setting = section[indexPath.row], let height = setting.cellHeight { return height } return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let section = settings[indexPath.section] if let setting = section[indexPath.row], setting.enabled { setting.onClick(navigationController) } } fileprivate func calculateStatusCellHeightForSetting(_ setting: Setting) -> CGFloat { dummyToggleCell.layoutSubviews() let topBottomMargin: CGFloat = 10 let width = dummyToggleCell.contentView.frame.width - 2 * dummyToggleCell.separatorInset.left return heightForLabel(dummyToggleCell.textLabel!, width: width, text: setting.title?.string) + heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: setting.status?.string) + 2 * topBottomMargin } fileprivate func heightForLabel(_ label: UILabel, width: CGFloat, text: String?) -> CGFloat { guard let text = text else { return 0 } let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let attrs = [NSFontAttributeName: label.font as Any] let boundingRect = NSString(string: text).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrs, context: nil) return boundingRect.height } } struct SettingsTableSectionHeaderFooterViewUX { static let titleHorizontalPadding: CGFloat = 15 static let titleVerticalPadding: CGFloat = 6 static let titleVerticalLongPadding: CGFloat = 20 } class SettingsTableSectionHeaderFooterView: UITableViewHeaderFooterView { enum TitleAlignment { case top case bottom } var titleAlignment: TitleAlignment = .bottom { didSet { remakeTitleAlignmentConstraints() } } var showTopBorder: Bool = true { didSet { topBorder.isHidden = !showTopBorder } } var showBottomBorder: Bool = true { didSet { bottomBorder.isHidden = !showBottomBorder } } lazy var titleLabel: UILabel = { var headerLabel = UILabel() headerLabel.textColor = UIConstants.TableViewHeaderTextColor headerLabel.font = UIFont.systemFont(ofSize: 12.0, weight: UIFontWeightRegular) headerLabel.numberOfLines = 0 return headerLabel }() fileprivate lazy var topBorder: UIView = { let topBorder = UIView() topBorder.backgroundColor = UIConstants.SeparatorColor return topBorder }() fileprivate lazy var bottomBorder: UIView = { let bottomBorder = UIView() bottomBorder.backgroundColor = UIConstants.SeparatorColor return bottomBorder }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor addSubview(titleLabel) addSubview(topBorder) addSubview(bottomBorder) setupInitialConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupInitialConstraints() { bottomBorder.snp.makeConstraints { make in make.bottom.left.right.equalTo(self) make.height.equalTo(0.5) } topBorder.snp.makeConstraints { make in make.top.left.right.equalTo(self) make.height.equalTo(0.5) } remakeTitleAlignmentConstraints() } override func prepareForReuse() { super.prepareForReuse() showTopBorder = true showBottomBorder = true titleLabel.text = nil titleAlignment = .bottom } fileprivate func remakeTitleAlignmentConstraints() { switch titleAlignment { case .top: titleLabel.snp.remakeConstraints { make in make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding) make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding) make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding) } case .bottom: titleLabel.snp.remakeConstraints { make in make.left.right.equalTo(self).inset(SettingsTableSectionHeaderFooterViewUX.titleHorizontalPadding) make.bottom.equalTo(self).offset(-SettingsTableSectionHeaderFooterViewUX.titleVerticalPadding) make.top.equalTo(self).offset(SettingsTableSectionHeaderFooterViewUX.titleVerticalLongPadding) } } } }
mpl-2.0
3dc2c816543f3ea0b90e5287608c5dc9
37.77038
304
0.679061
5.48539
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/SkeletonView/Sources/Extensions/UIView+Frame.swift
2
1906
// // UIView+Frame.swift // SkeletonView-iOS // // Created by Juanpe Catalán on 06/11/2017. // Copyright © 2017 SkeletonView. All rights reserved. // import UIKit // MARK: Frame extension UIView { var maxBoundsEstimated: CGRect { if let parentStackView = (superview as? UIStackView) { var origin: CGPoint = .zero switch parentStackView.alignment { case .center: origin.x = maxWidthEstimated / 2 case .trailing: origin.x = maxWidthEstimated default: break } return CGRect(origin: origin, size: maxSizeEstimated) } return CGRect(origin: .zero, size: maxSizeEstimated) } var maxSizeEstimated: CGSize { return CGSize(width: maxWidthEstimated, height: maxHeightEstimated) } var maxWidthEstimated: CGFloat { let constraintsWidth = nonContentSizeLayoutConstraints.filter({ $0.firstAttribute == NSLayoutConstraint.Attribute.width }) return max(between: frame.size.width, andContantsOf: constraintsWidth) } var maxHeightEstimated: CGFloat { let constraintsHeight = nonContentSizeLayoutConstraints.filter({ $0.firstAttribute == NSLayoutConstraint.Attribute.height }) return max(between: frame.size.height, andContantsOf: constraintsHeight) } private func max(between value: CGFloat, andContantsOf constraints: [NSLayoutConstraint]) -> CGFloat { let max = constraints.reduce(value, { max, constraint in var tempMax = max if constraint.constant > tempMax { tempMax = constraint.constant } return tempMax }) return max } var nonContentSizeLayoutConstraints: [NSLayoutConstraint] { return constraints.filter({ "\(type(of: $0))" != "NSContentSizeLayoutConstraint" }) } }
mit
50a6303e213b881a71adc9c4419d7c45
33
132
0.639181
4.869565
false
false
false
false
tripleCC/BreakOutToRefresh
PullToRefreshDemo/BreakOutToRefreshView.swift
1
13338
// // BreakOutToRefreshView.swift // PullToRefreshDemo // // Created by dasdom on 17.01.15. // // Copyright (c) 2015 Dominik Hauser <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import SpriteKit @objc public protocol BreakOutToRefreshDelegate: class { func refreshViewDidRefresh(refreshView: BreakOutToRefreshView) } public class BreakOutToRefreshView: SKView { private let sceneHeight = CGFloat(100) private let breakOutScene: BreakOutScene private unowned let scrollView: UIScrollView public weak var delegate: BreakOutToRefreshDelegate? public var forceEnd = false public var isRefreshing = false private var isDragging = false private var isVisible = false public var scenebackgroundColor: UIColor { didSet { breakOutScene.scenebackgroundColor = scenebackgroundColor } } public var paddleColor: UIColor { didSet { breakOutScene.paddleColor = paddleColor } } public var ballColor: UIColor { didSet { breakOutScene.ballColor = ballColor } } public var blockColors: [UIColor] { didSet { breakOutScene.blockColors = blockColors } } public override init(frame: CGRect) { assert(false, "Use init(scrollView:) instead.") breakOutScene = BreakOutScene(size: frame.size) scrollView = UIScrollView() scenebackgroundColor = UIColor.whiteColor() paddleColor = UIColor.whiteColor() ballColor = UIColor.whiteColor() blockColors = [UIColor.whiteColor()] super.init(frame: frame) } public init(scrollView inScrollView: UIScrollView) { let frame = CGRect(x: 0.0, y: -sceneHeight, width: inScrollView.frame.size.width, height: sceneHeight) breakOutScene = BreakOutScene(size: frame.size) self.scrollView = inScrollView scenebackgroundColor = UIColor.whiteColor() paddleColor = UIColor.grayColor() ballColor = UIColor.blackColor() blockColors = [UIColor(white: 0.2, alpha: 1.0), UIColor(white: 0.4, alpha: 1.0), UIColor(white: 0.6, alpha: 1.0)] breakOutScene.scenebackgroundColor = scenebackgroundColor breakOutScene.paddleColor = paddleColor breakOutScene.ballColor = ballColor breakOutScene.blockColors = blockColors super.init(frame: frame) layer.borderColor = UIColor.grayColor().CGColor layer.borderWidth = 1.0 presentScene(StartScene(size: frame.size)) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func beginRefreshing() { isRefreshing = true let doors = SKTransition.doorsOpenVerticalWithDuration(0.5) presentScene(breakOutScene, transition: doors) breakOutScene.updateLabel("Loading...") UIView.animateWithDuration(0.4, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in self.scrollView.contentInset.top += self.sceneHeight }) { (_) -> Void in if self.scrollView.contentOffset.y < -60 { self.breakOutScene.reset() self.breakOutScene.start() } self.isVisible = true } } public func endRefreshing() { if (!isDragging || forceEnd) && isVisible { self.isVisible = false UIView.animateWithDuration(0.4, delay: 0, options: .CurveEaseInOut, animations: { () -> Void in self.scrollView.contentInset.top -= self.sceneHeight }) { (_) -> Void in self.isRefreshing = false self.presentScene(StartScene(size: self.frame.size)) } } else { breakOutScene.updateLabel("Loading Finished") isRefreshing = false } } } extension BreakOutToRefreshView: UIScrollViewDelegate { public func scrollViewWillBeginDragging(scrollView: UIScrollView) { isDragging = true } public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { isDragging = false if !isRefreshing && scrollView.contentOffset.y + scrollView.contentInset.top < -sceneHeight { beginRefreshing() targetContentOffset.memory.y = -scrollView.contentInset.top delegate?.refreshViewDidRefresh(self) } if !isRefreshing { endRefreshing() } } public func scrollViewDidScroll(scrollView: UIScrollView) { let frameHeight = frame.size.height let yPosition = sceneHeight - (-scrollView.contentInset.top-scrollView.contentOffset.y)*2 breakOutScene.moveHandle(yPosition) } } class BreakOutScene: SKScene, SKPhysicsContactDelegate { let ballName = "ball" let paddleName = "paddle" let blockName = "block" let backgroundLabelName = "backgroundLabel" let ballCategory : UInt32 = 0x1 << 0 let backCategory : UInt32 = 0x1 << 1 let blockCategory : UInt32 = 0x1 << 2 let paddleCategory : UInt32 = 0x1 << 3 var contentCreated = false var isStarted = false var scenebackgroundColor: UIColor! var paddleColor: UIColor! var ballColor: UIColor! var blockColors: [UIColor]! override func didMoveToView(view: SKView) { super.didMoveToView(view) if !contentCreated { createSceneContents() contentCreated = true } } override func update(currentTime: NSTimeInterval) { let ball = self.childNodeWithName(ballName) as! SKSpriteNode! let maxSpeed: CGFloat = 600.0 let speed = sqrt(ball.physicsBody!.velocity.dx * ball.physicsBody!.velocity.dx + ball.physicsBody!.velocity.dy * ball.physicsBody!.velocity.dy) if speed > maxSpeed { ball.physicsBody!.linearDamping = 0.4 } else { ball.physicsBody!.linearDamping = 0.0 } } func createSceneContents() { physicsWorld.gravity = CGVectorMake(0.0, 0.0) physicsWorld.contactDelegate = self backgroundColor = scenebackgroundColor scaleMode = .AspectFit physicsBody = SKPhysicsBody(edgeLoopFromRect: frame) physicsBody?.restitution = 1.0 physicsBody?.friction = 0.0 name = "scene" let back = SKNode() back.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointMake(frame.size.width - 1, 0), toPoint: CGPointMake(frame.size.width - 1, frame.size.height)) back.physicsBody?.categoryBitMask = backCategory addChild(back) createLoadingLabelNode() let paddle = createPaddle() paddle.position = CGPoint(x: frame.size.width-30.0, y: CGRectGetMidY(frame)) addChild(paddle) createBall() createBlocks() } func createPaddle() -> SKSpriteNode { let paddle = SKSpriteNode(color: paddleColor, size: CGSize(width: 5, height: 30)) paddle.physicsBody = SKPhysicsBody(rectangleOfSize: paddle.size) paddle.physicsBody?.dynamic = false paddle.physicsBody?.restitution = 1.0 paddle.physicsBody?.friction = 0.0 paddle.name = paddleName return paddle } func createBlocks() { for i in 0..<3 { var color = blockColors.count > 0 ? blockColors[0] : UIColor(white: 0.2, alpha: 1.0) if i == 1 { color = blockColors.count > 1 ? blockColors[1] : UIColor(white: 0.4, alpha: 1.0) } else if i == 2 { color = blockColors.count > 2 ? blockColors[2] : UIColor(white: 0.6, alpha: 1.0) } for j in 0..<5 { let block = SKSpriteNode(color: color, size: CGSize(width: 5, height: 19)) block.position = CGPoint(x: 20+CGFloat(i)*6, y: CGFloat(j)*20 + 10) block.name = blockName block.physicsBody = SKPhysicsBody(rectangleOfSize: block.size) block.physicsBody?.categoryBitMask = blockCategory block.physicsBody?.allowsRotation = false block.physicsBody?.restitution = 1.0 block.physicsBody?.friction = 0.0 block.physicsBody?.dynamic = false addChild(block) } } } func removeBlocks() { var node = childNodeWithName(blockName) while (node != nil) { node?.removeFromParent() node = childNodeWithName(blockName) } } func createBall() { let ball = SKSpriteNode(color: ballColor, size: CGSize(width: 8, height: 8)) ball.position = CGPoint(x: frame.size.width - 30.0 - ball.size.width, y: CGRectGetHeight(frame)*CGFloat(arc4random())/CGFloat(UINT32_MAX)) ball.name = ballName ball.physicsBody = SKPhysicsBody(circleOfRadius: ceil(ball.size.width/2.0)) ball.physicsBody?.usesPreciseCollisionDetection = true ball.physicsBody?.categoryBitMask = ballCategory ball.physicsBody?.contactTestBitMask = blockCategory | paddleCategory | backCategory ball.physicsBody?.allowsRotation = false ball.physicsBody?.linearDamping = 0.0 ball.physicsBody?.restitution = 1.0 ball.physicsBody?.friction = 0.0 addChild(ball) } func removeBall() { if let ball = childNodeWithName(ballName) { ball.removeFromParent() } } func createLoadingLabelNode() { let loadingLabelNode = SKLabelNode(text: "Loading...") loadingLabelNode.fontColor = UIColor.lightGrayColor() loadingLabelNode.fontSize = 20 loadingLabelNode.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)) loadingLabelNode.name = backgroundLabelName addChild(loadingLabelNode) } func reset() { removeBlocks() createBlocks() removeBall() createBall() } func start() { isStarted = true let ball = childNodeWithName(ballName) ball?.physicsBody?.applyImpulse(CGVector(dx: -0.5, dy: 0.2)) } func updateLabel(text: String) { if let label: SKLabelNode = childNodeWithName(backgroundLabelName) as? SKLabelNode { label.text = text } } func moveHandle(value: CGFloat) { let paddle = childNodeWithName(paddleName) paddle?.position.y = value } func didEndContact(contact: SKPhysicsContact) { var ballBody: SKPhysicsBody? var otherBody: SKPhysicsBody? if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { ballBody = contact.bodyA otherBody = contact.bodyB } else { ballBody = contact.bodyB otherBody = contact.bodyA } if ((otherBody?.categoryBitMask ?? 0) == backCategory) { reset() start() } else if ballBody!.categoryBitMask & ballCategory != 0 { let minimalXVelocity = CGFloat(20.0) let minimalYVelocity = CGFloat(20.0) var velocity = ballBody!.velocity as CGVector if velocity.dx > -minimalXVelocity && velocity.dx <= 0 { velocity.dx = -minimalXVelocity-1 } else if velocity.dx > 0 && velocity.dx < minimalXVelocity { velocity.dx = minimalXVelocity+1 } if velocity.dy > -minimalYVelocity && velocity.dy <= 0 { velocity.dy = -minimalYVelocity-1 } else if velocity.dy > 0 && velocity.dy < minimalYVelocity { velocity.dy = minimalYVelocity+1 } ballBody?.velocity = velocity } if otherBody != nil && (otherBody!.categoryBitMask & blockCategory != 0) && otherBody!.categoryBitMask == blockCategory { otherBody!.node?.removeFromParent() if isGameWon() { reset() start() } } } func isGameWon() -> Bool { var numberOfBricks = 0 self.enumerateChildNodesWithName(blockName) { node, stop in numberOfBricks = numberOfBricks + 1 } return numberOfBricks == 0 } } class StartScene: SKScene { var contentCreated = false override func didMoveToView(view: SKView) { super.didMoveToView(view) if !contentCreated { createSceneContents() contentCreated = true } } func createSceneContents() { backgroundColor = SKColor.whiteColor() scaleMode = .AspectFit addChild(startLabelNode()) addChild(descriptionLabelNode()) } func startLabelNode() -> SKLabelNode { let startNode = SKLabelNode(text: "Pull to Break Out!") startNode.fontColor = UIColor.blackColor() startNode.fontSize = 20 startNode.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)) startNode.name = "start" return startNode } func descriptionLabelNode() -> SKLabelNode { let descriptionNode = SKLabelNode(text: "Scroll to move handle") descriptionNode.fontColor = UIColor.blackColor() descriptionNode.fontSize = 17 descriptionNode.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)-20) descriptionNode.name = "description" return descriptionNode } }
mit
f36412165e110f5215f9ac578f0a06e5
28.838926
151
0.690058
4.245067
false
false
false
false
shafiullakhan/Swift-Paper
Swift-Paper/Swift-Paper/BaseFlowLayout/CollectionViewCell.swift
1
955
// // CollectionViewCell.swift // Swift-Paper // // Created by Shaf on 8/5/15. // Copyright (c) 2015 Shaffiulla. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { var indexData: Int var cellSize: CGSize required init(coder aDecoder: NSCoder) { indexData = -1; cellSize = CGSizeZero super.init(coder: aDecoder) } override init(frame: CGRect) { indexData = -1; cellSize = CGSizeZero super.init(frame: frame); self.backgroundColor = UIColor.whiteColor(); self.layer.cornerRadius = 4; self.clipsToBounds = true; var backgroundView = UIImageView(image: UIImage(named: "2")) self.backgroundView = backgroundView; } func setIndex(index :Int, withSize size:CGSize){ self.indexData=index; self.cellSize=size; } func layout(){ } }
mit
b592bac44907b0abbffbfa5dad92d6a5
21.209302
68
0.596859
4.400922
false
false
false
false
natecook1000/swift
test/SILGen/cf_members.swift
2
14164
// RUN: %target-swift-emit-silgen -enable-sil-ownership -I %S/../IDE/Inputs/custom-modules %s -enable-objc-interop -I %S/Inputs/usr/include | %FileCheck %s import ImportAsMember func makeMetatype() -> Struct1.Type { return Struct1.self } // CHECK-LABEL: sil @$S10cf_members17importAsUnaryInityyF public func importAsUnaryInit() { // CHECK: function_ref @CCPowerSupplyCreateDangerous : $@convention(c) () -> @owned CCPowerSupply var a = CCPowerSupply(dangerous: ()) let f: (()) -> CCPowerSupply = CCPowerSupply.init(dangerous:) a = f(()) } // CHECK-LABEL: sil @$S10cf_members3foo{{[_0-9a-zA-Z]*}}F public func foo(_ x: Double) { // CHECK: bb0([[X:%.*]] : @trivial $Double): // CHECK: [[GLOBALVAR:%.*]] = global_addr @IAMStruct1GlobalVar // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBALVAR]] : $*Double // CHECK: [[ZZ:%.*]] = load [trivial] [[READ]] let zz = Struct1.globalVar // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBALVAR]] : $*Double // CHECK: assign [[ZZ]] to [[WRITE]] Struct1.globalVar = zz // CHECK: [[Z:%.*]] = project_box // CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: apply [[FN]]([[X]]) var z = Struct1(value: x) // The metatype expression should still be evaluated even if it isn't // used. // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$S10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[FN:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: apply [[FN]]([[X]]) z = makeMetatype().init(value: x) // CHECK: [[SELF_META:%.*]] = metatype $@thin Struct1.Type // CHECK: [[THUNK:%.*]] = function_ref @$SSo10IAMStruct1V5valueABSd_tcfCTcTO // CHECK: [[A:%.*]] = apply [[THUNK]]([[SELF_META]]) // CHECK: [[BORROWED_A:%.*]] = begin_borrow [[A]] // CHECK: [[A_COPY:%.*]] = copy_value [[BORROWED_A]] // CHECK: [[BORROWED_A2:%.*]] = begin_borrow [[A_COPY]] let a: (Double) -> Struct1 = Struct1.init(value:) // CHECK: apply [[BORROWED_A2]]([[X]]) // CHECK: destroy_value [[A_COPY]] // CHECK: end_borrow [[BORROWED_A]] from [[A]] z = a(x) // TODO: Support @convention(c) references that only capture thin metatype // let b: @convention(c) (Double) -> Struct1 = Struct1.init(value:) // z = b(x) // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1 // CHECK: [[FN:%.*]] = function_ref @IAMStruct1InvertInPlace // CHECK: apply [[FN]]([[WRITE]]) z.invert() // CHECK: [[WRITE:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[WRITE]] // CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] : // CHECK: [[FN:%.*]] = function_ref @IAMStruct1Rotate : $@convention(c) (@in Struct1, Double) -> Struct1 // CHECK: apply [[FN]]([[ZTMP]], [[X]]) z = z.translate(radians: x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME:@\$SSo10IAMStruct1V9translate7radiansABSd_tFTcTO]] // CHECK: [[C:%.*]] = apply [[THUNK]]([[ZVAL]]) // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[C_COPY:%.*]] = copy_value [[BORROWED_C]] // CHECK: [[BORROWED_C2:%.*]] = begin_borrow [[C_COPY]] let c: (Double) -> Struct1 = z.translate(radians:) // CHECK: apply [[BORROWED_C2]]([[X]]) // CHECK: destroy_value [[C_COPY]] // CHECK: end_borrow [[BORROWED_C]] from [[C]] z = c(x) // CHECK: [[THUNK:%.*]] = function_ref [[THUNK_NAME]] // CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]] // CHECK: [[BORROW:%.*]] = begin_borrow [[THICK]] // CHECK: [[COPY:%.*]] = copy_value [[BORROW]] let d: (Struct1) -> (Double) -> Struct1 = Struct1.translate(radians:) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[BORROW_COPY:%.*]] = begin_borrow [[COPY]] // CHECK: apply [[BORROW_COPY]]([[ZVAL]]) // CHECK: destroy_value [[COPY]] z = d(z)(x) // TODO: If we implement SE-0042, this should thunk the value Struct1 param // to a const* param to the underlying C symbol. // // let e: @convention(c) (Struct1, Double) -> Struct1 // = Struct1.translate(radians:) // z = e(z, x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[FN:%.*]] = function_ref @IAMStruct1Scale // CHECK: apply [[FN]]([[ZVAL]], [[X]]) z = z.scale(x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[THUNK:%.*]] = function_ref @$SSo10IAMStruct1V5scaleyABSdFTcTO // CHECK: [[F:%.*]] = apply [[THUNK]]([[ZVAL]]) // CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]] // CHECK: [[F_COPY:%.*]] = copy_value [[BORROWED_F]] // CHECK: [[BORROWED_F2:%.*]] = begin_borrow [[F_COPY]] let f = z.scale // CHECK: apply [[BORROWED_F2]]([[X]]) // CHECK: destroy_value [[F_COPY]] // CHECK: end_borrow [[BORROWED_F]] from [[F]] z = f(x) // CHECK: [[THUNK:%.*]] = function_ref @$SSo10IAMStruct1V5scaleyABSdFTcTO // CHECK: thin_to_thick_function [[THUNK]] let g = Struct1.scale // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] z = g(z)(x) // TODO: If we implement SE-0042, this should directly reference the // underlying C function. // let h: @convention(c) (Struct1, Double) -> Struct1 = Struct1.scale // z = h(z, x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: store [[ZVAL]] to [trivial] [[ZTMP:%.*]] : // CHECK: [[ZVAL_2:%.*]] = load [trivial] [[ZTMP]] // CHECK: store [[ZVAL_2]] to [trivial] [[ZTMP_2:%.*]] : // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetRadius : $@convention(c) (@in Struct1) -> Double // CHECK: apply [[GET]]([[ZTMP_2]]) _ = z.radius // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetRadius : $@convention(c) (Struct1, Double) -> () // CHECK: apply [[SET]]([[ZVAL]], [[X]]) z.radius = x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetAltitude : $@convention(c) (Struct1) -> Double // CHECK: apply [[GET]]([[ZVAL]]) _ = z.altitude // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[Z]] : $*Struct1 // CHECK: [[SET:%.*]] = function_ref @IAMStruct1SetAltitude : $@convention(c) (@inout Struct1, Double) -> () // CHECK: apply [[SET]]([[WRITE]], [[X]]) z.altitude = x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[GET:%.*]] = function_ref @IAMStruct1GetMagnitude : $@convention(c) (Struct1) -> Double // CHECK: apply [[GET]]([[ZVAL]]) _ = z.magnitude // CHECK: [[FN:%.*]] = function_ref @IAMStruct1StaticMethod // CHECK: apply [[FN]]() var y = Struct1.staticMethod() // CHECK: [[SELF:%.*]] = metatype // CHECK: [[THUNK:%.*]] = function_ref @$SSo10IAMStruct1V12staticMethods5Int32VyFZTcTO // CHECK: [[I:%.*]] = apply [[THUNK]]([[SELF]]) // CHECK: [[BORROWED_I:%.*]] = begin_borrow [[I]] // CHECK: [[I_COPY:%.*]] = copy_value [[BORROWED_I]] // CHECK: [[BORROWED_I2:%.*]] = begin_borrow [[I_COPY]] let i = Struct1.staticMethod // CHECK: apply [[BORROWED_I2]]() // CHECK: destroy_value [[I_COPY]] // CHECK: end_borrow [[BORROWED_I]] from [[I]] y = i() // TODO: Support @convention(c) references that only capture thin metatype // let j: @convention(c) () -> Int32 = Struct1.staticMethod // y = j() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty // CHECK: apply [[GET]]() _ = Struct1.property // CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty // CHECK: apply [[SET]](%{{[0-9]+}}) Struct1.property = y // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty // CHECK: apply [[GET]]() _ = Struct1.getOnlyProperty // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$S10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetProperty // CHECK: apply [[GET]]() _ = makeMetatype().property // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$S10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[SET:%.*]] = function_ref @IAMStruct1StaticSetProperty // CHECK: apply [[SET]](%{{[0-9]+}}) makeMetatype().property = y // CHECK: [[MAKE_METATYPE:%.*]] = function_ref @$S10cf_members12makeMetatype{{[_0-9a-zA-Z]*}}F // CHECK: apply [[MAKE_METATYPE]]() // CHECK: [[GET:%.*]] = function_ref @IAMStruct1StaticGetOnlyProperty // CHECK: apply [[GET]]() _ = makeMetatype().getOnlyProperty // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesLast : $@convention(c) (Double, Struct1) -> () // CHECK: apply [[FN]]([[X]], [[ZVAL]]) z.selfComesLast(x: x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] let k: (Double) -> () = z.selfComesLast(x:) k(x) let l: (Struct1) -> (Double) -> () = Struct1.selfComesLast(x:) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] l(z)(x) // TODO: If we implement SE-0042, this should thunk to reorder the arguments. // let m: @convention(c) (Struct1, Double) -> () = Struct1.selfComesLast(x:) // m(z, x) // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]] : $*Struct1 // CHECK: [[ZVAL:%.*]] = load [trivial] [[READ]] // CHECK: [[FN:%.*]] = function_ref @IAMStruct1SelfComesThird : $@convention(c) (Int32, Float, Struct1, Double) -> () // CHECK: apply [[FN]]({{.*}}, {{.*}}, [[ZVAL]], [[X]]) z.selfComesThird(a: y, b: 0, x: x) let n: (Int32, Float, Double) -> () = z.selfComesThird(a:b:x:) n(y, 0, x) let o: (Struct1) -> (Int32, Float, Double) -> () = Struct1.selfComesThird(a:b:x:) o(z)(y, 0, x) // TODO: If we implement SE-0042, this should thunk to reorder the arguments. // let p: @convention(c) (Struct1, Int, Float, Double) -> () // = Struct1.selfComesThird(a:b:x:) // p(z, y, 0, x) } // CHECK: } // end sil function '$S10cf_members3foo{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil shared [serializable] [thunk] @$SSo10IAMStruct1V5valueABSd_tcfCTO // CHECK: bb0([[X:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $@thin Struct1.Type): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1CreateSimple // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil shared [serializable] [thunk] @$SSo10IAMStruct1V9translate7radiansABSd_tFTO // CHECK: bb0([[X:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $Struct1): // CHECK: store [[SELF]] to [trivial] [[TMP:%.*]] : // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Rotate // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[TMP]], [[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil shared [serializable] [thunk] @$SSo10IAMStruct1V5scaleyABSdFTO // CHECK: bb0([[X:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1Scale // CHECK: [[RET:%.*]] = apply [[CFUNC]]([[SELF]], [[X]]) // CHECK: return [[RET]] // CHECK-LABEL: sil shared [serializable] [thunk] @$SSo10IAMStruct1V12staticMethods5Int32VyFZTO // CHECK: bb0([[SELF:%.*]] : @trivial $@thin Struct1.Type): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1StaticMethod // CHECK: [[RET:%.*]] = apply [[CFUNC]]() // CHECK: return [[RET]] // CHECK-LABEL: sil shared [serializable] [thunk] @$SSo10IAMStruct1V13selfComesLast1xySd_tFTO // CHECK: bb0([[X:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesLast // CHECK: apply [[CFUNC]]([[X]], [[SELF]]) // CHECK-LABEL: sil shared [serializable] [thunk] @$SSo10IAMStruct1V14selfComesThird1a1b1xys5Int32V_SfSdtFTO // CHECK: bb0([[X:%.*]] : @trivial $Int32, [[Y:%.*]] : @trivial $Float, [[Z:%.*]] : @trivial $Double, [[SELF:%.*]] : @trivial $Struct1): // CHECK: [[CFUNC:%.*]] = function_ref @IAMStruct1SelfComesThird // CHECK: apply [[CFUNC]]([[X]], [[Y]], [[SELF]], [[Z]]) // CHECK-LABEL: sil @$S10cf_members3bar{{[_0-9a-zA-Z]*}}F public func bar(_ x: Double) { // CHECK: function_ref @CCPowerSupplyCreate : $@convention(c) (Double) -> @owned CCPowerSupply let ps = CCPowerSupply(watts: x) // CHECK: function_ref @CCRefrigeratorCreate : $@convention(c) (CCPowerSupply) -> @owned CCRefrigerator let fridge = CCRefrigerator(powerSupply: ps) // CHECK: function_ref @CCRefrigeratorOpen : $@convention(c) (CCRefrigerator) -> () fridge.open() // CHECK: function_ref @CCRefrigeratorGetPowerSupply : $@convention(c) (CCRefrigerator) -> @autoreleased CCPowerSupply let ps2 = fridge.powerSupply // CHECK: function_ref @CCRefrigeratorSetPowerSupply : $@convention(c) (CCRefrigerator, CCPowerSupply) -> () fridge.powerSupply = ps2 let a: (Double) -> CCPowerSupply = CCPowerSupply.init(watts:) let _ = a(x) let b: (CCRefrigerator) -> () -> () = CCRefrigerator.open b(fridge)() let c = fridge.open c() } // CHECK-LABEL: sil @$S10cf_members28importGlobalVarsAsProperties{{[_0-9a-zA-Z]*}}F public func importGlobalVarsAsProperties() -> (Double, CCPowerSupply, CCPowerSupply?) { // CHECK: global_addr @kCCPowerSupplyDC // CHECK: global_addr @kCCPowerSupplyAC // CHECK: global_addr @kCCPowerSupplyDefaultPower return (CCPowerSupply.defaultPower, CCPowerSupply.AC, CCPowerSupply.DC) }
apache-2.0
6d8dddc2fb3f9f588b52e5e205e9af92
45.900662
155
0.586204
3.352426
false
false
false
false
J3D1-WARR10R/WikiRaces
WKRKit/WKRKit/Game/WKRRace.swift
2
3889
// // WKRRace.swift // WKRKit // // Created by Andrew Finke on 8/5/17. // Copyright © 2017 Andrew Finke. All rights reserved. // import WKRUIKit internal struct WKRRace { // MARK: - Properties private let isSolo: Bool /// The race's bonus points internal var bonusPoints = 0 /// The end page for the race private let finalPage: WKRPage /// Fetches all the links that link to the page. Torn down at the end of the race. internal var linkedPagesFetcher: WKRLinkedPagesFetcher? = WKRLinkedPagesFetcher() /// The players that have participated in the race internal private(set) var players = [WKRPlayer]() // MARK: - Initialization internal init(config: WKRRaceConfig, isSolo: Bool) { self.isSolo = isSolo finalPage = config.endingPage linkedPagesFetcher?.start(for: finalPage) } // MARK: - Player Updates /// Update the race's players /// /// - Parameter player: The update player internal mutating func playerUpdated(_ player: WKRPlayer) { if let index = players.firstIndex(of: player) { players[index] = player } else { players.append(player) } } // MARK: - Pages /// Attributes for a Wikipedia page relating to the race. Used for detecting if the player found the page /// or is other players should show "X is close" message. /// /// - Parameter page: The page to check againts /// - Returns: Tuple with found page and link on page values. internal func attributes(for page: WKRPage) -> (foundPage: Bool, linkOnPage: Bool) { var adjustedURL = page.url // Adjust for links to sections if adjustedURL.absoluteString.contains("#") { let components = adjustedURL.absoluteString.components(separatedBy: "#") if components.count == 2, let newURL = URL(string: components[0]) { adjustedURL = newURL } } if page == finalPage { return (true, false) } else if adjustedURL == finalPage.url { return (true, false) } else if page.title == finalPage.title { return (true, false) } else if linkedPagesFetcher?.foundLinkOn(page) ?? false { return (false, true) } return (false, false) } // MARK: - End Race Helpers /// Calculates how my points each place should receive for the race. Every player that found the article /// gets points for how many players they did better then. All players also get the race bonus points /// if there are any. /// /// - Returns: Each player's points in a dictionary internal func calculatePoints() -> [WKRPlayerProfile: Int] { var times = [WKRPlayer: Int]() for player in players.filter({ $0.state == .foundPage }) { times[player] = player.raceHistory?.duration } var points = [WKRPlayerProfile: Int]() let positions = times.keys.sorted { (lhs, rhs) -> Bool in return times[lhs] ?? 0 < times[rhs] ?? 0 } for (index, player) in positions.enumerated() { points[player.profile] = players.count - index - 1 + bonusPoints } return points } /// Check if the race should end. The race should end when there is one or less /// than one player still racing or when >= 3 players have finished /// /// - Returns: If the race should end internal func shouldEnd() -> Bool { if isSolo { return players.first?.state != .racing } else { return (players.filter({ $0.state == .racing }).count <= 1 && players.filter({ $0.state != .connecting }).count > 1) || players.filter({ $0.state == .foundPage }).count >= WKRKitConstants.current.maxFoundPagePlayers } } }
mit
bdbe052a7db553a08f936f156a11851f
33.105263
114
0.604167
4.272527
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/TouchBarStickerItemView.swift
1
3900
// // TouchBarThumbailItemView.swift // Telegram // // Created by Mikhail Filimonov on 14/09/2018. // Copyright © 2018 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit import TelegramCore import TGUIKit @available(OSX 10.12.2, *) class TouchBarStickerItemView: NSScrubberItemView { private var animatedSticker:MediaAnimatedStickerView? private var imageView: TransformImageView? private let fetchDisposable = MetaDisposable() private(set) var file: TelegramMediaFile? required override init(frame frameRect: NSRect) { super.init(frame: frameRect) // let gesture = NSPressGestureRecognizer(target: self, action: #selector(pressGesture)) // gesture.minimumPressDuration = 0.5 // self.addGestureRecognizer(gesture) } var quickPreview: QuickPreviewMedia? { if let file = file { let reference = file.stickerReference != nil ? FileMediaReference.stickerPack(stickerPack: file.stickerReference!, media: file) : FileMediaReference.standalone(media: file) if file.isAnimatedSticker { return .file(reference, AnimatedStickerPreviewModalView.self) } else { return .file(reference, StickerPreviewModalView.self) } } return nil } func update(context: AccountContext, file: TelegramMediaFile, animated: Bool) { self.file = file if file.isAnimatedSticker, animated { self.imageView?.removeFromSuperview() self.imageView = nil if self.animatedSticker == nil { self.animatedSticker = MediaAnimatedStickerView(frame: NSZeroRect) addSubview(self.animatedSticker!) } guard let animatedSticker = self.animatedSticker else { return } animatedSticker.update(with: file, size: NSMakeSize(30, 30), context: context, parent: nil, table: nil, parameters: nil, animated: false, positionFlags: nil, approximateSynchronousValue: false) } else { self.animatedSticker?.removeFromSuperview() self.animatedSticker = nil if self.imageView == nil { self.imageView = TransformImageView() addSubview(self.imageView!) } guard let imageView = self.imageView else { return } let dimensions = file.dimensions?.size ?? frame.size let imageSize = NSMakeSize(30, 30) let arguments = TransformImageArguments(corners: ImageCorners(), imageSize: dimensions.aspectFitted(imageSize), boundingSize: imageSize, intrinsicInsets: NSEdgeInsets()) imageView.setSignal(signal: cachedMedia(media: file, arguments: arguments, scale: backingScaleFactor), clearInstantly: true) imageView.setSignal(chatMessageSticker(postbox: context.account.postbox, file: stickerPackFileReference(file), small: true, scale: backingScaleFactor, fetched: true), cacheImage: { result in cacheMedia(result, media: file, arguments: arguments, scale: System.backingScale) }) imageView.set(arguments: arguments) imageView.setFrameSize(imageSize) } // fetchDisposable.set(fileInteractiveFetched(account: account, fileReference: FileMediaReference.stickerPack(stickerPack: file.stickerReference!, media: file)).start()) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateLayer() { // layer?.backgroundColor = NSColor.controlColor.cgColor } deinit { fetchDisposable.dispose() } override func layout() { super.layout() imageView?.center() animatedSticker?.center() } }
gpl-2.0
3c3ea0c283cdcbf45d0502ca308a4b4f
37.60396
205
0.645294
5.164238
false
false
false
false
novifinancial/serde-reflection
serde-generate/runtime/swift/Sources/Serde/BinarySerializer.swift
1
4021
// Copyright (c) Facebook, Inc. and its affiliates. import Foundation public class BinarySerializer: Serializer { var output: [UInt8] private var containerDepthBudget: Int public init(maxContainerDepth: Int) { output = [] output.reserveCapacity(64) containerDepthBudget = maxContainerDepth } public func increase_container_depth() throws { if containerDepthBudget == 0 { throw SerializationError.invalidValue(issue: "Exceeded maximum container depth") } containerDepthBudget -= 1 } public func decrease_container_depth() { containerDepthBudget += 1 } public func serialize_char(value _: Character) throws { throw SerializationError.invalidValue(issue: "Not implemented: char serialization") } public func serialize_f32(value: Float) throws { throw SerializationError.invalidValue(issue: "Not implemented: f32 serialization") } public func serialize_f64(value: Double) throws { throw SerializationError.invalidValue(issue: "Not implemented: f64 serialization") } public func get_bytes() -> [UInt8] { return output } public func serialize_str(value: String) throws { try serialize_bytes(value: Array(value.utf8)) } public func serialize_bytes(value: [UInt8]) throws { try serialize_len(value: value.count) output.append(contentsOf: value) } public func serialize_bool(value: Bool) throws { writeByte(value ? 1 : 0) } public func serialize_unit(value _: Unit) throws {} func writeByte(_ value: UInt8) { output.append(value) } public func serialize_u8(value: UInt8) throws { writeByte(value) } public func serialize_u16(value: UInt16) throws { writeByte(UInt8(truncatingIfNeeded: value)) writeByte(UInt8(truncatingIfNeeded: value >> 8)) } public func serialize_u32(value: UInt32) throws { writeByte(UInt8(truncatingIfNeeded: value)) writeByte(UInt8(truncatingIfNeeded: value >> 8)) writeByte(UInt8(truncatingIfNeeded: value >> 16)) writeByte(UInt8(truncatingIfNeeded: value >> 24)) } public func serialize_u64(value: UInt64) throws { writeByte(UInt8(truncatingIfNeeded: value)) writeByte(UInt8(truncatingIfNeeded: value >> 8)) writeByte(UInt8(truncatingIfNeeded: value >> 16)) writeByte(UInt8(truncatingIfNeeded: value >> 24)) writeByte(UInt8(truncatingIfNeeded: value >> 32)) writeByte(UInt8(truncatingIfNeeded: value >> 40)) writeByte(UInt8(truncatingIfNeeded: value >> 48)) writeByte(UInt8(truncatingIfNeeded: value >> 56)) } public func serialize_u128(value: UInt128) throws { try serialize_u64(value: value.low) try serialize_u64(value: value.high) } public func serialize_i8(value: Int8) throws { try serialize_u8(value: UInt8(bitPattern: value)) } public func serialize_i16(value: Int16) throws { try serialize_u16(value: UInt16(bitPattern: value)) } public func serialize_i32(value: Int32) throws { try serialize_u32(value: UInt32(bitPattern: value)) } public func serialize_i64(value: Int64) throws { try serialize_u64(value: UInt64(bitPattern: value)) } public func serialize_i128(value: Int128) throws { try serialize_u64(value: value.low) try serialize_i64(value: value.high) } public func serialize_option_tag(value: Bool) throws { writeByte(value ? 1 : 0) } public func get_buffer_offset() -> Int { return output.count } public func serialize_len(value _: Int) throws { assertionFailure("Not implemented") } public func serialize_variant_index(value _: UInt32) throws { assertionFailure("Not implemented") } public func sort_map_entries(offsets _: [Int]) { assertionFailure("Not implemented") } }
apache-2.0
e8aa2b28d39af3c4951d564ef4774d36
29.233083
92
0.654315
4.192909
false
false
false
false
kf99916/JSContextFoundation
JSContextFoundation/JSContextFoundation.swift
1
2732
// // JSContextFoundation.swift // JSContextFoundation // // Created by Zheng-Xiang Ke on 2016/5/13. // Copyright © 2016年 Zheng-Xiang Ke. All rights reserved. // import Foundation import JavaScriptCore public enum JSContextFoundationError: Error { case fileNotFound case fileNotLoaded case fileNotDownloaded } open class JSContextFoundation : JSContext { public override init!(virtualMachine: JSVirtualMachine!) { super.init(virtualMachine: virtualMachine) exceptionHandler = { context, exception in let exceptionDictionary = exception?.toDictionary() print("[JSCotextFoundation][Exception] \(String(describing: exception)) at line \(String(describing: exceptionDictionary?["line"])):\(String(describing: exceptionDictionary?["column"]))") } insert() } public convenience override init!() { self.init(virtualMachine: JSVirtualMachine()) } open func requireWithPath(_ path: String) throws { guard FileManager.default.fileExists(atPath: path) else { throw JSContextFoundationError.fileNotFound } guard let script = try? String(contentsOfFile: path, encoding: String.Encoding.utf8) else { throw JSContextFoundationError.fileNotLoaded } evaluateScript(script) } open func requireWithUrl(_ url: URL, completionHandler: @escaping (Error?) -> Void) { let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) -> Void in if let error = error { completionHandler(error) } else { guard let httpResponse = response as? HTTPURLResponse else { completionHandler(JSContextFoundationError.fileNotDownloaded) return } switch httpResponse.statusCode { case 404: completionHandler(JSContextFoundationError.fileNotFound) default: guard let data = data, let script = String(data: data, encoding: String.Encoding.utf8) as String? else { completionHandler(JSContextFoundationError.fileNotDownloaded) return } self.evaluateScript(script) completionHandler(nil) } } }) task.resume() } fileprivate func insert() { let jsInsertArray: [JSInsert] = [Global(), Console()] for jsInsert in jsInsertArray { jsInsert.insert(self) } } }
mit
853d75c9fbe3032b823404a9be013450
33.1125
199
0.588494
5.361493
false
false
false
false
eeschimosu/Swifternalization
Swifternalization/InternalPattern.swift
5
619
// // InternalPatterns.swift // Swifternalization // // Created by Tomasz Szulc on 28/06/15. // Copyright (c) 2015 Tomasz Szulc. All rights reserved. // import Foundation /** Represents internal patterns used by the framework to avoid copy-pastes. */ enum InternalPattern: String { /** Pattern that matches expressions. */ case Expression = "(?<=\\{)(.+)(?=\\})" /** Pattern that matches expression types. */ case ExpressionPatternType = "(^.{2,3})(?=:)" /** Pattern that matches key without expression. */ case KeyWithoutExpression = "^(.*?)(?=\\{)" }
mit
a141f6cfac148b454537ed330d8c6ac0
20.37931
72
0.605816
4.126667
false
false
false
false
malcommac/Hydra
Sources/Hydra/Promise+Map.swift
1
3917
/* * Hydra * Fullfeatured lightweight Promise & Await Library for Swift * * Created by: Daniele Margutti * Email: [email protected] * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * 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 /// Promise resolve tryp /// /// - parallel: resolve all promises in parallel /// - series: resolve all promises in series, in order public enum PromiseResolveType { case parallel case series } /// Map an array of items and transform it to Promises. /// Then promises can be resolved in parallel or serially; rejects as soon as any Promise rejects. /// /// - Parameters: /// - context: context to run the handler on (if not specified `background` context is used) /// - type: type of execution /// - items: items to transform /// - transform: transform callback which return the promise /// - Returns: a Promise which resolve all created promises public func map<A, B, S: Sequence>(_ context: Context? = nil, as type: PromiseResolveType, _ items: S, _ transform: @escaping (A) throws -> Promise<B>) -> Promise<[B]> where S.Iterator.Element == A { let ctx = context ?? .background switch type { case .parallel: return map_parallel(context: ctx, items: items, transform: transform) default: return map_series(context: ctx, items: items, transform: transform) } } /// Series version of the map operator /// /// - Parameters: /// - context: context to run the handler on (if not specified `background` context is used) /// - items: items to transform /// - transform: transform callback which return the promise /// - Returns: a Promise which resolve all created promises public func map_series<A, B, S: Sequence>(context: Context, items: S, transform: @escaping (A) throws -> Promise<B>) -> Promise<[B]> where S.Iterator.Element == A { let initial = Promise<[B]>(resolved: []) return items.reduce(initial) { chain, item in return chain.then(in: context) { results in try transform(item).then(in: context) { results + [$0] } } } } /// Parallel version of the map operator /// /// - Parameters: /// - context: context to run the handler on (if not specified `background` context is used) /// - items: items to transform /// - transform: transform callback which return the promise /// - Returns: a Promise which resolve all created promises internal func map_parallel<A, B, S: Sequence>(context: Context, items: S, transform: @escaping (A) throws -> Promise<B>) -> Promise<[B]> where S.Iterator.Element == A { let transformPromise = Promise<Void>(resolved: ()) return transformPromise.then(in: context) { () -> Promise<[B]> in do { let mappedPromises: [Promise<B>] = try items.map({ item in return try transform(item) }) return all(mappedPromises) } catch let error { return Promise<[B]>(rejected: error) } } }
mit
9165cc62d335d7e66e776887a2f6a305
36.653846
199
0.716037
3.904287
false
false
false
false
salesawagner/wascar
Sources/Core/Network/URL.swift
1
2995
// // URL.swift // wascar // // Created by Wagner Sales on 24/11/16. // Copyright © 2016 Wagner Sales. All rights reserved. // import CoreLocation //************************************************************************************************** // // MARK: - Constants - // //************************************************************************************************** private let kPlaceType = "car_repair" private let kPlaceRadius = 5000 private let kPhotoMaxWidth = 400 //************************************************************************************************** // // MARK: - Definitions - // //************************************************************************************************** //************************************************************************************************** // // MARK: - Class - URL // //************************************************************************************************** class URL { //************************************************** // MARK: - Properties //************************************************** static var apiKey: String { return "AIzaSyBQdUB4ud-KqBpEVuq7gfLuc9c_f0q1RKY" } static var placeApiUrl: String { return "https://maps.googleapis.com/maps/api/place" } static var photoBaseUrl: String { return "\(self.placeApiUrl)/photo" } //************************************************** // MARK: - Constructors //************************************************** //************************************************** // MARK: - Private Methods //************************************************** //************************************************** // MARK: - Internal Methods //************************************************** //************************************************** // MARK: - Public Methods //************************************************** class func baseUrl(_ locationType: String) -> String { return "\(self.placeApiUrl)/\(locationType)/json" } class func places(_ placeType: String = kPlaceType, location: CLLocation) -> String { let coordinate = location.coordinate let latitude = coordinate.latitude let longitude = coordinate.longitude var url = "\(self.baseUrl("nearbysearch"))" url += "?location=\(String(format: "%f,%f", latitude, longitude))" url += "&radius=\(kPlaceRadius)" url += "&type=\(placeType)" url += "&key=\(self.apiKey)" return url } class func placeById(_ id: String) -> String { var url = self.baseUrl("details") url += "?placeid=\(id)" url += "&key=\(self.apiKey)" return url } class func photo(_ reference: String, maxWidth: Int = kPhotoMaxWidth) -> String { var url = self.photoBaseUrl url += "?maxwidth=\(maxWidth)" url += "&photoreference=\(reference)" url += "&key=\(self.apiKey)" return url } //************************************************** // MARK: - Override Public Methods //************************************************** }
mit
bb519a2968edef123e81c8ca2acb60ce
27.788462
100
0.378424
5.074576
false
false
false
false
hulinSun/MyRx
MyRx/MyRx/Classes/Core/Category/UIImage+Extension.swift
1
3196
// // UIImage+Extension.swift // MyRx // // Created by Hony on 2017/1/4. // Copyright © 2017年 Hony. All rights reserved. // import UIKit import CoreGraphics import CoreFoundation extension UIImage{ class func creatImage(with color: UIColor) -> UIImage{ let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let ctx = UIGraphicsGetCurrentContext() ctx?.setFillColor(color.cgColor) ctx?.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } class func handleImage(originalImage: UIImage,size: CGSize)-> UIImage{ let originalsize = originalImage.size if (originalsize.width < size.width) && (originalsize.height < size.height){ return originalImage }else if (originalsize.width > size.width) && (originalsize.height > size.height){ var rate: CGFloat = 1.0 let widthRate = originalsize.width / size.width let heightRate = originalsize.height / size.height rate = widthRate > heightRate ? heightRate : widthRate var imgRef: CGImage var rect: CGRect if heightRate > widthRate{ rect = CGRect(x: 0, y: originalsize.height/2-size.height*rate/2, width: originalsize.width, height: size.height*rate) }else{ rect = CGRect(x: originalsize.width/2-size.width*rate/2, y: 0, width: size.width*rate, height: originalsize.height) } imgRef = (originalImage.cgImage?.cropping(to: rect))! UIGraphicsBeginImageContext(size) let ctx = UIGraphicsGetCurrentContext() ctx?.translateBy(x: 0, y: size.height) ctx?.scaleBy(x: 1.0, y: -1.0) ctx?.draw(imgRef, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let standardImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return standardImage! }else if (originalsize.height > size.height) || (originalsize.width > size.width){ var imageRef: CGImage var rect: CGRect = .zero if originalsize.height > size.height{ rect = CGRect(x: 0, y: originalsize.height/2 - size.height/2, width: originalsize.width, height: size.height) }else if originalsize.width > size.width{ rect = CGRect(x: originalsize.width/2-size.width/2, y:0, width: size.width, height: originalsize.height) } imageRef = (originalImage.cgImage?.cropping(to: rect))! UIGraphicsBeginImageContext(size) let ctx = UIGraphicsGetCurrentContext() ctx?.translateBy(x: 0, y: size.height) ctx?.scaleBy(x: 1.0, y: -1.0) ctx?.draw(imageRef, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let standardImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return standardImage! }else{ return originalImage } } }
mit
fb12c639e8b4a00d9b08751dfa9b2579
42.148649
133
0.609458
4.362022
false
false
false
false