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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
laurentVeliscek/AudioKit | AudioKit/Common/Playgrounds/Filters.playground/Pages/High Shelf Filter.xcplaygroundpage/Contents.swift | 1 | 1518 | //: ## High Shelf Filter
//:
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
var highShelfFilter = AKHighShelfFilter(player)
highShelfFilter.cutOffFrequency = 10000 // Hz
highShelfFilter.gain = 0 // dB
AudioKit.output = highShelfFilter
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("High Shelf Filter")
addSubview(AKResourcesAudioFileLoaderView(
player: player,
filenames: filtersPlaygroundFiles))
addSubview(AKBypassButton(node: highShelfFilter))
addSubview(AKPropertySlider(
property: "Cutoff Frequency",
format: "%0.1f Hz",
value: highShelfFilter.cutOffFrequency, minimum: 20, maximum: 22050,
color: AKColor.greenColor()
) { sliderValue in
highShelfFilter.cutOffFrequency = sliderValue
})
addSubview(AKPropertySlider(
property: "Gain",
format: "%0.1f dB",
value: highShelfFilter.gain, minimum: -40, maximum: 40,
color: AKColor.redColor()
) { sliderValue in
highShelfFilter.gain = sliderValue
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| mit | 80ae31a0ab2de48eb06a53ec820d4713 | 27.111111 | 80 | 0.652174 | 5.145763 | false | false | false | false |
yonaskolb/XcodeGen | Sources/ProjectSpec/Target.swift | 1 | 14555 | import Foundation
import JSONUtilities
import XcodeProj
import Version
public struct LegacyTarget: Equatable {
public static let passSettingsDefault = false
public var toolPath: String
public var arguments: String?
public var passSettings: Bool
public var workingDirectory: String?
public init(
toolPath: String,
passSettings: Bool = passSettingsDefault,
arguments: String? = nil,
workingDirectory: String? = nil
) {
self.toolPath = toolPath
self.arguments = arguments
self.passSettings = passSettings
self.workingDirectory = workingDirectory
}
}
extension LegacyTarget: PathContainer {
static var pathProperties: [PathProperty] {
[
.string("workingDirectory"),
]
}
}
public struct Target: ProjectTarget {
public var name: String
public var type: PBXProductType
public var platform: Platform
public var settings: Settings
public var sources: [TargetSource]
public var dependencies: [Dependency]
public var info: Plist?
public var entitlements: Plist?
public var transitivelyLinkDependencies: Bool?
public var directlyEmbedCarthageDependencies: Bool?
public var requiresObjCLinking: Bool?
public var preBuildScripts: [BuildScript]
public var postCompileScripts: [BuildScript]
public var postBuildScripts: [BuildScript]
public var buildRules: [BuildRule]
public var configFiles: [String: String]
public var scheme: TargetScheme?
public var legacy: LegacyTarget?
public var deploymentTarget: Version?
public var attributes: [String: Any]
public var productName: String
public var onlyCopyFilesOnInstall: Bool
public var isLegacy: Bool {
legacy != nil
}
public var filename: String {
var filename = productName
if let fileExtension = type.fileExtension {
filename += ".\(fileExtension)"
}
if type == .staticLibrary {
filename = "lib\(filename)"
}
return filename
}
public init(
name: String,
type: PBXProductType,
platform: Platform,
productName: String? = nil,
deploymentTarget: Version? = nil,
settings: Settings = .empty,
configFiles: [String: String] = [:],
sources: [TargetSource] = [],
dependencies: [Dependency] = [],
info: Plist? = nil,
entitlements: Plist? = nil,
transitivelyLinkDependencies: Bool? = nil,
directlyEmbedCarthageDependencies: Bool? = nil,
requiresObjCLinking: Bool? = nil,
preBuildScripts: [BuildScript] = [],
postCompileScripts: [BuildScript] = [],
postBuildScripts: [BuildScript] = [],
buildRules: [BuildRule] = [],
scheme: TargetScheme? = nil,
legacy: LegacyTarget? = nil,
attributes: [String: Any] = [:],
onlyCopyFilesOnInstall: Bool = false
) {
self.name = name
self.type = type
self.platform = platform
self.deploymentTarget = deploymentTarget
self.productName = productName ?? name
self.settings = settings
self.configFiles = configFiles
self.sources = sources
self.dependencies = dependencies
self.info = info
self.entitlements = entitlements
self.transitivelyLinkDependencies = transitivelyLinkDependencies
self.directlyEmbedCarthageDependencies = directlyEmbedCarthageDependencies
self.requiresObjCLinking = requiresObjCLinking
self.preBuildScripts = preBuildScripts
self.postCompileScripts = postCompileScripts
self.postBuildScripts = postBuildScripts
self.buildRules = buildRules
self.scheme = scheme
self.legacy = legacy
self.attributes = attributes
self.onlyCopyFilesOnInstall = onlyCopyFilesOnInstall
}
}
extension Target: CustomStringConvertible {
public var description: String {
"\(name): \(platform.rawValue) \(type)"
}
}
extension Target: PathContainer {
static var pathProperties: [PathProperty] {
[
.dictionary([
.string("sources"),
.object("sources", TargetSource.pathProperties),
.string("configFiles"),
.object("dependencies", Dependency.pathProperties),
.object("info", Plist.pathProperties),
.object("entitlements", Plist.pathProperties),
.object("preBuildScripts", BuildScript.pathProperties),
.object("prebuildScripts", BuildScript.pathProperties),
.object("postCompileScripts", BuildScript.pathProperties),
.object("postBuildScripts", BuildScript.pathProperties),
.object("legacy", LegacyTarget.pathProperties),
.object("scheme", TargetScheme.pathProperties),
]),
]
}
}
extension Target {
static func resolveMultiplatformTargets(jsonDictionary: JSONDictionary) -> JSONDictionary {
guard let targetsDictionary: [String: JSONDictionary] = jsonDictionary["targets"] as? [String: JSONDictionary] else {
return jsonDictionary
}
var crossPlatformTargets: [String: JSONDictionary] = [:]
for (targetName, target) in targetsDictionary {
if let platforms = target["platform"] as? [String] {
for platform in platforms {
var platformTarget = target
platformTarget = platformTarget.expand(variables: ["platform": platform])
platformTarget["platform"] = platform
let platformSuffix = platformTarget["platformSuffix"] as? String ?? "_\(platform)"
let platformPrefix = platformTarget["platformPrefix"] as? String ?? ""
let newTargetName = platformPrefix + targetName + platformSuffix
var settings = platformTarget["settings"] as? JSONDictionary ?? [:]
if settings["configs"] != nil || settings["groups"] != nil || settings["base"] != nil {
var base = settings["base"] as? JSONDictionary ?? [:]
if base["PRODUCT_NAME"] == nil {
base["PRODUCT_NAME"] = targetName
}
settings["base"] = base
} else {
if settings["PRODUCT_NAME"] == nil {
settings["PRODUCT_NAME"] = targetName
}
}
platformTarget["productName"] = targetName
platformTarget["settings"] = settings
if let deploymentTargets = target["deploymentTarget"] as? [String: Any] {
platformTarget["deploymentTarget"] = deploymentTargets[platform]
}
crossPlatformTargets[newTargetName] = platformTarget
}
} else {
crossPlatformTargets[targetName] = target
}
}
var merged = jsonDictionary
merged["targets"] = crossPlatformTargets
return merged
}
}
extension Target: Equatable {
public static func == (lhs: Target, rhs: Target) -> Bool {
lhs.name == rhs.name &&
lhs.type == rhs.type &&
lhs.platform == rhs.platform &&
lhs.deploymentTarget == rhs.deploymentTarget &&
lhs.transitivelyLinkDependencies == rhs.transitivelyLinkDependencies &&
lhs.requiresObjCLinking == rhs.requiresObjCLinking &&
lhs.directlyEmbedCarthageDependencies == rhs.directlyEmbedCarthageDependencies &&
lhs.settings == rhs.settings &&
lhs.configFiles == rhs.configFiles &&
lhs.sources == rhs.sources &&
lhs.info == rhs.info &&
lhs.entitlements == rhs.entitlements &&
lhs.dependencies == rhs.dependencies &&
lhs.preBuildScripts == rhs.preBuildScripts &&
lhs.postCompileScripts == rhs.postCompileScripts &&
lhs.postBuildScripts == rhs.postBuildScripts &&
lhs.buildRules == rhs.buildRules &&
lhs.scheme == rhs.scheme &&
lhs.legacy == rhs.legacy &&
NSDictionary(dictionary: lhs.attributes).isEqual(to: rhs.attributes)
}
}
extension LegacyTarget: JSONObjectConvertible {
public init(jsonDictionary: JSONDictionary) throws {
toolPath = try jsonDictionary.json(atKeyPath: "toolPath")
arguments = jsonDictionary.json(atKeyPath: "arguments")
passSettings = jsonDictionary.json(atKeyPath: "passSettings") ?? LegacyTarget.passSettingsDefault
workingDirectory = jsonDictionary.json(atKeyPath: "workingDirectory")
}
}
extension LegacyTarget: JSONEncodable {
public func toJSONValue() -> Any {
var dict: [String: Any?] = [
"toolPath": toolPath,
"arguments": arguments,
"workingDirectory": workingDirectory,
]
if passSettings != LegacyTarget.passSettingsDefault {
dict["passSettings"] = passSettings
}
return dict
}
}
extension Target: NamedJSONDictionaryConvertible {
public init(name: String, jsonDictionary: JSONDictionary) throws {
let resolvedName: String = jsonDictionary.json(atKeyPath: "name") ?? name
self.name = resolvedName
productName = jsonDictionary.json(atKeyPath: "productName") ?? resolvedName
let typeString: String = try jsonDictionary.json(atKeyPath: "type")
if let type = PBXProductType(string: typeString) {
self.type = type
} else {
throw SpecParsingError.unknownTargetType(typeString)
}
let platformString: String = try jsonDictionary.json(atKeyPath: "platform")
if let platform = Platform(rawValue: platformString) {
self.platform = platform
} else {
throw SpecParsingError.unknownTargetPlatform(platformString)
}
if let string: String = jsonDictionary.json(atKeyPath: "deploymentTarget") {
deploymentTarget = try Version.parse(string)
} else if let double: Double = jsonDictionary.json(atKeyPath: "deploymentTarget") {
deploymentTarget = try Version.parse(String(double))
} else {
deploymentTarget = nil
}
settings = jsonDictionary.json(atKeyPath: "settings") ?? .empty
configFiles = jsonDictionary.json(atKeyPath: "configFiles") ?? [:]
if let source: String = jsonDictionary.json(atKeyPath: "sources") {
sources = [TargetSource(path: source)]
} else if let array = jsonDictionary["sources"] as? [Any] {
sources = try array.compactMap { source in
if let string = source as? String {
return TargetSource(path: string)
} else if let dictionary = source as? [String: Any] {
return try TargetSource(jsonDictionary: dictionary)
} else {
return nil
}
}
} else {
sources = []
}
if jsonDictionary["dependencies"] == nil {
dependencies = []
} else {
let dependencies: [Dependency] = try jsonDictionary.json(atKeyPath: "dependencies", invalidItemBehaviour: .fail)
self.dependencies = dependencies.filter { [platform] dependency -> Bool in
// If unspecified, all platforms are supported
guard let platforms = dependency.platforms else { return true }
return platforms.contains(platform)
}
}
if jsonDictionary["info"] != nil {
info = try jsonDictionary.json(atKeyPath: "info") as Plist
}
if jsonDictionary["entitlements"] != nil {
entitlements = try jsonDictionary.json(atKeyPath: "entitlements") as Plist
}
transitivelyLinkDependencies = jsonDictionary.json(atKeyPath: "transitivelyLinkDependencies")
directlyEmbedCarthageDependencies = jsonDictionary.json(atKeyPath: "directlyEmbedCarthageDependencies")
requiresObjCLinking = jsonDictionary.json(atKeyPath: "requiresObjCLinking")
preBuildScripts = jsonDictionary.json(atKeyPath: "preBuildScripts") ?? jsonDictionary.json(atKeyPath: "prebuildScripts") ?? []
postCompileScripts = jsonDictionary.json(atKeyPath: "postCompileScripts") ?? []
postBuildScripts = jsonDictionary.json(atKeyPath: "postBuildScripts") ?? jsonDictionary.json(atKeyPath: "postbuildScripts") ?? []
buildRules = jsonDictionary.json(atKeyPath: "buildRules") ?? []
scheme = jsonDictionary.json(atKeyPath: "scheme")
legacy = jsonDictionary.json(atKeyPath: "legacy")
attributes = jsonDictionary.json(atKeyPath: "attributes") ?? [:]
onlyCopyFilesOnInstall = jsonDictionary.json(atKeyPath: "onlyCopyFilesOnInstall") ?? false
}
}
extension Target: JSONEncodable {
public func toJSONValue() -> Any {
var dict: [String: Any?] = [
"type": type.name,
"platform": platform.rawValue,
"settings": settings.toJSONValue(),
"configFiles": configFiles,
"attributes": attributes,
"sources": sources.map { $0.toJSONValue() },
"dependencies": dependencies.map { $0.toJSONValue() },
"postCompileScripts": postCompileScripts.map { $0.toJSONValue() },
"prebuildScripts": preBuildScripts.map { $0.toJSONValue() },
"postbuildScripts": postBuildScripts.map { $0.toJSONValue() },
"buildRules": buildRules.map { $0.toJSONValue() },
"deploymentTarget": deploymentTarget?.deploymentTarget,
"info": info?.toJSONValue(),
"entitlements": entitlements?.toJSONValue(),
"transitivelyLinkDependencies": transitivelyLinkDependencies,
"directlyEmbedCarthageDependencies": directlyEmbedCarthageDependencies,
"requiresObjCLinking": requiresObjCLinking,
"scheme": scheme?.toJSONValue(),
"legacy": legacy?.toJSONValue(),
]
if productName != name {
dict["productName"] = productName
}
if onlyCopyFilesOnInstall {
dict["onlyCopyFilesOnInstall"] = true
}
return dict
}
}
| mit | a3298a57bf0ea7f696b43667361d838d | 38.444444 | 137 | 0.611955 | 5.619691 | false | false | false | false |
gameontext/sample-room-swift | Sources/SwiftRoom/Message.swift | 1 | 14324 | /**
* Copyright IBM Corporation 2017
*
* 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 SwiftyJSON
import LoggerAPI
public class Message {
// The first segment in the WebSocket protocol for Game On!
// This is used as a primitive routing filter as messages flow through the system
public enum Target: String {
case
// Protocol acknowledgement, sent on RoomEndpoint.connected
ack,
// Message sent to player(s)
player,
// Message sent to a specific player to trigger a location change (they are allowed to exit the room)
playerLocation,
// Message sent to the room
room,
// A player enters the room
roomHello,
// A player reconnects to the room (e.g. reconnected session)
roomJoin,
// A player's has disconnected from the room without leaving it
roomPart,
// A player leaves the room
roomGoodbye
}
let target: Target
// Target id for the message (This room, specific player, or '*')
let targetId: String
// Stringified JSON payload
let payload: String
// userId and username will be present in JSON payload
let userId: String?
let username: String?
// Parse a string read from the WebSocket
public init(message: String) throws {
// Expected format:
// target,targetId,{"json": "payload"}
guard let targetIndex = message.characters.index(of: ",") else {
throw SwiftRoomError.invalidMessageFormat
}
let targetStr = message.substring(to: targetIndex)
guard let targetVal = Target.init(rawValue: targetStr) else {
throw SwiftRoomError.invalidMessageFormat
}
self.target = targetVal
var remaining = message.substring(from: targetIndex).trimmingCharacters(in: .whitespacesAndNewlines)
// remaining = `,targetId,{"json": "payload"}`. Now remove the ','
remaining.remove(at: remaining.startIndex)
// Extract targetId
guard let targetIdIndex = remaining.characters.index(of: ",") else {
throw SwiftRoomError.invalidMessageFormat
}
self.targetId = remaining.substring(to: targetIdIndex)
// Extract JSON
guard let jsonIndex = remaining.characters.index(of: "{") else {
throw SwiftRoomError.invalidMessageFormat
}
self.payload = remaining.substring(from: jsonIndex)
guard let payloadJSON = payload.data(using: String.Encoding.utf8) else {
throw SwiftRoomError.errorInJSONProcessing
}
let json = JSON(data: payloadJSON)
self.userId = json["userId"].stringValue
self.username = json["username"].stringValue
}
public init(target: Target, targetId: String? = "", payload: String) throws {
self.target = target
self.targetId = targetId!
self.payload = payload
guard let payloadJSON = payload.data(using: String.Encoding.utf8) else {
throw SwiftRoomError.errorInJSONProcessing
}
let json = JSON(data: payloadJSON)
self.userId = json["userId"].stringValue
self.username = json["username"].stringValue
}
public static func createAckMessage() -> String {
return Target.ack.rawValue + "," + "{\"version\":[1,2]}"
}
// Create an event targeted at a specific player (use broadcast to send to all connections)
public static func createSpecificEvent(userId: String, messageForUser: String) throws -> Message {
// player,<userId>,{
// "type": "event",
// "content": {
// "<userId>": "specific to player"
// },
// "bookmark": "String representing last message seen"
// }
let payload: JSON = [
Constants.Message.type: Constants.Message.event,
Constants.Message.content: [
userId: messageForUser
],
Constants.Message.bookmark: Constants.Message.prefix + uniqueStr()
]
let payloadStr = try jsonToString(json: payload)
return try Message(target: Target.player, targetId: userId, payload: payloadStr)
}
// Construct an event that broadcasts to all players. The first string will
// be the message sent to all players. Additional messages should be specified
// in pairs afterwards, "userId1", "player message 1", "userId2", "player message 2".
//If the optional specified messages are uneven, only the general message will be sent.
public static func createBroadcastEvent(allContent: String? = "", pairs: [String]?) throws -> Message {
// player,*,{
// "type": "event",
// "content": {
// "*": "general text for everyone",
// "<userId>": "specific to player"
// },
// "bookmark": "String representing last message seen"
// }
let payload: String = buildBroadcastContent(content: allContent, pairs: pairs)
Log.info("creating broadcast event with payload: \(payload)")
return try Message(target: Target.player, targetId: Constants.Message.all, payload: payload)
}
public static func createChatMessage(username: String, message: String) throws -> Message {
// player,*,{...}
// {
// "type": "chat",
// "username": "username",
// "content": "<message>",
// "bookmark": "String representing last message seen"
// }
let payload: JSON = [
Constants.Message.type: Constants.Message.chat,
Constants.Message.username: username,
Constants.Message.content: message,
Constants.Message.bookmark: Constants.Message.prefix + uniqueStr()
]
let payloadStr = try jsonToString(json: payload)
Log.info("creating chat message with payload: \(payloadStr)")
return try Message(target: Target.player, targetId: Constants.Message.all, payload: payloadStr)
}
// Send information about the room to the client. This message is sent after receiving a `roomHello`.
public static func createLocationMessage(userId: String, roomDescription: RoomDescription) throws -> Message {
// player,<userId>,{
// "type": "location",
// "name": "Room name",
// "fullName": "Room's descriptive full name",
// "description", "Lots of text about what the room looks like",
// "exits": {
// "shortDirection" : "currentDescription for Player",
// "N" : "a dark entranceway"
// },
// "commands": {
// "/custom" : "Description of what command does"
// },
// "roomInventory": ["itemA","itemB"]
// }
let commands: JSON = JSON(roomDescription.commands)
let inventory: JSON = JSON(roomDescription.inventory)
let payload: JSON = [
Constants.Message.type: "location",
"name": roomDescription.name,
"fullName": roomDescription.fullName,
"description": roomDescription.description,
"commands": commands.object,
"roomInventory": inventory.object
]
let payloadStr = try jsonToString(json: payload)
return try Message(target: Target.player, targetId: userId, payload: payloadStr)
}
// Indicates that a player can leave by the requested exit (`exitId`).
public static func createExitMessage(userId: String, exitId: String?, message: String?) throws -> Message {
guard let exitId = exitId else {
throw SwiftRoomError.missingExitId
}
// playerLocation,<userId>,{
// "type": "exit",
// "content": "You exit through door xyz... ",
// "exitId": "N"
// "exit": { ... }
// }
// The exit attribute describes an exit the map service wouldn't know about..
// This would have to be customized..
let payload: JSON = [
Constants.Message.type: "exit",
"exitId": exitId,
Constants.Message.content: message ?? "Fare thee well"
]
let payloadStr = try jsonToString(json: payload)
return try Message(target: Target.playerLocation, targetId: userId, payload: payloadStr)
}
// Used for test purposes, create a message targeted for the room
public static func createRoomMessage(roomId: String, userId: String, username: String, content: String) throws -> Message {
// room,<roomId>,{
// "username": "<username>",
// "userId": "<userId>"
// "content": "<message>"
// }
let payload: JSON = [
Constants.Message.userId: userId,
Constants.Message.username: username,
Constants.Message.content: content
]
let payloadStr = try jsonToString(json: payload)
return try Message(target: Target.room, targetId: roomId, payload: payloadStr)
}
// Used for test purposes, create a room hello message
public static func createRoomHello(roomId: String, userId: String, username: String, version: Int) throws -> Message {
// roomHello,<roomId>,{
// "username": "<username>",
// "userId": "<userId>",
// "version": 1|2
// }
let payload: JSON = [
Constants.Message.userId: userId,
Constants.Message.username: username,
"version": version
]
let payloadStr = try jsonToString(json: payload)
return try Message(target: Target.roomHello, targetId: roomId, payload: payloadStr)
}
// Used for test purposes, create a room goodbye message
public static func createRoomGoodbye(roomId: String, userId: String, username: String) throws -> Message {
// roomGoodbye,<roomId>,{
// "username": "<username>",
// "userId": "<userId>"
// }
let payload: JSON = [
Constants.Message.userId: userId,
Constants.Message.username: username,
]
let payloadStr = try jsonToString(json: payload)
return try Message(target: Target.roomGoodbye, targetId: roomId, payload: payloadStr)
}
// Used for test purposes, create a room join message
public static func createRoomJoin(roomId: String, userId: String, username: String, version: Int) throws -> Message {
// roomJoin,<roomId>,{
// "username": "<username>",
// "userId": "<userId>",
// "version": 2
// }
let payload: JSON = [
Constants.Message.userId: userId,
Constants.Message.username: username,
"version": version
]
let payloadStr = try jsonToString(json: payload)
return try Message(target: Target.roomJoin, targetId: roomId, payload: payloadStr)
}
// Used for test purposes, create a room part message
public static func createRoomPart(roomId: String, userId: String, username: String) throws -> Message {
// roomPart,<roomId>,{
// "username": "<username>",
// "userId": "<userId>"
// }
let payload: JSON = [
Constants.Message.userId: userId,
Constants.Message.username: username,
]
let payloadStr = try jsonToString(json: payload)
return try Message(target: Target.roomPart, targetId: roomId, payload: payloadStr)
}
public func toString() -> String {
return self.target.rawValue + "," + targetId + "," + payload
}
private static func uniqueStr() -> String {
return UUID().uuidString
}
private static func jsonToString(json: JSON) throws -> String {
let data = try json.rawData()
guard let jsonString: String = String(bytes: data, encoding: String.Encoding.utf8) else {
throw SwiftRoomError.errorInJSONProcessing
}
return jsonString
}
public static func buildBroadcastContent(content: String?, pairs: [String]?) -> String {
var dict: [String: Any] = [:]
dict[Constants.Message.type] = Constants.Message.event
dict[Constants.Message.bookmark] = Constants.Message.prefix + uniqueStr()
var message: [String: String] = [:]
if let content = content {
message[Constants.Message.all] = content
}
// only add additional messages if there is an even number
if let pairs = pairs, (pairs.count % 2) == 0 {
for i in stride(from:0, through: pairs.count-1, by: 2) {
message[pairs[i]] = pairs[i+1]
}
}
dict[Constants.Message.content] = message
return dict.description.replacingOccurrences(of: "[", with: "{").replacingOccurrences(of: "]", with: "}")
}
}
| apache-2.0 | 43433c169a366f01df91a027296780c7 | 34.543424 | 127 | 0.569953 | 4.930809 | false | false | false | false |
jwfriese/FrequentFlyer | FrequentFlyerTests/Jobs/JobsDataDeserializerSpec.swift | 1 | 14260 | import XCTest
import Quick
import Nimble
import RxSwift
import SwiftyJSON
import Result
@testable import FrequentFlyer
class JobsDataDeserializerSpec: QuickSpec {
class MockBuildDataDeserializer: BuildDataDeserializer {
private var toReturnBuild: [Data : Build] = [:]
private var toReturnError: [Data : DeserializationError] = [:]
fileprivate func when(_ data: JSON, thenReturn build: Build) {
let jsonData = try! data.rawData(options: .prettyPrinted)
toReturnBuild[jsonData] = build
}
fileprivate func when(_ data: JSON, thenErrorWith error: DeserializationError) {
let jsonData = try! data.rawData(options: .prettyPrinted)
toReturnError[jsonData] = error
}
override func deserialize(_ data: Data) -> Result<Build, DeserializationError> {
let inputAsJSON = JSON(data: data)
for (keyData, build) in toReturnBuild {
let keyAsJSON = JSON(data: keyData)
if keyAsJSON == inputAsJSON {
return Result.success(build)
}
}
for (keyData, error) in toReturnError {
let keyAsJSON = JSON(data: keyData)
if keyAsJSON == inputAsJSON {
return Result.failure(error)
}
}
return Result.failure(DeserializationError(details: "fatal error in test", type: .missingRequiredData))
}
}
override func spec() {
describe("JobsDataDeserializer") {
var subject: JobsDataDeserializer!
var mockBuildDataDeserializer: MockBuildDataDeserializer!
var validNextBuildJSONOne: JSON!
var validFinishedBuildJSONOne: JSON!
var validNextBuildJSONTwo: JSON!
var validFinishedBuildJSONTwo: JSON!
var validFinishedBuildResultOne: Build!
var validNextBuildResultOne: Build!
var validFinishedBuildResultTwo: Build!
var validNextBuildResultTwo: Build!
var validJobJSONOne: JSON!
var validJobJSONTwo: JSON!
let publishSubject = PublishSubject<[Job]>()
var result: StreamResult<[Job]>!
var jobs: [Job] {
get {
return result.elements.flatMap { $0 }
}
}
beforeEach {
subject = JobsDataDeserializer()
mockBuildDataDeserializer = MockBuildDataDeserializer()
subject.buildDataDeserializer = mockBuildDataDeserializer
validFinishedBuildJSONOne = JSON(dictionaryLiteral: [
("name", "finished one")
])
validNextBuildJSONOne = JSON(dictionaryLiteral: [
("name", "next one")
])
validJobJSONOne = JSON(dictionaryLiteral :[
("name", "turtle job"),
("finished_build", validFinishedBuildJSONOne),
("next_build", validNextBuildJSONOne),
("groups", ["group_one", "group_two"])
])
validFinishedBuildJSONTwo = JSON(dictionaryLiteral: [
("name", "finished two"),
])
validNextBuildJSONTwo = JSON(dictionaryLiteral: [
("name", "next two")
])
validJobJSONTwo = JSON(dictionaryLiteral :[
("name", "crab job"),
("finished_build", validFinishedBuildJSONTwo),
("next_build", validNextBuildJSONTwo),
("groups", ["group_one", "group_three"])
])
validFinishedBuildResultOne = BuildBuilder().withName("finished one").build()
validNextBuildResultOne = BuildBuilder().withName("next one").build()
validFinishedBuildResultTwo = BuildBuilder().withName("finished two").build()
validNextBuildResultTwo = BuildBuilder().withName("next two").build()
mockBuildDataDeserializer.when(validFinishedBuildJSONOne, thenReturn: validFinishedBuildResultOne)
mockBuildDataDeserializer.when(validFinishedBuildJSONTwo, thenReturn: validFinishedBuildResultTwo)
mockBuildDataDeserializer.when(validNextBuildJSONOne, thenReturn: validNextBuildResultOne)
mockBuildDataDeserializer.when(validNextBuildJSONTwo, thenReturn: validNextBuildResultTwo)
}
describe("Deserializing jobs data that is all valid") {
beforeEach {
let validInputJSON = JSON([
validJobJSONOne,
validJobJSONTwo
])
let validData = try! validInputJSON.rawData(options: .prettyPrinted)
result = StreamResult(subject.deserialize(validData))
}
it("returns a job for each JSON job entry") {
if jobs.count != 2 {
fail("Expected to return 2 jobs, returned \(jobs.count)")
return
}
let expectedJobOne = Job(
name: "turtle job",
nextBuild: validNextBuildResultOne,
finishedBuild: validFinishedBuildResultOne,
groups: ["group_one", "group_two"]
)
let expectedJobTwo = Job(
name: "crab job",
nextBuild: validNextBuildResultTwo,
finishedBuild: validFinishedBuildResultTwo,
groups: ["group_one", "group_three"]
)
expect(jobs[0]).to(equal(expectedJobOne))
expect(jobs[1]).to(equal(expectedJobTwo))
}
it("returns no error") {
expect(result.error).to(beNil())
}
}
describe("Deserializing job data where some of the data is invalid") {
context("Missing required 'name' field") {
beforeEach {
var invalidJobJSON: JSON! = validJobJSONTwo
_ = invalidJobJSON.dictionaryObject?.removeValue(forKey: "name")
let inputJSON = JSON([
validJobJSONOne,
invalidJobJSON
])
let invalidData = try! inputJSON.rawData(options: .prettyPrinted)
result = StreamResult(subject.deserialize(invalidData))
}
it("emits a job only for each valid JSON job entry") {
let expectedJob = Job(
name: "turtle job",
nextBuild: validNextBuildResultOne,
finishedBuild: validFinishedBuildResultOne,
groups: ["group_one", "group_two"]
)
expect(jobs).to(equal([expectedJob]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("'name' field is not a string") {
beforeEach {
var invalidJobJSON: JSON! = validJobJSONTwo
_ = invalidJobJSON.dictionaryObject?.updateValue(1, forKey: "name")
let inputJSON = JSON([
validJobJSONOne,
invalidJobJSON
])
let invalidData = try! inputJSON.rawData(options: .prettyPrinted)
result = StreamResult(subject.deserialize(invalidData))
}
it("emits a job only for each valid JSON job entry") {
let expectedJob = Job(
name: "turtle job",
nextBuild: validNextBuildResultOne,
finishedBuild: validFinishedBuildResultOne,
groups: ["group_one", "group_two"]
)
expect(jobs).to(equal([expectedJob]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("Missing just 'next_build'") {
beforeEach {
var stillValidJobJSON: JSON! = validJobJSONTwo
_ = stillValidJobJSON.dictionaryObject?.removeValue(forKey: "next_build")
let inputJSON = JSON([
validJobJSONOne,
stillValidJobJSON
])
let invalidData = try! inputJSON.rawData(options: .prettyPrinted)
result = StreamResult(subject.deserialize(invalidData))
}
it("emits a job for each valid JSON job entry") {
let expectedJobOne = Job(
name: "turtle job",
nextBuild: validNextBuildResultOne,
finishedBuild: validFinishedBuildResultOne,
groups: ["group_one", "group_two"]
)
let expectedJobTwo = Job(
name: "crab job",
nextBuild: nil,
finishedBuild: validFinishedBuildResultTwo,
groups: ["group_one", "group_three"]
)
expect(jobs).to(equal([expectedJobOne, expectedJobTwo]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("Missing just 'finished_build'") {
beforeEach {
var stillValidJobJSON: JSON! = validJobJSONTwo
_ = stillValidJobJSON.dictionaryObject?.removeValue(forKey: "finished_build")
let inputJSON = JSON([
validJobJSONOne,
stillValidJobJSON
])
let invalidData = try! inputJSON.rawData(options: .prettyPrinted)
result = StreamResult(subject.deserialize(invalidData))
}
it("emits a job for each valid JSON job entry") {
let expectedJobOne = Job(
name: "turtle job",
nextBuild: validNextBuildResultOne,
finishedBuild: validFinishedBuildResultOne,
groups: ["group_one", "group_two"]
)
let expectedJobTwo = Job(
name: "crab job",
nextBuild: validNextBuildResultTwo,
finishedBuild: nil,
groups: ["group_one", "group_three"]
)
expect(jobs).to(equal([expectedJobOne, expectedJobTwo]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
context("Missing both 'next_build' and 'finished_build' fields simulataneously") {
beforeEach {
var bothBuildsMissingJSON: JSON! = validJobJSONTwo
_ = bothBuildsMissingJSON.dictionaryObject?.removeValue(forKey: "next_build")
_ = bothBuildsMissingJSON.dictionaryObject?.removeValue(forKey: "finished_build")
let inputJSON = JSON([
validJobJSONOne,
bothBuildsMissingJSON
])
let invalidData = try! inputJSON.rawData(options: .prettyPrinted)
result = StreamResult(subject.deserialize(invalidData))
}
it("emits a job for each valid JSON job entry") {
let expectedJobOne = Job(
name: "turtle job",
nextBuild: validNextBuildResultOne,
finishedBuild: validFinishedBuildResultOne,
groups: ["group_one", "group_two"]
)
let expectedJobTwo = Job(
name: "crab job",
nextBuild: nil,
finishedBuild: nil,
groups: ["group_one", "group_three"]
)
expect(jobs).to(equal([expectedJobOne, expectedJobTwo]))
}
it("emits completed") {
expect(result.completed).to(beTrue())
}
}
}
describe("Given data cannot be interpreted as JSON") {
beforeEach {
let jobsDataString = "some string"
let invalidJobsData = jobsDataString.data(using: String.Encoding.utf8)
result = StreamResult(subject.deserialize(invalidJobsData!))
}
it("emits no methods") {
expect(jobs).to(haveCount(0))
}
it("emits an error") {
expect(result.error as? DeserializationError).to(equal(DeserializationError(details: "Could not interpret data as JSON dictionary", type: .invalidInputFormat)))
}
}
}
}
}
| apache-2.0 | ae617ff8e5696b130ba3b991abc52013 | 40.095101 | 180 | 0.475245 | 6.826233 | false | false | false | false |
qvik/HelsinkiOS-IBD-Demo | HelsinkiOS-Demo/Views/Base/BaseNavigationView.swift | 1 | 1838 | //
// BaseNavigationView.swift
// HelsinkiOS-Demo
//
// Created by Jerry Jalava on 28/09/15.
// Copyright © 2015 Qvik. All rights reserved.
//
import UIKit
@IBDesignable public class BaseNavigationView: UIView {
@IBOutlet weak var backButton: UIButton!
@IBInspectable public var showBackButton: Bool = false {
didSet {
backButton.hidden = !showBackButton
}
}
public var view: UIView!
// MARK: Private methods
private func getXibName() -> String {
let className = NSStringFromClass(self.dynamicType) as String
let nameParts = className.characters.split {$0 == "."}.map { String($0) }
return nameParts[1] as String
}
private func loadViewFromNib(name: String) -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: name, bundle: bundle)
// Assumes UIView is top level and only object in CustomView.xib file
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
// MARK: Overridable methods
func viewInited() {
}
// MARK: Lifecycle
required override public init(frame: CGRect) {
super.init(frame: frame)
self.initView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initView()
}
func initView() {
let xibName = getXibName()
view = loadViewFromNib(xibName)
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)
viewInited()
}
}
| mit | 2d31ab9e02f2c0575499bab38480bdae | 24.164384 | 101 | 0.597169 | 4.834211 | false | false | false | false |
abaca100/Nest | iOS-NestDK/UIAlertController+Convenience.swift | 1 | 2854 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `UIAlertController+Convenience` methods allow for quick construction of `UIAlertController`s with common structures.
*/
import UIKit
extension UIAlertController {
/**
A simple `UIAlertController` that prompts for a name, then runs a completion block passing in the name.
- parameter attributeType: The type of object that will be named.
- parameter completion: A block to call, passing in the provided text.
- returns: A `UIAlertController` instance with a UITextField, cancel button, and add button.
*/
convenience init(attributeType: String, completionHandler: (name: String) -> Void, var placeholder: String? = nil, var shortType: String? = nil) {
if placeholder == nil {
placeholder = attributeType
}
if shortType == nil {
shortType = attributeType
}
let title = NSLocalizedString("New", comment: "New") + " \(attributeType)"
let message = NSLocalizedString("Enter a name.", comment: "Enter a name.")
self.init(title: title, message: message, preferredStyle: .Alert)
self.addTextFieldWithConfigurationHandler { textField in
textField.placeholder = placeholder
textField.autocapitalizationType = .Words
}
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel"), style: .Cancel) { action in
self.dismissViewControllerAnimated(true, completion: nil)
}
let add = NSLocalizedString("Add", comment: "Add")
let addString = "\(add) \(shortType!)"
let addNewObject = UIAlertAction(title: addString, style: .Default) { action in
if let name = self.textFields!.first!.text {
let trimmedName = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
completionHandler(name: trimmedName)
}
self.dismissViewControllerAnimated(true, completion: nil)
}
self.addAction(cancelAction)
self.addAction(addNewObject)
}
/**
A simple `UIAlertController` made to show an error message that's passed in.
- parameter body: The body of the alert.
- returns: A `UIAlertController` with an 'Okay' button.
*/
convenience init(title: String, body: String) {
self.init(title: title, message: body, preferredStyle: .Alert)
let okayAction = UIAlertAction(title: NSLocalizedString("Okay", comment: "Okay"), style: .Default) { action in
self.dismissViewControllerAnimated(true, completion: nil)
}
self.addAction(okayAction)
}
} | apache-2.0 | 7fab7146fec4543acc448ae01681d789 | 42.892308 | 150 | 0.647616 | 5.148014 | false | false | false | false |
victorchee/CustomTransition | CustomTransition/CustomTransition/FirstViewController.swift | 1 | 2937 | //
// FirstViewController.swift
// CustomTransition
//
// Created by qihaijun on 11/4/15.
// Copyright © 2015 VictorChee. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, UIViewControllerTransitioningDelegate {
private var percentDrivenTransition: UIPercentDrivenInteractiveTransition?
override func viewDidLoad() {
super.viewDidLoad()
transitioningDelegate = self
let edgePanGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(edgePan(_:)))
edgePanGesture.edges = UIRectEdge.right
view.addGestureRecognizer(edgePanGesture)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? SecondViewController {
let edgePanGesture = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(edgePan(_:)))
edgePanGesture.edges = UIRectEdge.left
destination.view.addGestureRecognizer(edgePanGesture)
destination.transitioningDelegate = self
}
super.prepare(for: segue, sender: sender)
}
@objc func edgePan(_ sender: UIScreenEdgePanGestureRecognizer) {
let window = UIApplication.shared.keyWindow!
let progress = abs(sender.translation(in: window).x / window.bounds.width)
if sender.state == .began {
percentDrivenTransition = UIPercentDrivenInteractiveTransition()
if sender.edges == .right {
performSegue(withIdentifier: "Modal", sender: sender)
} else {
dismiss(animated: true, completion: nil)
}
} else if sender.state == .changed {
percentDrivenTransition?.update(progress)
} else if sender.state == .cancelled || sender.state == .ended {
if progress > 0.5 {
percentDrivenTransition?.finish()
} else {
percentDrivenTransition?.cancel()
}
percentDrivenTransition = nil
}
}
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return CustomModalTransition()
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return CustomDismissTransition()
}
func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return percentDrivenTransition
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return percentDrivenTransition
}
}
| mit | 15c000b8b02d69521f832fb0d3d08142 | 39.777778 | 217 | 0.683583 | 6.495575 | false | false | false | false |
MakeSchool/Swift-Playgrounds | More-P0-Closures.playground/Contents.swift | 2 | 7756 | import UIKit
//: ## Closures
//:
//: Closures are like functions with a twist. They can refer to variables in their containing scope, which makes them way more powerful than normal functions. In Swift, closures pop up everywhere, so it will help to play with some examples to get familiar with them.
//: ### A Simple Example
//:
//: Let's look at a simple closure:
func addOne(value: Int) -> Int {
return value + 1
}
addOne(1)
//: "Wait!" you say. "That's just a plain old function!" And you're right. A global function is a named closure. The trivial closure above takes a value and adds one to it, returning the result.
//: ### Capture
//:
//: What distinguishes closures from functions is that closures **capture** variables from their surrounding environment. This means that you can refer to local variables from within a closure, and even if they have later gone out of scope, the closure still has access to them. Value types get copied when they are captured, while reference types are strongly referenced, meaning the closure prevents them from being deallocated until the closure itself is deallocated.
//: ### Nested Functions
//:
//: Let's look at a more sophisticated example of closures, one that actually takes advantage of a closure's ability to refer to variables in its containing scope. **Nested functions** are another instance of closures in Swift:
func fibonacciSequence(length: Int) -> [Int] {
let initialElements = [0, 1]
func sequence() -> [Int] {
var elements = initialElements
for (var i = elements.count; i < length; ++i) {
elements.append(elements[i - 2] + elements[i - 1])
}
return elements
}
// This calls the closure, which has captured the initial sequence elements
// and will complete the sequence to the desired length
return sequence()
}
//: The nested function (`sequence`) builds up a sequence by adding the last two elements in the sequence together and appending this new value to the elements array. The important thing to note here is that the nested function _captures_ both the local variable `initialElements` and the `length` parameter. The values of these two captured variables determine the values that wind up in the array returned by `sequence`, even though they aren't expressly passed as parameters to the closure.
//: Calling the `fibonacciSequence` outer function with the desired length of the sequence returns an array containing that many Fibonacci numbers:
fibonacciSequence(12)
//: Closure Expressions
//:
//: It's not necessary to name a closure if you return it or call it immediately. This allows us to write functions that return anonymous functions. Consider this function, which builds functions that extend a `String` by repeating its final character:
func extender(base: String) -> (Int) -> String {
return { count in
let lastCharacter = base[advance(base.endIndex, -1)]
var extendedString = base
for (var i = 1; i < count; ++i) {
extendedString.append(lastCharacter)
}
return extendedString
}
}
//: If those double arrows (`->`) are tripping you up, that's understandable. You may not have seen a function return a function before, and it's hard to read at first. Let's break it down a little further.
//: The function `extender` takes a `String` and returns a closure that captures that string and also takes an `Int` and returns a `String`. That's a mouthful, but it demonstrates the fact that closures in Swift can be created, passed around, and returned just like other types.
//: Let's make an extender that will add extra "y"s to the end of the string "Hey":
let heyExtender = extender("Hey")
//: Notice that the thing we get back is described as "(Function)". That's our closure. Let's call it with 5 as the total number of "y"s:
let extendedHey = heyExtender(5)
//: What's the advantage of returning a closure instead of just building the extended string directly in the `extender` function? Well, we can invoke the closure we get back multiple times with different parameters to build all the extended "hey"s we want:
heyExtender(8)
heyExtender(16)
heyExtender(32)
//: ### Trailing Closure Syntax
//:
//: Many functions in the Swift standard library take closures as parameters. These closures may be used to help the function do its job, or they may be used as a callback to notify another object when the function has completed. Swift has special syntax for the rather common case that a closure is the final parameter in a function's parameter list. Let's take a look at an example.
let scores = [ 70, 93, 81, 55, 99, 77, 62 ]
sorted(scores, { (a, b) -> Bool in
a < b // Sort ascending
})
//: The standard function `sorted` takes an array and returns a sorted array of the same type. It also takes a second parameter: a closure you can use to customize which object is ordered as the lesser of the pair of its parameters. Above, we wrote the closure in-line using closure expression syntax. But we can also move it outside the function call entirely, using **trailing closure syntax**:
sorted(scores) { (a, b) -> Bool in
b < a // Sort descending this time
}
//: Note in the above case that the parentheses containing the parameter list are closed, and the opening brace for the closure comes afterward. This looks a little unusual at first, but you are likely to see this syntax often, so you will quickly grow accustomed to it.
//: ### Avoiding Retain Cycles
//:
//: So far, we've mostly been capturing value types in our closures. There is a pitfall to be aware of when capturing reference types: if an object has a reference to a closure, which in turn refers to the object itself (even just by accessing one of the object's properties), the object will never be released, leading to a memory leak. This type of circular reference is called a **strong reference cycle** (or "retain cycle").
//: The class below generates random numbers and keeps a running tally of the generated values. Inside the callback, notice that we have commented out the line `[unowned self] in`. The part in square brackets is called the **capture list**, and it tells the closure _not_ to hold onto a strong reference to `self`. With this line commented out, self will be strongly referenced by the closure, and the object itself will hold a strong reference to the closure, creating a strong reference cycle.
class RandomNumberAccumulator {
typealias RandomNumberCallback = () -> ()
var sum: UInt32
var callback: RandomNumberCallback!
init() {
sum = 0
self.callback = {
// [unowned self] in // Omitting this causes self to be captured strongly by this block
println("\(self.sum)")
}
}
func generate() {
self.sum += arc4random_uniform(100)
callback()
}
}
var rna = RandomNumberAccumulator()
rna.generate()
rna.generate()
rna.generate()
rna.generate()
//: Whenever a class holds a reference to a closure that refers back to the object, you should include a capture list that explicitly makes the reference to `self` an **unowned** reference. Otherwise, your app will leak memory.
//: ### Recap
//:
//: In this Playground, we've seen a few examples of closures, some trivial and some fairly advanced. You learned that closures have the special ability to "capture" variables from their surrounding scope, which allows them to operate on these values even after they leave their original scope. You learned that functions can have nested functions and that functions can return functions. Finally, you learned how to avoid strong reference cycles when an object needs to hold onto a reference to a closure that references the object.
| mit | 1ea02a0d42fddf848ca2055540925c40 | 60.555556 | 533 | 0.73556 | 4.504065 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS | UberGoCore/UberGoCore/MapService.swift | 1 | 3721 | //
// Map.swift
// UberGoCore
//
// Created by Nghia Tran on 6/4/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Foundation
import MapKit
import RxCocoa
import RxSwift
protocol MapServiceViewModel {
var input: MapServiceInput { get }
var output: MapServiceOutput { get }
}
protocol MapServiceInput {
}
protocol MapServiceOutput {
var currentLocationVar: Variable<CLLocation?> { get }
var currentPlaceObs: Observable<PlaceObj> { get }
var authorizedDriver: Driver<Bool>! { get }
}
// MARK: - MapService
public final class MapService: NSObject, MapServiceViewModel, MapServiceInput, MapServiceOutput {
// MARK: - Input Output
var input: MapServiceInput { return self }
var output: MapServiceOutput { return self }
// MARK: - Output
public var currentLocationVar = Variable<CLLocation?>(nil)
public var currentPlaceObs: Observable<PlaceObj>
public var authorizedDriver: Driver<Bool>!
// Private
fileprivate lazy var locationManager: CLLocationManager = self.lazyLocationManager()
// MARK: - Init
public override init() {
// Current Place
self.currentPlaceObs = self.currentLocationVar
.asObservable()
.filterNil()
.take(1)
.throttle(5.0, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.flatMapLatest({ MapService.currentPlaceObverser($0) })
super.init()
// Authorize
self.authorizedDriver = Observable
.deferred { [weak self] in
let status = CLLocationManager.authorizationStatus()
guard let `self` = self else { return Observable.empty() }
return self.locationManager
.rx.didChangeAuthorizationStatus
.startWith(status)
}
.asDriver(onErrorJustReturn: CLAuthorizationStatus.notDetermined)
.map {
switch $0 {
case .authorizedAlways:
return true
default:
return false
}
}
}
// MARK: - Public
public func startUpdatingLocation() {
self.locationManager.startUpdatingLocation()
}
public func stopUpdatingLocation() {
self.locationManager.stopUpdatingLocation()
}
fileprivate class func currentPlaceObverser(_ location: CLLocation) -> Observable<PlaceObj> {
let param = PlaceSearchRequestParam(location: location.coordinate)
return PlaceSearchRequest(param)
.toObservable()
.map({ return $0.first })
.filterNil()
}
}
extension MapService {
fileprivate func lazyLocationManager() -> CLLocationManager {
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
return locationManager
}
}
// MARK: - CLLocationManagerDelegate
extension MapService: CLLocationManagerDelegate {
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
Logger.info("Error \(error)")
}
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
Logger.info("didChangeAuthorization \(status)")
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let lastLocation = locations.last else { return }
// Notify
self.currentLocationVar.value = lastLocation
}
}
| mit | dddddf881c085850f59522d83a09f604 | 28.76 | 117 | 0.649194 | 5.502959 | false | false | false | false |
ta2yak/loqui | loqui/AppDelegate.swift | 1 | 4599 | //
// AppDelegate.swift
// loqui
//
// Created by Kawasaki Tatsuya on 2017/07/01.
// Copyright © 2017年 Kawasaki Tatsuya. All rights reserved.
//
import UIKit
import Firebase
import SimpleTab
import MaterialComponents
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var simpleTBC:SimpleTabBarController?
var mainColorScheme:MDCBasicColorScheme?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Setup Firebase
FirebaseApp.configure()
mainColorScheme = MDCBasicColorScheme(primaryColor: UIColor.mainColor(),
primaryLightColor: UIColor.mainLightColor(),
primaryDarkColor: UIColor.mainDarkColor())
//# Setup Simple Tab Bar Controller
setupSimpleTab()
return true
}
func setupSimpleTab() {
//# Get Handle of Tab Bar Control
/* In storyboard, ensure :
- Tab Bar Controller is set as SimpleTabBarController
- Tab Bar is set as SimpleTabBar
- Tab Bar Item is set as SimpleTabBarItem
*/
simpleTBC = self.window!.rootViewController as? SimpleTabBarController
//# Set the View Transition
simpleTBC?.viewTransition = PopViewTransition()
//simpleTBC?.viewTransition = CrossFadeViewTransition()
//# Set Tab Bar Style ( tab bar , tab item animation style etc )
let style:SimpleTabBarStyle = PopTabBarStyle(tabBar: simpleTBC!.tabBar)
//let style:SimpleTabBarStyle = ElegantTabBarStyle(tabBar: simpleTBC!.tabBar)
//# Optional - Set Tab Title attributes for selected and unselected (normal) states.
// Or use the App tint color to set the states
style.setTitleTextAttributes(attributes: [NSFontAttributeName as NSObject : UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName as NSObject: UIColor.lightGray], forState: .normal)
style.setTitleTextAttributes(attributes: [NSFontAttributeName as NSObject : UIFont.systemFont(ofSize: 14),NSForegroundColorAttributeName as NSObject: UIColor.mainColor()], forState: .selected)
//# Optional - Set Tab Icon colors for selected and unselected (normal) states.
// Or use the App tint color to set the states
style.setIconColor(color: UIColor.lightGray, forState: UIControlState.normal)
style.setIconColor(color: UIColor.mainColor(), forState: UIControlState.selected)
//# Let the tab bar control know of the style
// Note: All style settings must be done prior to this.
simpleTBC?.tabBarStyle = style
}
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 | f01bcecb0f48ff931a79400a40df6959 | 45.897959 | 285 | 0.70148 | 5.716418 | false | false | false | false |
raginmari/RAGTextField | Example/RAGTextField/PlaceholderViewController.swift | 1 | 2902 | import UIKit
import RAGTextField
final class PlaceholderViewController: UIViewController, UITextFieldDelegate {
@IBOutlet private weak var simpleTextField: RAGTextField! {
didSet {
simpleTextField.placeholderMode = .simple
setUp(simpleTextField)
}
}
@IBOutlet private weak var whenNotEmptyTextField: RAGTextField! {
didSet {
whenNotEmptyTextField.placeholderMode = .scalesWhenNotEmpty
setUp(whenNotEmptyTextField)
}
}
@IBOutlet private weak var whenEditingTextField: RAGTextField! {
didSet {
whenEditingTextField.placeholderMode = .scalesWhenEditing
setUp(whenEditingTextField)
}
}
@IBOutlet private weak var offsetTextField: RAGTextField! {
didSet {
offsetTextField.placeholderMode = .scalesWhenEditing
setUp(offsetTextField, color: ColorPalette.savanna.withAlphaComponent(0.1))
}
}
@IBOutlet weak var placeholderOffsetControl: UISegmentedControl! {
didSet {
placeholderOffsetControl.tintColor = ColorPalette.savanna
}
}
private func setUp(_ textField: RAGTextField, color: UIColor = ColorPalette.chalk) {
textField.delegate = self
textField.textColor = ColorPalette.midnight
textField.tintColor = ColorPalette.midnight
textField.textBackgroundView = makeTextBackgroundView(color: color)
textField.textPadding = UIEdgeInsets(top: 4.0, left: 4.0, bottom: 4.0, right: 4.0)
textField.textPaddingMode = .textAndPlaceholderAndHint
textField.scaledPlaceholderOffset = 2.0
textField.placeholderScaleWhenEditing = 0.8
textField.placeholderColor = ColorPalette.stone
}
private func makeTextBackgroundView(color: UIColor) -> UIView {
let view = UIView()
view.layer.cornerRadius = 4.0
view.backgroundColor = color
return view
}
override func viewDidLoad() {
title = "Placeholder"
setPlaceholderOffset(at: placeholderOffsetControl.selectedSegmentIndex)
super.viewDidLoad()
}
@IBAction func onPlaceholderOffsetChanged(_ control: UISegmentedControl) {
setPlaceholderOffset(at: control.selectedSegmentIndex)
}
private func setPlaceholderOffset(at index: Int) {
_ = offsetTextField.resignFirstResponder()
let offset: CGFloat = [0.0, 8.0, 16.0][index]
offsetTextField.scaledPlaceholderOffset = offset
let value = "Offset by \(Int(offset))pt"
offsetTextField.text = value
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
}
| mit | 1c4cb9dfe2300302c470b9f2b029331e | 30.204301 | 90 | 0.63887 | 5.51711 | false | false | false | false |
Bajocode/ExploringModerniOSArchitectures | Architectures/Shared/Utility/TmdbParser.swift | 1 | 3256 | //
// TmdbParser.swift
// Architectures
//
// Created by Fabijan Bajo on 20/05/2017.
//
//
/*
Tmdb object parsing utility methods
*/
import Foundation
struct TmdbParser {
// DataManager's access to the parsing utilities
public static func parsedResult(withJSONData data: Data, type: ModelType) -> DataResult {
do{
// Serialize raw json into foundation json and retrieve movie array
let jsonFoundationObject = try JSONSerialization.jsonObject(with: data, options: [])
guard
let jsonDict = jsonFoundationObject as? [AnyHashable:Any],
let jsonObjectsArray = jsonDict["results"] as? [[String:Any]] else {
return .failure(TmdbError.invalidJSONData(key: "results", dictionary: jsonFoundationObject))
}
return .success(parsedObjects(withJSONArray: jsonObjectsArray, type: type))
} catch let serializationError {
return .failure(serializationError)
}
}
// Caller of individual object parsers based on object type
private static func parsedObjects(withJSONArray array: [[String: Any]], type: ModelType) -> [Transportable] {
switch type {
case .movie: return array.flatMap { parsedMovie(forMovieJSON: $0) }
case .actor: return array.flatMap { parsedActor(forActorJSON: $0) }
}
}
// Parse individual movie dictionaries, extracted from json response
private static func parsedMovie(forMovieJSON json: [String:Any]) -> Movie? {
guard
let movieID = json["id"] as? Int,
let title = json["title"] as? String,
let posterPath = json["poster_path"] as? String,
let averageRating = json["vote_average"] as? Double,
let releaseDate = json["release_date"] as? String else {
// Do not have enough information to construct the object
return nil
}
return Movie(title: title, posterPath: posterPath, movieID: movieID, releaseDate: releaseDate, averageRating: averageRating)
}
// Parse individual actor dictionaries, extracted from json response
private static func parsedActor(forActorJSON json: [String:Any]) -> Actor? {
guard
let actorID = json["id"] as? Int,
let name = json["name"] as? String,
let profilePath = json["profile_path"] as? String else {
// Do not have enough information to construct the object
return nil
}
return Actor(name: name, profilePath: profilePath, actorID: actorID)
}
}
// MARK: - Tmdb parsing related helper types
fileprivate enum TmdbError: CustomStringConvertible, Error {
case invalidJSONData(key: String, dictionary: Any)
case serializationError(error: Error)
case other(string: String)
var description: String {
switch self {
case .invalidJSONData(let key, let dict):
return "Could not find key '\(key)' in JSON dictionary:\n \(dict)"
case .serializationError(let error):
return "JSON serialization failed with error:\n \(error)"
case .other(let string):
return string
}
}
}
| mit | 8930b6038ccb58a7af69fb1cf91543f2 | 37.761905 | 132 | 0.626843 | 4.753285 | false | false | false | false |
juanm95/Soundwich | Quaggify/LoginViewController.swift | 1 | 2466 | //
// LoginViewController.swift
// Quaggify
//
// Created by Jonathan Bijos on 02/02/17.
// Copyright © 2017 Quaggie. All rights reserved.
//
import UIKit
class LoginViewController: ViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
let titleLabel: UILabel = {
let label = UILabel()
label.text = "Soundwich"
label.textColor = ColorPalette.white
label.font = Font.montSerratRegular(size: 36)
label.textAlignment = .center
return label
}()
lazy var loginButton: UIButton = {
let button = UIButton(type: .system)
button.tintColor = .white
button.setTitle("Login with Spotify", for: .normal)
button.titleLabel?.font = Font.montSerratBold(size: 16)
button.addTarget(self, action: #selector(login), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let alertController = UIAlertController(title: "Soundwich", message: "Enter your username", preferredStyle: UIAlertControllerStyle.alert)
alertController.addTextField{ (textField : UITextField!) -> Void in
textField.placeholder = "Enter username"
}
alertController.addAction(UIAlertAction(title: "Login", style: UIAlertActionStyle.default, handler: {(alert: UIAlertAction!) in
let username = alertController.textFields![0].text!
print(username)
UserDefaults.standard.set(username, forKey: "username")
API.registerUser(username: username)
}))
self.present(alertController, animated: true, completion: nil)
}
func login () {
SpotifyService.shared.login()
}
override func setupViews() {
super.setupViews()
view.backgroundColor = ColorPalette.black
view.addSubview(titleLabel)
view.addSubview(loginButton)
titleLabel.anchorCenterYToSuperview()
titleLabel.anchor(nil, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 0, rightConstant: 8, widthConstant: 0, heightConstant: 40)
loginButton.anchor(nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 32)
}
}
| mit | 5839568166f068b61dd5365daae17eed | 32.310811 | 210 | 0.687221 | 4.677419 | false | false | false | false |
khizkhiz/swift | benchmark/single-source/Chars.swift | 2 | 1262 | //===--- Chars.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test tests the performance of ASCII Character comparison.
import TestsUtils
@inline(never)
public func run_Chars(N: Int) {
// Permute some characters.
let alphabet: [Character] = [
"A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U",
"V", "W", "X", "Y", "Z", "/", "f", "Z", "z", "6", "7", "C", "j", "f", "9",
"g", "g", "I", "J", "K", "c", "x", "i", ".",
"2", "a", "t", "i", "o", "e", "q", "n", "X", "Y", "Z", "?", "m", "Z", ","
]
for _ in 0...N {
for firstChar in alphabet {
for middleChar in alphabet {
for lastChar in alphabet {
_ = ((firstChar == middleChar) != (middleChar < lastChar))
}
}
}
}
}
| apache-2.0 | 2a6d1a73b403cfe7f105e02b79e26bdd | 33.108108 | 80 | 0.461965 | 3.312336 | false | true | false | false |
LYM-mg/MGOFO | MGOFO/MGOFO/Class/Home/Source/LBXScanViewStyle.swift | 2 | 2705 | //
// LBXScanViewStyle.swift
// swiftScan https://github.com/MxABC/swiftScan
//
// Created by xialibing on 15/12/8.
// Copyright © 2015年 xialibing. All rights reserved.
//
import UIKit
///扫码区域动画效果
public enum LBXScanViewAnimationStyle
{
case LineMove //线条上下移动
case NetGrid//网格
case LineStill//线条停止在扫码区域中央
case None //无动画
}
///扫码区域4个角位置类型
public enum LBXScanViewPhotoframeAngleStyle
{
case Inner//内嵌,一般不显示矩形框情况下
case Outer//外嵌,包围在矩形框的4个角
case On //在矩形框的4个角上,覆盖
}
public struct LBXScanViewStyle
{
// MARK: - -中心位置矩形框
/// 是否需要绘制扫码矩形框,默认YES
public var isNeedShowRetangle:Bool = true
/**
* 默认扫码区域为正方形,如果扫码区域不是正方形,设置宽高比
*/
public var whRatio:CGFloat = 1.0
/**
@brief 矩形框(视频显示透明区)域向上移动偏移量,0表示扫码透明区域在当前视图中心位置,如果负值表示扫码区域下移
*/
public var centerUpOffset:CGFloat = 44
/**
* 矩形框(视频显示透明区)域离界面左边及右边距离,默认60
*/
public var xScanRetangleOffset:CGFloat = 60
/**
@brief 矩形框线条颜色,默认白色
*/
public var colorRetangleLine = UIColor.white
//MARK -矩形框(扫码区域)周围4个角
/**
@brief 扫码区域的4个角类型
*/
public var photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Outer
//4个角的颜色
public var colorAngle = UIColor(red: 0.0, green: 167.0/255.0, blue: 231.0/255.0, alpha: 1.0)
//扫码区域4个角的宽度和高度
public var photoframeAngleW:CGFloat = 24.0
public var photoframeAngleH:CGFloat = 24.0
/**
@brief 扫码区域4个角的线条宽度,默认6,建议8到4之间
*/
public var photoframeLineW:CGFloat = 6
//MARK: ----动画效果
/**
@brief 扫码动画效果:线条或网格
*/
public var anmiationStyle = LBXScanViewAnimationStyle.LineMove
/**
* 动画效果的图像,如线条或网格的图像
*/
public var animationImage:UIImage?
// MARK: -非识别区域颜色,默认 RGBA (0,0,0,0.5),范围(0--1)
public var color_NotRecoginitonArea:UIColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5);
public init() {
animationImage = UIImage(named: "MGCodeScan.bundle/qrcode_Scan_weixin_Line.png")
}
}
| mit | 6e3190e4b686c0a873b63c8de9512587 | 17.22807 | 103 | 0.626564 | 3.314195 | false | false | false | false |
ericvergnaud/antlr4 | runtime/Swift/Sources/Antlr4/TokenStream.swift | 9 | 5509 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
///
/// An _org.antlr.v4.runtime.IntStream_ whose symbols are _org.antlr.v4.runtime.Token_ instances.
///
public protocol TokenStream: IntStream {
///
/// Get the _org.antlr.v4.runtime.Token_ instance associated with the value returned by
/// _#LA LA(k)_. This method has the same pre- and post-conditions as
/// _org.antlr.v4.runtime.IntStream#LA_. In addition, when the preconditions of this method
/// are met, the return value is non-null and the value of
/// `LT(k).getType()==LA(k)`.
///
/// - SeeAlso: org.antlr.v4.runtime.IntStream#LA
///
func LT(_ k: Int) throws -> Token?
///
/// Gets the _org.antlr.v4.runtime.Token_ at the specified `index` in the stream. When
/// the preconditions of this method are met, the return value is non-null.
///
/// The preconditions for this method are the same as the preconditions of
/// _org.antlr.v4.runtime.IntStream#seek_. If the behavior of `seek(index)` is
/// unspecified for the current state and given `index`, then the
/// behavior of this method is also unspecified.
///
/// The symbol referred to by `index` differs from `seek()` only
/// in the case of filtering streams where `index` lies before the end
/// of the stream. Unlike `seek()`, this method does not adjust
/// `index` to point to a non-ignored symbol.
///
/// - Throws: ANTLRError.illegalArgument if {code index} is less than 0
/// - Throws: ANTLRError.unsupportedOperation if the stream does not support
/// retrieving the token at the specified index
///
func get(_ index: Int) throws -> Token
///
/// Gets the underlying _org.antlr.v4.runtime.TokenSource_ which provides tokens for this
/// stream.
///
func getTokenSource() -> TokenSource
///
/// Return the text of all tokens within the specified `interval`. This
/// method behaves like the following code (including potential exceptions
/// for violating preconditions of _#get_, but may be optimized by the
/// specific implementation.
///
///
/// TokenStream stream = ...;
/// String text = "";
/// for (int i = interval.a; i <= interval.b; i++) {
/// text += stream.get(i).getText();
/// }
///
///
/// - Parameter interval: The interval of tokens within this stream to get text
/// for.
/// - Returns: The text of all tokens within the specified interval in this
/// stream.
///
///
func getText(_ interval: Interval) throws -> String
///
/// Return the text of all tokens in the stream. This method behaves like the
/// following code, including potential exceptions from the calls to
/// _org.antlr.v4.runtime.IntStream#size_ and _#getText(org.antlr.v4.runtime.misc.Interval)_, but may be
/// optimized by the specific implementation.
///
///
/// TokenStream stream = ...;
/// String text = stream.getText(new Interval(0, stream.size()));
///
///
/// - Returns: The text of all tokens in the stream.
///
func getText() throws -> String
///
/// Return the text of all tokens in the source interval of the specified
/// context. This method behaves like the following code, including potential
/// exceptions from the call to _#getText(org.antlr.v4.runtime.misc.Interval)_, but may be
/// optimized by the specific implementation.
///
/// If `ctx.getSourceInterval()` does not return a valid interval of
/// tokens provided by this stream, the behavior is unspecified.
///
///
/// TokenStream stream = ...;
/// String text = stream.getText(ctx.getSourceInterval());
///
///
/// - Parameter ctx: The context providing the source interval of tokens to get
/// text for.
/// - Returns: The text of all tokens within the source interval of `ctx`.
///
func getText(_ ctx: RuleContext) throws -> String
///
/// Return the text of all tokens in this stream between `start` and
/// `stop` (inclusive).
///
/// If the specified `start` or `stop` token was not provided by
/// this stream, or if the `stop` occurred before the `start`
/// token, the behavior is unspecified.
///
/// For streams which ensure that the _org.antlr.v4.runtime.Token#getTokenIndex_ method is
/// accurate for all of its provided tokens, this method behaves like the
/// following code. Other streams may implement this method in other ways
/// provided the behavior is consistent with this at a high level.
///
///
/// TokenStream stream = ...;
/// String text = "";
/// for (int i = start.getTokenIndex(); i <= stop.getTokenIndex(); i++) {
/// text += stream.get(i).getText();
/// }
///
///
/// - Parameter start: The first token in the interval to get text for.
/// - Parameter stop: The last token in the interval to get text for (inclusive).
/// - Throws: ANTLRError.unsupportedOperation if this stream does not support
/// this method for the specified tokens
/// - Returns: The text of all tokens lying between the specified `start`
/// and `stop` tokens.
///
///
func getText(_ start: Token?, _ stop: Token?) throws -> String
}
| bsd-3-clause | 5a4d6afbd75a0e34d9b3ba3b1e162680 | 39.211679 | 108 | 0.630241 | 4.300546 | false | false | false | false |
justindhill/Jiramazing | src/model/Project.swift | 1 | 6177 | //
// Project.swift
// Jiramazing
//
// Created by Justin Hill on 7/23/16.
// Copyright © 2016 Justin Hill. All rights reserved.
//
import Foundation
@objc(JRAProject) public class Project: NSObject, NSCoding {
public var url: NSURL?
@objc(identifier) public var id: String?
public var key: String?
public var projectDescription: String?
public var lead: User?
// TODO: components support
public var issueTypes: [IssueType]?
public var browseUrl: NSURL?
public var email: String?
public var assigneeType: String?
public var versions: [Version]?
public var name: String?
public var roles: [String: NSURL]?
public var avatarUrls: [AvatarSize: NSURL]?
public var category: ProjectCategory?
// Coding keys
private let UrlKey = "url"
private let IdKey = "id"
private let KeyKey = "key"
private let DescriptionKey = "description"
private let LeadKey = "lead"
private let IssueTypesKey = "issueTypes"
private let BrowseUrlKey = "browseUrl"
private let EmailKey = "emailKey"
private let AssigneeTypeKey = "assigneeType"
private let VersionsKey = "versions"
private let NameKey = "name"
private let RolesKey = "roles"
private let AvatarUrlsKey = "avatarUrls"
private let CategoryKey = "category"
init(attributes: [String: AnyObject]) {
super.init()
self.id = attributes["id"] as? String
self.key = attributes["key"] as? String
self.projectDescription = attributes["description"] as? String
self.email = attributes["email"] as? String
self.assigneeType = attributes["assigneeType"] as? String
self.name = attributes["name"] as? String
if let urlString = attributes["self"] as? String, let url = NSURL(string: urlString) {
self.url = url
}
if let urlString = attributes["url"] as? String, let url = NSURL(string: urlString) {
self.browseUrl = url
}
if let leadAttributes = attributes["lead"] as? [String: AnyObject] {
self.lead = User(attributes: leadAttributes)
}
if let issueTypesAttributes = attributes["issueTypes"] as? [[String: AnyObject]] {
self.issueTypes = issueTypesAttributes.map({ (issueTypeAttributes) -> IssueType in
return IssueType(attributes: issueTypeAttributes)
})
}
if let rolesAttributes = attributes["roles"] as? [String: String] {
var roles = [String: NSURL]()
for (roleName, roleUrlString) in rolesAttributes {
if let roleUrl = NSURL(string: roleUrlString) {
roles[roleName] = roleUrl
}
}
self.roles = roles
}
if let versionsAttributes = attributes["versions"] as? [[String: AnyObject]] {
self.versions = versionsAttributes.map({ (versionAttributes) -> Version in
return Version(attributes: versionAttributes)
})
}
if let avatarUrlsAttributes = attributes["avatarUrls"] as? [String: String] {
self.avatarUrls = avatarUrlsAttributes.avatarSizeMap()
}
if let projectCategoryAttributes = attributes["projectCategory"] as? [String: AnyObject] {
self.category = ProjectCategory(attributes: projectCategoryAttributes)
}
}
public required init?(coder d: NSCoder) {
super.init()
self.url = d.decodeObjectForKey(UrlKey) as? NSURL
self.id = d.decodeObjectForKey(IdKey) as? String
self.key = d.decodeObjectForKey(KeyKey) as? String
self.projectDescription = d.decodeObjectForKey(DescriptionKey) as? String
self.lead = d.decodeObjectForKey(LeadKey) as? User
self.issueTypes = d.decodeObjectForKey(IssueTypesKey) as? [IssueType]
self.browseUrl = d.decodeObjectForKey(BrowseUrlKey) as? NSURL
self.email = d.decodeObjectForKey(EmailKey) as? String
self.assigneeType = d.decodeObjectForKey(AssigneeTypeKey) as? String
self.versions = d.decodeObjectForKey(VersionsKey) as? [Version]
self.name = d.decodeObjectForKey(NameKey) as? String
self.roles = d.decodeObjectForKey(RolesKey) as? [String: NSURL]
if let decodableUrls = d.decodeObjectForKey(AvatarUrlsKey) as? [Int: NSURL] {
var decodedUrls = [AvatarSize: NSURL]()
for (key, value) in decodableUrls {
if let avatarSize = AvatarSize(rawValue: key) {
decodedUrls[avatarSize] = value
}
}
self.avatarUrls = decodedUrls
}
self.category = d.decodeObjectForKey(CategoryKey) as? ProjectCategory
}
override public var description: String {
get {
let key = self.key ?? "nil"
let id = self.id ?? "nil"
return super.description.stringByAppendingString(" \(key) - \(id)")
}
}
public func encodeWithCoder(c: NSCoder) {
c.encodeObject(self.url, forKey: UrlKey)
c.encodeObject(self.id, forKey: IdKey)
c.encodeObject(self.key, forKey: KeyKey)
c.encodeObject(self.projectDescription, forKey: DescriptionKey)
c.encodeObject(self.lead, forKey: LeadKey)
c.encodeObject(self.issueTypes, forKey: IssueTypesKey)
c.encodeObject(self.browseUrl, forKey: BrowseUrlKey)
c.encodeObject(self.email, forKey: EmailKey)
c.encodeObject(self.assigneeType, forKey: AssigneeTypeKey)
c.encodeObject(self.versions, forKey: VersionsKey)
c.encodeObject(self.name, forKey: NameKey)
c.encodeObject(self.roles, forKey: RolesKey)
if let avatarUrls = self.avatarUrls {
var encodableUrls = [Int: NSURL]()
for (key, value) in avatarUrls {
encodableUrls[key.rawValue] = value
}
c.encodeObject(encodableUrls, forKey: AvatarUrlsKey)
} else {
c.encodeObject(nil, forKey: AvatarUrlsKey)
}
c.encodeObject(self.category, forKey: CategoryKey)
}
}
| mit | 76440b587289d2efd6089fd8f442ed0e | 35.761905 | 98 | 0.625648 | 4.517922 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureInput/Carthage/Checkouts/RxDataSources/Sources/DataSources+Rx/RxCollectionViewSectionedAnimatedDataSource.swift | 22 | 3903 | //
// RxCollectionViewSectionedAnimatedDataSource.swift
// RxExample
//
// Created by Krunoslav Zaher on 7/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
/*
This is commented becuse collection view has bugs when doing animated updates.
Take a look at randomized sections.
*/
open class RxCollectionViewSectionedAnimatedDataSource<S: AnimatableSectionModelType>
: CollectionViewSectionedDataSource<S>
, RxCollectionViewDataSourceType {
public typealias Element = [S]
public var animationConfiguration = AnimationConfiguration()
// For some inexplicable reason, when doing animated updates first time
// it crashes. Still need to figure out that one.
var dataSet = false
private let disposeBag = DisposeBag()
// This subject and throttle are here
// because collection view has problems processing animated updates fast.
// This should somewhat help to alleviate the problem.
private let partialUpdateEvent = PublishSubject<(UICollectionView, Event<Element>)>()
public override init() {
super.init()
self.partialUpdateEvent
// so in case it does produce a crash, it will be after the data has changed
.observeOn(MainScheduler.asyncInstance)
// Collection view has issues digesting fast updates, this should
// help to alleviate the issues with them.
.throttle(0.5, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] event in
self?.collectionView(event.0, throttledObservedEvent: event.1)
})
.addDisposableTo(disposeBag)
}
/**
This method exists because collection view updates are throttled because of internal collection view bugs.
Collection view behaves poorly during fast updates, so this should remedy those issues.
*/
open func collectionView(_ collectionView: UICollectionView, throttledObservedEvent event: Event<Element>) {
UIBindingObserver(UIElement: self) { dataSource, newSections in
let oldSections = dataSource.sectionModels
do {
// if view is not in view hierarchy, performing batch updates will crash the app
if collectionView.window == nil {
dataSource.setSections(newSections)
collectionView.reloadData()
return
}
let differences = try differencesForSectionedView(initialSections: oldSections, finalSections: newSections)
for difference in differences {
dataSource.setSections(difference.finalSections)
collectionView.performBatchUpdates(difference, animationConfiguration: self.animationConfiguration)
}
}
catch let e {
#if DEBUG
print("Error while binding data animated: \(e)\nFallback to normal `reloadData` behavior.")
rxDebugFatalError(e)
#endif
self.setSections(newSections)
collectionView.reloadData()
}
}.on(event)
}
open func collectionView(_ collectionView: UICollectionView, observedEvent: Event<Element>) {
UIBindingObserver(UIElement: self) { dataSource, newSections in
#if DEBUG
self._dataSourceBound = true
#endif
if !self.dataSet {
self.dataSet = true
dataSource.setSections(newSections)
collectionView.reloadData()
}
else {
let element = (collectionView, observedEvent)
dataSource.partialUpdateEvent.on(.next(element))
}
}.on(observedEvent)
}
}
| mit | 2ee28b060250f698eb0d8db7e4cde07a | 37.633663 | 123 | 0.638903 | 5.679767 | false | false | false | false |
Hodglim/hacking-with-swift | Project-14/WhackAPenguin/WhackSlot.swift | 1 | 1841 | //
// WhackSlot.swift
// WhackAPenguin
//
// Created by Darren Hodges on 27/10/2015.
// Copyright © 2015 Darren Hodges. All rights reserved.
//
import UIKit
import SpriteKit
class WhackSlot: SKNode
{
var charNode: SKSpriteNode!
var visible = false
var isHit = false
func configureAtPosition(pos: CGPoint)
{
position = pos
// Hole
let sprite = SKSpriteNode(imageNamed: "whackHole")
addChild(sprite)
// Mask
let cropNode = SKCropNode()
cropNode.position = CGPoint(x: 0, y: 15)
cropNode.zPosition = 1
cropNode.maskNode = SKSpriteNode(imageNamed: "whackMask")
// Penguin
charNode = SKSpriteNode(imageNamed: "penguinGood")
charNode.position = CGPoint(x: 0, y: -90)
charNode.name = "character"
cropNode.addChild(charNode)
addChild(cropNode)
}
func show(hideTime hideTime: Double)
{
if visible { return }
// Reset scale (can get increased when penguin is tapped)
charNode.xScale = 1
charNode.yScale = 1
charNode.runAction(SKAction.moveByX(0, y: 80, duration: 0.05))
visible = true
isHit = false
if RandomInt(min: 0, max: 2) == 0
{
charNode.texture = SKTexture(imageNamed: "penguinGood")
charNode.name = "charFriend"
}
else
{
charNode.texture = SKTexture(imageNamed: "penguinEvil")
charNode.name = "charEnemy"
}
// Hide again after a delay
RunAfterDelay(hideTime * 3.5)
{
[unowned self] in
self.hide()
}
}
func hide()
{
if !visible { return }
charNode.runAction(SKAction.moveByX(0, y:-80, duration:0.05))
visible = false
}
func hit()
{
isHit = true
let delay = SKAction.waitForDuration(0.25)
let hide = SKAction.moveByX(0, y:-80, duration:0.5)
let notVisible = SKAction.runBlock { [unowned self] in self.visible = false }
charNode.runAction(SKAction.sequence([delay, hide, notVisible]))
}
}
| mit | c8e2da16d7d997206615e0245fff2ecf | 19.674157 | 79 | 0.673913 | 3.205575 | false | false | false | false |
kenechilearnscode/AppUpdateCheck | AppUpdateCheck.swift | 1 | 1449 | //
// AppUpdateCheck.swift
//
//
// Created by Kc on 03/11/2015.
//
//
import Foundation
class AppUpdateCheck {
let defaults = NSUserDefaults.standardUserDefaults() // gets instance of NSUserDefaults for persistent store
let currentAppVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String // gets current app version on user's device
func saveCurrentVersionToDefaults() {
// saves currentAppVersion to defaults
defaults.setObject(currentAppVersion, forKey: "appVersion")
defaults.synchronize()
}
func hasAppBeenUpdated() -> Bool {
var appUpdated = false // indicates whether app has been updated or not
let previousAppVersion = defaults.stringForKey("appVersion") // checks stored app version in NSUserDefaults
if previousAppVersion == nil {
// first run, no appVersion has ever been saved to NSUserDefaults
saveCurrentVersionToDefaults()
} else if previousAppVersion != currentAppVersion {
// app versions are different, thus the app has been updated
saveCurrentVersionToDefaults()
appUpdated = true
}
print("The current app version is: \(currentAppVersion). \n The app has been updated: \(appUpdated)")
return appUpdated
}
}
| mit | e520af3e5217ace6c46d13766ddd6d60 | 31.2 | 162 | 0.638371 | 5.772908 | false | false | false | false |
cuzv/TinyCoordinator | Sample/UICollectionViewSample/CollectionViewCell.swift | 1 | 2575 | //
// CollectionViewCell.swift
// Copyright (c) 2016 Red Rain (https://github.com/cuzv).
//
// 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 TinyCoordinator
import SnapKit
class CollectionViewCell: UICollectionViewCell, TCReusableViewSupport {
let nameLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor.brown
label.font = UIFont.systemFont(ofSize: 17)
label.lineBreakMode = .byCharWrapping
label.numberOfLines = 0
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = UIColor.lightGray
nameLabel.layer.borderColor = UIColor.red.cgColor
nameLabel.layer.borderWidth = 1
contentView.addSubview(nameLabel)
nameLabel.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(contentView).inset(UIEdgeInsetsMake(8, 8, 8, 8))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
debugPrint("\(#file):\(#line):\(#function)")
}
override func layoutSubviews() {
nameLabel.preferredMaxLayoutWidth = bounds.width - 16
super.layoutSubviews()
}
func populate(data: TCDataType) {
if let data = data as? CellDataItem {
nameLabel.text = data.name
} else if let data = data as? CellDataItem2 {
nameLabel.text = data.name
}
}
}
| mit | 2d48d981aea3fd16ef1f7e5663b8dc5f | 35.267606 | 81 | 0.677282 | 4.63964 | false | false | false | false |
whitepaperclip/Exsilio-iOS | Exsilio/WaypointViewController.swift | 1 | 8915 | //
// WaypointViewController.swift
// Exsilio
//
// Created by Nick Kezhaya on 4/29/16.
//
//
import UIKit
import Fusuma
import SwiftyJSON
import Alamofire
import SCLAlertView
import FontAwesome_swift
import SVProgressHUD
import Mapbox
class WaypointViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var nameField: UITextField?
@IBOutlet var descriptionField: UITextField?
@IBOutlet var selectedImageView: UIImageView?
@IBOutlet var openMapButton: EXButton?
@IBOutlet var pickImageButton: EXButton?
var selectedImage: UIImage? {
didSet {
selectedImageView?.image = selectedImage
}
}
var selectedPoint: CLLocationCoordinate2D?
var waypoint: Waypoint?
override func viewDidLoad() {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UI.BackIcon, style: .plain, target: self, action: #selector(dismissModal))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .done, target: self, action: #selector(saveWaypoint))
self.openMapButton?.darkBorderStyle()
self.pickImageButton?.darkBorderStyle()
self.openMapButton?.setIcon(.map)
self.pickImageButton?.setIcon(.camera)
if let waypoint = self.waypoint {
if let name = waypoint["name"] as? String {
self.nameField?.text = name
}
if let description = waypoint["description"] as? String {
self.descriptionField?.text = description
}
if let latitude = waypoint["latitude"] as? Double, let longitude = waypoint["longitude"] as? Double {
self.pointSelected(CLLocationCoordinate2D(latitude: latitude, longitude: longitude))
}
if let imageURL = waypoint["image_url"] as? String {
if imageURL != API.MissingImagePath {
SVProgressHUD.show()
Alamofire.request(imageURL).responseImage { response in
SVProgressHUD.dismiss()
if let image = response.result.value {
self.fusumaImageSelected(image)
}
}
}
}
}
self.nameField?.becomeFirstResponder()
}
@IBAction func openMap() {
if let navController = self.storyboard!.instantiateViewController(withIdentifier: "MapNavigationController") as? UINavigationController {
let vc = navController.viewControllers.first as! MapViewController
vc.delegate = self
vc.startingPoint = self.selectedPoint
present(navController, animated: true, completion: nil)
}
}
func dismissModal() {
self.navigationController?.popViewController(animated: true)
}
func validateMessage() -> Bool {
var message = ""
if self.nameField?.text == nil || self.nameField!.text!.isEmpty {
message = "You forgot to put a name in."
} else if self.selectedPoint == nil {
message = "You forgot to select a point on the map."
}
if !message.isEmpty {
SCLAlertView().showError("Whoops!", subTitle: message, closeButtonTitle: "OK")
return false
}
return true
}
func pointSelected(_ coordinate: CLLocationCoordinate2D) {
selectedPoint = coordinate
openMapButton?.layer.borderWidth = 0
openMapButton?.backgroundColor = UI.GreenColor
openMapButton?.tintColor = .white
openMapButton?.setIcon(.check)
openMapButton?.updateColor(.white)
}
func saveWaypoint() {
if !self.validateMessage() {
return
}
var waypoint: Waypoint = self.waypoint == nil ? [:] : self.waypoint!
if let name = self.nameField?.text {
waypoint["name"] = name
}
if let description = self.descriptionField?.text {
waypoint["description"] = description
}
if let coords = self.selectedPoint {
waypoint["latitude"] = coords.latitude
waypoint["longitude"] = coords.longitude
}
if let image = self.selectedImage {
if waypoint["photo"] == nil || (waypoint["photo"] as! UIImage) != image {
waypoint["photo"] = image
}
}
if let tourId = CurrentTourSingleton.sharedInstance.tour["id"] as? Int {
var method: Alamofire.HTTPMethod = .post
let waypointId = waypoint["id"]
var url = "\(API.URL)\(API.ToursPath)/\(tourId)\(API.WaypointsPath)"
if waypointId != nil {
method = .put
url = url + "/\(waypointId!)"
}
var urlRequest: URLRequest
do {
urlRequest = try URLRequest(url: url, method: method, headers: API.authHeaders())
} catch { return }
SVProgressHUD.show()
Alamofire.upload(
multipartFormData: { multipartFormData in
let waypointName = waypoint["name"] as! String
let latitude = waypoint["latitude"] as! Double
let longitude = waypoint["longitude"] as! Double
multipartFormData.append(waypointName.data(using: String.Encoding.utf8)!, withName: "waypoint[name]")
multipartFormData.append("\(latitude)".data(using: String.Encoding.utf8)!, withName: "waypoint[latitude]")
multipartFormData.append("\(longitude)".data(using: String.Encoding.utf8)!, withName: "waypoint[longitude]")
if let description = waypoint["description"] as? String {
multipartFormData.append(description.data(using: String.Encoding.utf8)!, withName: "waypoint[description]")
}
if let image = waypoint["photo"] as? UIImage {
multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "waypoint[image]", fileName: "image.png", mimeType: "image/png")
}
},
with: urlRequest,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
switch response.result {
case .success(let json):
SVProgressHUD.dismiss()
if let errors = JSON(json)["errors"].string {
SCLAlertView().showError("Whoops!", subTitle: errors, closeButtonTitle: "OK")
} else {
self.dismissModal()
}
break
default:
SVProgressHUD.dismiss()
break
}
}
default:
SVProgressHUD.dismiss()
break
}
}
)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.descriptionField {
self.descriptionField?.resignFirstResponder()
} else {
self.descriptionField?.becomeFirstResponder()
}
return true
}
}
extension WaypointViewController: FusumaDelegate {
func fusumaVideoCompleted(withFileURL fileURL: URL) {
}
@IBAction func pickImage() {
let fusumaViewController = FusumaViewController()
fusumaViewController.delegate = self
self.present(fusumaViewController, animated: true, completion: nil)
}
func fusumaImageSelected(_ image: UIImage) {
self.selectedImage = image
self.pickImageButton?.layer.borderWidth = 0
self.pickImageButton?.backgroundColor = UI.GreenColor
self.pickImageButton?.tintColor = .white
self.pickImageButton?.setIcon(.check)
self.pickImageButton?.setTitleColor(.white, for: .normal)
self.pickImageButton?.updateColor(.white)
}
func fusumaCameraRollUnauthorized() {
SCLAlertView().showError("Error", subTitle: "We need to access the camera in order to designate a photo for this waypoint.", closeButtonTitle: "OK")
}
}
extension WaypointViewController: MapViewDelegate {
func mapView(_ mapView: MGLMapView, didTapAt coordinate: CLLocationCoordinate2D) {
mapView.clear()
let annotation = MGLPointAnnotation()
annotation.coordinate = coordinate
mapView.addAnnotation(annotation)
pointSelected(coordinate)
}
}
| mit | 7acb9ed01d34df13cbd54c970525678b | 34.376984 | 157 | 0.571845 | 5.610447 | false | false | false | false |
realm/SwiftLint | Source/swiftlint/Helpers/ProgressBar.swift | 1 | 2072 | import Dispatch
import Foundation
import SwiftLintFramework
// Inspired by https://github.com/jkandzi/Progress.swift
actor ProgressBar {
private var index = 1
private var lastPrintedTime: TimeInterval = 0.0
private let startTime = uptime()
private let count: Int
init(count: Int) {
self.count = count
}
func initialize() {
// When progress is printed, the previous line is reset, so print an empty line before anything else
queuedPrintError("")
}
func printNext() {
guard index <= count else { return }
let currentTime = uptime()
if currentTime - lastPrintedTime > 0.1 || index == count {
let lineReset = "\u{1B}[1A\u{1B}[K"
let bar = makeBar()
let timeEstimate = makeTimeEstimate(currentTime: currentTime)
let lineContents = "\(index) of \(count) \(bar) \(timeEstimate)"
queuedPrintError("\(lineReset)\(lineContents)")
lastPrintedTime = currentTime
}
index += 1
}
// MARK: - Private
private func makeBar() -> String {
let barLength = 30
let completedBarElements = Int(Double(barLength) * (Double(index) / Double(count)))
let barArray = Array(repeating: "=", count: completedBarElements) +
Array(repeating: " ", count: barLength - completedBarElements)
return "[\(barArray.joined())]"
}
private func makeTimeEstimate(currentTime: TimeInterval) -> String {
let totalTime = currentTime - startTime
let itemsPerSecond = Double(index) / totalTime
let estimatedTimeRemaining = Double(count - index) / itemsPerSecond
let estimatedTimeRemainingString = "\(Int(estimatedTimeRemaining))s"
return "ETA: \(estimatedTimeRemainingString) (\(Int(itemsPerSecond)) files/s)"
}
}
#if os(Linux)
// swiftlint:disable:next identifier_name
private let NSEC_PER_SEC = 1_000_000_000
#endif
private func uptime() -> TimeInterval {
Double(DispatchTime.now().uptimeNanoseconds) / Double(NSEC_PER_SEC)
}
| mit | 97a9e5a178a71e71eaa003cba2e07f87 | 31.888889 | 108 | 0.642375 | 4.465517 | false | false | false | false |
Noah-Huppert/baking-app | baking-app/IngredientsWarningViewController.swift | 1 | 2013 | //
// IngredientsWarningViewController.swift
// baking-app
//
// Created by Noah Huppert on 1/19/16.
// Copyright © 2016 noahhuppert.com. All rights reserved.
//
import UIKit
class IngredientsWarningViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var recipe: Recipe?
var uiIngredients: [UIIngredient] = [UIIngredient]()
override func viewDidLoad() {
super.viewDidLoad()
for ing in (recipe?.ingredients)! {
uiIngredients.append(UIIngredient(ingredient: ing));
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let dc = segue.destinationViewController as! StepsViewController
dc.recipe = recipe
}
@IBAction func onContinueButtonClicked(sender: AnyObject) {
performSegueWithIdentifier("to_steps", sender: nil)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (recipe?.ingredients.count)!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = indexPath.row
let cell = tableView.dequeueReusableCellWithIdentifier("cell")
let ingredient = uiIngredients[row]
cell?.textLabel?.text = "\(ingredient.name) X \(ingredient.ammount)"
if ingredient.checked {
cell?.accessoryType = .Checkmark
} else {
cell?.accessoryType = .None
}
return cell!
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let row = indexPath.row
uiIngredients[row].checked = !uiIngredients[row].checked
if uiIngredients[row].checked {
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark
} else {
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .None
}
}
}
| mit | 1f64854e11b6fb6f00dbaa3f3b3ef8a4 | 31.451613 | 109 | 0.65159 | 5.308707 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Phatav2/HATProfile.swift | 1 | 3093 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
public struct HATProfile: HATObject, HatApiType {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `recordID` in JSON is `id`
* `endpoint` in JSON is `endpoint`
* `data` in JSON is `data`
*/
private enum CodingKeys: String, CodingKey {
case recordID = "id"
case endpoint = "endpoint"
case data = "data"
}
// MARK: - Variables
/// The endpoint the data are coming from. Optional
public var endpoint: String? = ""
/// The record ID of the data. Optional
public var recordID: String? = ""
/// The data of the profile
public var data: HATProfileData = HATProfileData()
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public init(from dict: Dictionary<String, JSON>) {
self.init()
self.initialize(dict: dict)
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public mutating func initialize(dict: Dictionary<String, JSON>) {
if let tempRecordId: String = (dict[CodingKeys.recordID.rawValue]?.stringValue) {
recordID = tempRecordId
}
if let tempEndPoint: String = (dict[CodingKeys.endpoint.rawValue]?.stringValue) {
endpoint = tempEndPoint
}
if let tempData: [String: JSON] = (dict[CodingKeys.data.rawValue]?.dictionaryValue) {
data = HATProfileData(dict: tempData)
}
}
// MARK: - HatApiType Protocol
/**
It initialises everything from the received Dictionary file from the cache
- fromCache: The dictionary file received from the cache
*/
public mutating func initialize(fromCache: Dictionary<String, Any>) {
let json: JSON = JSON(fromCache)
self.initialize(dict: json.dictionaryValue)
}
// MARK: - JSON Mapper
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [
CodingKeys.endpoint.rawValue: self.endpoint ?? "",
CodingKeys.recordID.rawValue: self.recordID ?? "",
CodingKeys.data.rawValue: self.data.toJSON()
]
}
}
| mpl-2.0 | 9a34f9cd9e8f4c2bd4b2824487e083ad | 25.895652 | 93 | 0.588749 | 4.707763 | false | false | false | false |
octplane/Rapide | Rapide/AppDelegate.swift | 1 | 7498 | //
// AppDelegate.swift
// Rapide
//
// Created by Pierre Baillet on 11/06/2014.
// Copyright (c) 2014 Pierre Baillet. All rights reserved.
//
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate, NSStreamDelegate, NSTextFieldDelegate {
@IBOutlet var window :NSWindow!
@IBOutlet var clipView :NSClipView!
@IBOutlet var textView: NSTextView!
@IBOutlet var tf :NSTextField!
var inputStream :NSInputStream?
var outputStream :NSOutputStream?
var lineRemain :String = ""
let nickname :String = "SpectreMan_"
var server :CFString = "irc.freenode.org"
var port :UInt32 = 6667
var ircPassword :String? = nil
var motto :String = "Plus rapide qu'un missile !"
var channel :String = "#swift-test"
enum ConnectionStatus: Int {
case Disconnected, BeforePassword, BeforeNick, BeforeUser, AfterUser, Connected
func toString() -> String {
switch self {
case .Disconnected:
return "Disconnected"
case .BeforePassword:
return "Before Password"
case .BeforeNick:
return "Before Nick Setting"
case .BeforeUser:
return "Before User Setting"
case .AfterUser:
return "After User Setting"
case .Connected:
return "Connected"
}
}
}
var status :ConnectionStatus = ConnectionStatus.Disconnected
func get<T>(input: T?, orElse: T) -> T {
if let i = input {
return i
}
return orElse
}
func getI(input: String?, orElse: UInt32) -> UInt32 {
if let i = input?.toInt() {
return UInt32(i)
}
return orElse
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
let pi = NSProcessInfo.processInfo()
server = get(pi.environment["server"] as? String, orElse: server as String)
port = getI(pi.environment["port"] as? String, orElse: port)
ircPassword = pi.environment["password"] as? String
channel = get(pi.environment["channel"] as? String, orElse: channel)
println("Connecting to \(server):\(port) and joining \(channel)")
var readStream :Unmanaged<CFReadStream>?
var writeStream :Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(nil, server, 6667, &readStream, &writeStream)
self.inputStream = readStream!.takeUnretainedValue()
self.outputStream = writeStream!.takeUnretainedValue()
self.inputStream!.delegate = self
self.outputStream!.delegate = self
self.inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
self.outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
self.inputStream!.open()
self.outputStream!.open()
}
func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent){
var msg :String = ""
switch eventCode {
case NSStreamEvent.HasBytesAvailable:
if aStream == self.inputStream {
var data = [UInt8](count: 4096, repeatedValue: 0)
let read = self.inputStream!.read(&data, maxLength: 4096)
let strData = NSString(bytes: data, length: read, encoding: NSUTF8StringEncoding)
handleInput(strData! as String)
}
case NSStreamEvent.HasSpaceAvailable:
if aStream == self.outputStream {
msg = "Can write bytes"
handleCommunication()
} else {
msg = "Can write on inputStream ??!"
}
case NSStreamEvent.OpenCompleted:
msg = "Open has completed"
self.status = ConnectionStatus.BeforePassword
case NSStreamEvent.ErrorOccurred:
msg = "Something wrong happened..."
default:
msg = "Something happened !"
}
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func handleInput(input :String) {
var lines: [String] = split(input) { $0 == "\r\n" }
// what's remaining to process
if lines.count > 0 {
lines[0] = lineRemain + lines[0]
} else {
lines = [lineRemain]
}
lineRemain = lines[lines.count - 1]
let parsable = lines[0...(lines.count-1)]
for (line) in parsable {
let parts = line.componentsSeparatedByString(" ")
println(line)
textView.insertText( line + "\n" )
let from = parts[0]
let code = parts[1]
if from == "PING" {
sendMessage("PONG \(code)")
} else if parts.count > 2 {
let dest = parts[2]
let rest = " ".join(parts[3...(parts.count - 1)])
if code == "JOIN" {
let chan = dest.substringFromIndex(advance(dest.startIndex,1))
sendMessage("PRIVMSG \(chan) :\(motto)")
}
if code == "PRIVMSG" {
if rest.rangeOfString("ping", options: nil, range: nil, locale: nil) != nil {
sendMessage("PRIVMSG \(dest) :pong.")
}
if rest.rangeOfString("king", options: nil, range: nil, locale: nil) != nil {
sendMessage("PRIVMSG \(dest) :kong.")
}
}
}
}
}
func handleCommunication() {
switch self.status {
case ConnectionStatus.BeforePassword:
if ircPassword != nil {
sendMessage("PASS \(ircPassword)")
}
println("PASS or not.")
status = ConnectionStatus.BeforeNick
// case ConnectionStatus.BeforeNick:
println("Sending Nick")
let msg = "NICK \(nickname)"
sendMessage(msg)
status = ConnectionStatus.BeforeUser
// case ConnectionStatus.BeforeUser:
println("Sending USER info")
sendMessage("USER \(nickname) localhost servername Rapido Bot")
status = ConnectionStatus.AfterUser
case ConnectionStatus.AfterUser:
println("JOINing")
sendMessage("JOIN \(channel)")
status = ConnectionStatus.Connected
default:
let c = 1
}
}
func sendMessage(msg: String) -> Int {
let message = msg + "\r\n"
let l = message.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
var data = [UInt8](count: l, repeatedValue: 0)
let r:Range = message.startIndex...(message.endIndex.predecessor())
let ret:Bool = message.getBytes(&data, maxLength: l, usedLength: nil, encoding: NSUTF8StringEncoding, options: nil, range: r, remainingRange: nil)
return self.outputStream!.write(data, maxLength: l)
}
override func controlTextDidEndEditing(notif :NSNotification) {
if notif.object as! NSObject == tf {
sendMessage("PRIVMSG \(channel) :"+tf.stringValue)
}
}
}
| mit | cc15e3100c0842ca65d004da72fc9fa9 | 32.324444 | 154 | 0.556015 | 5.079946 | false | false | false | false |
milseman/swift | stdlib/public/SDK/Foundation/NSString.swift | 14 | 4113 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
//===----------------------------------------------------------------------===//
// Strings
//===----------------------------------------------------------------------===//
@available(*, unavailable, message: "Please use String or NSString")
public class NSSimpleCString {}
@available(*, unavailable, message: "Please use String or NSString")
public class NSConstantString {}
@_silgen_name("swift_convertStringToNSString")
public // COMPILER_INTRINSIC
func _convertStringToNSString(_ string: String) -> NSString {
return string._bridgeToObjectiveC()
}
extension NSString : ExpressibleByStringLiteral {
/// Create an instance initialized to `value`.
public required convenience init(stringLiteral value: StaticString) {
var immutableResult: NSString
if value.hasPointerRepresentation {
immutableResult = NSString(
bytesNoCopy: UnsafeMutableRawPointer(mutating: value.utf8Start),
length: Int(value.utf8CodeUnitCount),
encoding: value.isASCII ? String.Encoding.ascii.rawValue : String.Encoding.utf8.rawValue,
freeWhenDone: false)!
} else {
var uintValue = value.unicodeScalar
immutableResult = NSString(
bytes: &uintValue,
length: 4,
encoding: String.Encoding.utf32.rawValue)!
}
self.init(string: immutableResult as String)
}
}
extension NSString : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to prevent infinite recursion trying to bridge
// AnyHashable to NSObject.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
// Consistently use Swift equality and hashing semantics for all strings.
return AnyHashable(self as String)
}
}
extension NSString {
public convenience init(format: NSString, _ args: CVarArg...) {
// We can't use withVaList because 'self' cannot be captured by a closure
// before it has been initialized.
let va_args = getVaList(args)
self.init(format: format as String, arguments: va_args)
}
public convenience init(
format: NSString, locale: Locale?, _ args: CVarArg...
) {
// We can't use withVaList because 'self' cannot be captured by a closure
// before it has been initialized.
let va_args = getVaList(args)
self.init(format: format as String, locale: locale, arguments: va_args)
}
public class func localizedStringWithFormat(
_ format: NSString, _ args: CVarArg...
) -> Self {
return withVaList(args) {
self.init(format: format as String, locale: Locale.current, arguments: $0)
}
}
public func appendingFormat(_ format: NSString, _ args: CVarArg...)
-> NSString {
return withVaList(args) {
self.appending(NSString(format: format as String, arguments: $0) as String) as NSString
}
}
}
extension NSMutableString {
public func appendFormat(_ format: NSString, _ args: CVarArg...) {
return withVaList(args) {
self.append(NSString(format: format as String, arguments: $0) as String)
}
}
}
extension NSString {
/// Returns an `NSString` object initialized by copying the characters
/// from another given string.
///
/// - Returns: An `NSString` object initialized by copying the
/// characters from `aString`. The returned object may be different
/// from the original receiver.
@nonobjc
public convenience init(string aString: NSString) {
self.init(string: aString as String)
}
}
extension NSString : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(self as String)
}
}
| apache-2.0 | 41687f19f5a3765c2b6b85eaea320836 | 33.275 | 97 | 0.653781 | 4.821805 | false | false | false | false |
johnno1962/eidolon | Kiosk/Bid Fulfillment/RegisterViewController.swift | 1 | 3327 | import UIKit
import RxSwift
protocol RegistrationSubController {
// I know, leaky abstraction, but the amount
// of useless syntax to change it isn't worth it.
var finished: PublishSubject<Void> { get }
}
class RegisterViewController: UIViewController {
@IBOutlet var flowView: RegisterFlowView!
@IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView!
@IBOutlet var confirmButton: UIButton!
var provider: Networking!
let coordinator = RegistrationCoordinator()
dynamic var placingBid = true
private let _viewWillDisappear = PublishSubject<Void>()
var viewWillDisappear: Observable<Void> {
return self._viewWillDisappear.asObserver()
}
func internalNavController() -> UINavigationController? {
return self.childViewControllers.first as? UINavigationController
}
override func viewDidLoad() {
super.viewDidLoad()
coordinator.storyboard = self.storyboard!
let registerIndex = coordinator.currentIndex.asObservable()
let indexIsConfirmed = registerIndex.map { return ($0 == RegistrationIndex.ConfirmVC.toInt()) }
indexIsConfirmed
.not()
.bindTo(confirmButton.rx_hidden)
.addDisposableTo(rx_disposeBag)
registerIndex
.bindTo(flowView.highlightedIndex)
.addDisposableTo(rx_disposeBag)
let details = self.fulfillmentNav().bidDetails
flowView.details = details
bidDetailsPreviewView.bidDetails = details
flowView
.highlightedIndex
.asObservable()
.distinctUntilChanged()
.subscribeNext { [weak self] (index) in
if let _ = self?.fulfillmentNav() {
let registrationIndex = RegistrationIndex.fromInt(index)
let nextVC = self?.coordinator.viewControllerForIndex(registrationIndex)
self?.goToViewController(nextVC!)
}
}
.addDisposableTo(rx_disposeBag)
goToNextVC()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
_viewWillDisappear.onNext()
}
func goToNextVC() {
let nextVC = coordinator.nextViewControllerForBidDetails(fulfillmentNav().bidDetails)
goToViewController(nextVC)
}
func goToViewController(controller: UIViewController) {
self.internalNavController()!.viewControllers = [controller]
if let subscribableVC = controller as? RegistrationSubController {
subscribableVC
.finished
.subscribeCompleted { [weak self] in
self?.goToNextVC()
self?.flowView.update()
}
.addDisposableTo(rx_disposeBag)
}
if let viewController = controller as? RegistrationPasswordViewController {
viewController.provider = provider
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == .ShowLoadingView {
let nextViewController = segue.destinationViewController as! LoadingViewController
nextViewController.placingBid = placingBid
nextViewController.provider = provider
}
}
}
| mit | 689e25681f0221e12884282bc36ea98b | 30.685714 | 103 | 0.644725 | 5.836842 | false | false | false | false |
darthpelo/LedsControl | RPiLedsControl/Sources/App/GPIOService.swift | 1 | 1819 | #if os(Linux)
import Glibc
#else
import Darwin.C
#endif
// MARK: - Darwin / Xcode Support
#if os(OSX)
private var O_SYNC: CInt { fatalError("Linux only") }
#endif
import SwiftyGPIO
import SwiftGPIOLibrary
enum Command {
static let Zero = 0
static let One = 1
static let Two = 2
static let Three = 3
static let Four = 4
}
enum GPIOError: Error {
case InternalError
}
final class GPIOService {
class var sharedInstance: GPIOService {
struct Singleton {
static let instance = GPIOService()
}
return Singleton.instance
}
private let gpioLib = GPIOLib.sharedInstance
private var ports: [GPIOName: GPIO] = [:]
private let list: [GPIOName] = [.P20, .P26]
func setup() {
self.ports = gpioLib.setupOUT(ports: [.P20, .P26], for: .RaspberryPi2)
}
var yellow: Int {
return gpioLib.status(ports[.P20])
}
var green: Int {
return gpioLib.status(ports[.P26])
}
func execute(command: Int) throws {
switch(command) {
case Command.Zero:
powerOff()
case Command.One:
switchYellow(Command.One)
case Command.Two:
switchYellow(Command.Two)
case Command.Three:
switchGreen(Command.Three)
case Command.Four:
switchGreen(Command.Four)
default:
throw GPIOError.InternalError
}
}
fileprivate func switchYellow(_ cmd: Int) {
switch cmd {
case Command.One:
gpioLib.switchOn(ports: [.P20])
case Command.Two:
gpioLib.switchOff(ports: [.P20])
default:()
}
}
fileprivate func switchGreen(_ cmd: Int) {
switch cmd {
case Command.Three:
gpioLib.switchOn(ports: [.P26])
case Command.Four:
gpioLib.switchOff(ports: [.P26])
default:()
}
}
fileprivate func powerOff() {
gpioLib.switchOff(ports: list)
}
}
| mit | 24a7ca8405931a661b236cae7c37837e | 18.771739 | 74 | 0.637163 | 3.638 | false | false | false | false |
SwiftyVK/SwiftyVK | Library/Sources/Networking/Attempt/Attempt.swift | 2 | 3730 | import Foundation
protocol Attempt: class, OperationConvertible {
init(
request: URLRequest,
session: VKURLSession,
callbacks: AttemptCallbacks
)
}
final class AttemptImpl: Operation, Attempt {
private let request: URLRequest
private var task: VKURLSessionTask?
private let urlSession: VKURLSession
private let callbacks: AttemptCallbacks
init(
request: URLRequest,
session: VKURLSession,
callbacks: AttemptCallbacks
) {
self.request = request
self.urlSession = session
self.callbacks = callbacks
super.init()
}
override func main() {
let semaphore = DispatchSemaphore(value: 0)
let completion: (Data?, URLResponse?, Error?) -> () = { [weak self] data, response, error in
/// Because URLSession executes completions in their own serial queue
DispatchQueue.global(qos: .utility).async {
defer {
semaphore.signal()
}
guard let strongSelf = self, !strongSelf.isCancelled else { return }
if let error = error as NSError?, error.code != NSURLErrorCancelled {
strongSelf.callbacks.onFinish(.error(.urlRequestError(error)))
}
else if let data = data {
strongSelf.callbacks.onFinish(Response(data))
}
else {
strongSelf.callbacks.onFinish(.error(.unexpectedResponse))
}
}
}
task = urlSession.dataTask(with: request, completionHandler: completion)
task?.addObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesReceived), options: .new, context: nil)
task?.addObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesSent), options: .new, context: nil)
task?.resume()
semaphore.wait()
}
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?
) {
guard let keyPath = keyPath else { return }
guard let task = task else { return }
switch keyPath {
case (#keyPath(URLSessionTask.countOfBytesSent)):
guard task.countOfBytesExpectedToSend > 0 else { return }
callbacks.onSent(task.countOfBytesSent, task.countOfBytesExpectedToSend)
case(#keyPath(URLSessionTask.countOfBytesReceived)):
guard task.countOfBytesExpectedToReceive > 0 else { return }
callbacks.onRecive(task.countOfBytesReceived, task.countOfBytesExpectedToReceive)
default:
break
}
}
override func cancel() {
super.cancel()
task?.cancel()
}
deinit {
task?.removeObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesReceived))
task?.removeObserver(self, forKeyPath: #keyPath(URLSessionTask.countOfBytesSent))
}
}
struct AttemptCallbacks {
let onFinish: (Response) -> ()
let onSent: (_ total: Int64, _ of: Int64) -> ()
let onRecive: (_ total: Int64, _ of: Int64) -> ()
init(
onFinish: @escaping ((Response) -> ()) = { _ in },
onSent: @escaping ((_ total: Int64, _ of: Int64) -> ()) = { _, _ in },
onRecive: @escaping ((_ total: Int64, _ of: Int64) -> ()) = { _, _ in }
) {
self.onFinish = onFinish
self.onSent = onSent
self.onRecive = onRecive
}
static var `default`: AttemptCallbacks {
return AttemptCallbacks()
}
}
| mit | 58b4dc1932718fa8f814a083f9404e51 | 32.603604 | 119 | 0.582842 | 5.231417 | false | false | false | false |
silt-lang/silt | Sources/Lithosphere/Utils.swift | 1 | 2454 | //===-------------------- Utils.swift - Utility Functions -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
public struct ByteSourceRange {
public let offset: Int
public let length: Int
public init(offset: Int, length: Int) {
self.offset = offset
self.length = length
}
public var endOffset: Int {
return offset+length
}
public var isEmpty: Bool {
return length == 0
}
public func intersectsOrTouches(_ other: ByteSourceRange) -> Bool {
return self.endOffset >= other.offset &&
self.offset <= other.endOffset
}
public func intersects(_ other: ByteSourceRange) -> Bool {
return self.endOffset > other.offset &&
self.offset < other.endOffset
}
/// Returns the byte range for the overlapping region between two ranges.
public func intersected(_ other: ByteSourceRange) -> ByteSourceRange {
let start = max(self.offset, other.offset)
let end = min(self.endOffset, other.endOffset)
if start > end {
return ByteSourceRange(offset: 0, length: 0)
} else {
return ByteSourceRange(offset: start, length: end-start)
}
}
}
public struct SourceEdit {
/// The byte range of the original source buffer that the edit applies to.
public let range: ByteSourceRange
/// The length of the edit replacement in UTF8 bytes.
public let replacementLength: Int
public init(range: ByteSourceRange, replacementLength: Int) {
self.range = range
self.replacementLength = replacementLength
}
public func intersectsOrTouchesRange(_ other: ByteSourceRange) -> Bool {
return self.range.intersectsOrTouches(other)
}
public func intersectsRange(_ other: ByteSourceRange) -> Bool {
return self.range.intersects(other)
}
}
extension String {
func utf8Slice(offset: Int, length: Int) -> Substring {
if length == 0 {
return Substring()
}
let utf8 = self.utf8
let begin = utf8.index(utf8.startIndex, offsetBy: offset)
let end = utf8.index(begin, offsetBy: length)
return Substring(utf8[begin..<end])
}
}
| mit | 3a5abd7cb0b7054ddb148f85dea976d9 | 28.926829 | 80 | 0.661777 | 4.397849 | false | false | false | false |
DivineDominion/mac-licensing-fastspring-cocoafob | Shared/License/License.swift | 1 | 698 | // Copyright (c) 2015-2019 Christian Tietze
//
// See the file LICENSE for copying permission.
/// Valid license information.
public struct License {
public let name: String
public let licenseCode: String
public init(name: String, licenseCode: String) {
self.name = name
self.licenseCode = licenseCode
}
}
extension License {
internal struct DefaultsKey: RawRepresentable {
let rawValue: String
init(rawValue: String) {
self.rawValue = rawValue
}
static let name = DefaultsKey(rawValue: "licensee")
static let licenseCode = DefaultsKey(rawValue: "license_code")
}
}
extension License: Equatable { }
| mit | 3f2ae68737b6f19865bc2e8e9b8a2f20 | 23.068966 | 70 | 0.657593 | 4.684564 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift | 8 | 2236 | //
// UIBarButtonItem+Rx.swift
// RxCocoa
//
// Created by Daniel Tartaglia on 5/31/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
fileprivate var rx_tap_key: UInt8 = 0
extension Reactive where Base: UIBarButtonItem {
/// Bindable sink for `enabled` property.
public var isEnabled: Binder<Bool> {
return Binder(self.base) { element, value in
element.isEnabled = value
}
}
/// Bindable sink for `title` property.
public var title: Binder<String> {
return Binder(self.base) { element, value in
element.title = value
}
}
/// Reactive wrapper for target action pattern on `self`.
public var tap: ControlEvent<()> {
let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<()> in
Observable.create { [weak control = self.base] observer in
guard let control = control else {
observer.on(.completed)
return Disposables.create()
}
let target = BarButtonItemTarget(barButtonItem: control) {
observer.on(.next(()))
}
return target
}
.takeUntil(self.deallocated)
.share()
}
return ControlEvent(events: source)
}
}
@objc
final class BarButtonItemTarget: RxTarget {
typealias Callback = () -> Void
weak var barButtonItem: UIBarButtonItem?
var callback: Callback!
init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) {
self.barButtonItem = barButtonItem
self.callback = callback
super.init()
barButtonItem.target = self
barButtonItem.action = #selector(BarButtonItemTarget.action(_:))
}
override func dispose() {
super.dispose()
#if DEBUG
MainScheduler.ensureExecutingOnScheduler()
#endif
barButtonItem?.target = nil
barButtonItem?.action = nil
callback = nil
}
@objc func action(_ sender: AnyObject) {
callback()
}
}
#endif
| mit | 43a21ed3febf5822162f37c118b42408 | 24.11236 | 82 | 0.577181 | 4.796137 | false | false | false | false |
quintonwall/SalesforceViews | Pods/SwiftlySalesforce/Pod/Classes/LoginDelegate.swift | 2 | 4080 | //
// LoginDelegate.swift
// SwiftlySalesforce
//
// For license & details see: https://www.github.com/mike4aday/SwiftlySalesforce
// Copyright (c) 2016. All rights reserved.
//
import SafariServices
import PromiseKit
import Alamofire
public typealias LoginResult = Alamofire.Result<AuthData>
public protocol LoginDelegate {
func login(url: URL) throws
}
public protocol LoginViewController: class {
var replacedRootViewController: UIViewController? {
get set
}
}
fileprivate final class SafariLoginViewController: SFSafariViewController, LoginViewController {
// Hold reference to the view controller that's temporarily replaced by the login view controller
var replacedRootViewController: UIViewController?
}
// MARK: - Extension
extension LoginDelegate {
public var loggingIn: Bool {
get {
if let _ = UIApplication.shared.keyWindow?.rootViewController as? LoginViewController {
return true
}
else {
return false
}
}
}
/// Initiates login process by replacing current root view controller with
/// Salesforce-hosted webform, per OAuth2 "user-agent" flow. This is the prescribed
/// authentication method, as the client app does not access the user credentials.
/// See https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_user_agent_oauth_flow.htm
/// - Parameter url: Salesforce authorization URL
public func login(url: URL) throws {
guard !loggingIn else {
throw SalesforceError.invalidity(message: "Already logging in!")
}
guard let window = UIApplication.shared.keyWindow else {
throw SalesforceError.invalidity(message: "No valid window!")
}
// Replace current root view controller with Safari view controller for login
let loginVC = SafariLoginViewController(url: url)
loginVC.replacedRootViewController = window.rootViewController
window.rootViewController = loginVC
}
/// Handles the redirect URL returned by Salesforce after OAuth2 authentication and authorization.
/// Restores the root view controller that was replaced by the Salesforce-hosted login web form
/// - Parameter url: URL returned by Salesforce after OAuth2 authentication & authorization
public func handleRedirectURL(url: URL) {
var result:LoginResult
// Note: docs are wrong - error information may be in URL fragment *or* in query string...
if let urlEncodedString = url.fragment ?? url.query, let authData = AuthData(urlEncodedString: urlEncodedString) {
result = .success(authData)
}
else {
// Can't make sense of the redirect URL
result = .failure(SalesforceError.unsupportedURL(url: url))
}
salesforce.authManager.loginCompleted(result: result)
// Restore the original root view controller
if let window = UIApplication.shared.keyWindow, let currentRootVC = window.rootViewController as? LoginViewController, let replacedRootVC = currentRootVC.replacedRootViewController {
window.rootViewController = replacedRootVC
}
}
@available(*, deprecated: 3.1.0, message: "Parameter 'redirectURL' renamed to 'url.' Call handleRedirectURL(url: URL) instead.")
public func handleRedirectURL(redirectURL: URL) {
return handleRedirectURL(url: redirectURL)
}
/// Call this to initiate logout process.
/// Revokes OAuth2 refresh and/or access token, then replaces
/// the current root view controller with a Safari view controller for login
/// - Returns: Promise<Void>; chain to this for custom post-logout actions
public func logout() -> Promise<Void> {
return Promise<Void> {
fulfill, reject in
firstly {
salesforce.authManager.revoke()
}.then {
() -> () in
if let loginURL = try? salesforce.authManager.loginURL(), let window = UIApplication.shared.keyWindow {
// Replace current root view controller with Safari view controller for login
let loginVC = SafariLoginViewController(url: loginURL)
loginVC.replacedRootViewController = window.rootViewController
window.rootViewController = loginVC
}
fulfill()
}.catch {
error -> () in
reject(error)
}
}
}
}
| mit | fa20867df5ead0bf9fc6ec0688939653 | 33.576271 | 184 | 0.746814 | 4.290221 | false | false | false | false |
ruddfawcett/Notepad | Example macOS/ViewController.swift | 1 | 860 | //
// ViewController.swift
// Example macOS
//
// Created by Christian Tietze on 21.07.17.
// Copyright © 2017 Rudd Fawcett. All rights reserved.
//
import Cocoa
import Notepad
class ViewController: NSViewController {
@IBOutlet var textView: NSTextView!
let storage = Storage()
override func viewDidLoad() {
super.viewDidLoad()
let theme = Theme("one-dark")
storage.theme = theme
textView.backgroundColor = theme.backgroundColor
textView.insertionPointColor = theme.tintColor
textView.layoutManager?.replaceTextStorage(storage)
if let testFile = Bundle.main.path(forResource: "tests", ofType: "md"),
let text = try? String(contentsOfFile: testFile) {
textView.string = text
} else {
print("Unable to load demo text.")
}
}
}
| mit | 936669ef8efd7a1b402677733e5f69e4 | 24.264706 | 79 | 0.641444 | 4.544974 | false | true | false | false |
practicalswift/swift | test/attr/accessibility.swift | 23 | 10283 | // RUN: %target-typecheck-verify-swift
// CHECK PARSING
private // expected-note {{modifier already specified here}}
private // expected-error {{duplicate modifier}}
func duplicateAttr() {}
private // expected-note {{modifier already specified here}}
public // expected-error {{duplicate modifier}}
func duplicateAttrChanged() {}
private // expected-note 2 {{modifier already specified here}}
public // expected-error {{duplicate modifier}}
internal // expected-error {{duplicate modifier}}
func triplicateAttrChanged() {}
private // expected-note 3 {{modifier already specified here}}
public // expected-error {{duplicate modifier}}
internal // expected-error {{duplicate modifier}}
fileprivate // expected-error {{duplicate modifier}}
func quadruplicateAttrChanged() {}
private(set)
public
var customSetter = 0
fileprivate(set)
public
var customSetter2 = 0
private(set) // expected-note {{modifier already specified here}}
public(set) // expected-error {{duplicate modifier}}
var customSetterDuplicateAttr = 0
private(set) // expected-note {{modifier already specified here}}
public // expected-note {{modifier already specified here}}
public(set) // expected-error {{duplicate modifier}}
private // expected-error {{duplicate modifier}}
var customSetterDuplicateAttrsAllAround = 0
private(get) // expected-error{{expected 'set' as subject of 'private' modifier}}
var invalidSubject = 0
private(42) // expected-error{{expected 'set' as subject of 'private' modifier}}
var invalidSubject2 = 0
private(a bunch of random tokens) // expected-error{{expected 'set' as subject of 'private' modifier}} expected-error{{expected declaration}}
var invalidSubject3 = 0
private(set // expected-error{{expected ')' in 'private' modifier}}
var unterminatedSubject = 0
private(42 // expected-error{{expected 'set' as subject of 'private' modifier}} expected-error{{expected declaration}}
var unterminatedInvalidSubject = 0
private() // expected-error{{expected 'set' as subject of 'private' modifier}}
var emptySubject = 0
private( // expected-error{{expected 'set' as subject of 'private' modifier}}
var unterminatedEmptySubject = 0
// Check that the parser made it here.
duplicateAttr(1) // expected-error{{argument passed to call that takes no arguments}}
// CHECK ALLOWED DECLS
private import Swift // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-9=}}
private(set) infix operator ~~~ // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-14=}}
private typealias MyInt = Int
private struct TestStruct {
private typealias LocalInt = MyInt
private var x = 0
private let y = 1
private func method() {}
private static func method() {}
private init() {}
private subscript(_: MyInt) -> LocalInt { return x }
}
private class TestClass {
private init() {}
internal deinit {} // expected-error {{'internal' modifier cannot be applied to this declaration}} {{3-12=}}
}
private enum TestEnum {
private case Foo, Bar // expected-error {{'private' modifier cannot be applied to this declaration}} {{3-11=}}
}
private protocol TestProtocol {
private associatedtype Foo // expected-error {{'private' modifier cannot be applied to this declaration}} {{3-11=}}
internal var Bar: Int { get } // expected-error {{'internal' modifier cannot be used in protocols}} {{3-12=}}
// expected-note@-1 {{protocol requirements implicitly have the same access as the protocol itself}}
public func baz() // expected-error {{'public' modifier cannot be used in protocols}} {{3-10=}}
// expected-note@-1 {{protocol requirements implicitly have the same access as the protocol itself}}
}
public(set) func publicSetFunc() {} // expected-error {{'public' modifier cannot be applied to this declaration}} {{1-13=}}
public(set) var defaultVis = 0 // expected-error {{internal variable cannot have a public setter}}
internal(set) private var privateVis = 0 // expected-error {{private variable cannot have an internal setter}}
private(set) var defaultVisOK = 0
private(set) public var publicVis = 0
private(set) var computed: Int { // expected-error {{'private(set)' modifier cannot be applied to read-only variables}} {{1-14=}}
return 42
}
private(set) var computedRW: Int {
get { return 42 }
set { }
}
private(set) let constant = 42 // expected-error {{'private(set)' modifier cannot be applied to constants}} {{1-14=}}
public struct Properties {
private(set) var stored = 42
private(set) var computed: Int { // expected-error {{'private(set)' modifier cannot be applied to read-only properties}} {{3-16=}}
return 42
}
private(set) var computedRW: Int {
get { return 42 }
set { }
}
private(set) let constant = 42 // expected-error {{'private(set)' modifier cannot be applied to read-only properties}} {{3-16=}}
public(set) var defaultVis = 0 // expected-error {{internal property cannot have a public setter}}
open(set) var defaultVis2 = 0 // expected-error {{internal property cannot have an open setter}}
public(set) subscript(a a: Int) -> Int { // expected-error {{internal subscript cannot have a public setter}}
get { return 0 }
set {}
}
internal(set) private subscript(b b: Int) -> Int { // expected-error {{private subscript cannot have an internal setter}}
get { return 0 }
set {}
}
private(set) subscript(c c: Int) -> Int {
get { return 0 }
set {}
}
private(set) public subscript(d d: Int) -> Int {
get { return 0 }
set {}
}
private(set) subscript(e e: Int) -> Int { return 0 } // expected-error {{'private(set)' modifier cannot be applied to read-only subscripts}} {{3-16=}}
}
private extension Properties {
public(set) var extProp: Int { // expected-error {{private property cannot have a public setter}}
get { return 42 }
set { }
}
open(set) var extProp2: Int { // expected-error {{private property cannot have an open setter}}
get { return 42 }
set { }
}
}
internal protocol EmptyProto {}
internal protocol EmptyProto2 {}
private extension Properties : EmptyProto {} // expected-error {{'private' modifier cannot be used with extensions that declare protocol conformances}} {{1-9=}}
private(set) extension Properties : EmptyProto2 {} // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-14=}}
public struct PublicStruct {}
internal struct InternalStruct {} // expected-note * {{declared here}}
private struct PrivateStruct {} // expected-note * {{declared here}}
protocol InternalProto { // expected-note * {{declared here}}
associatedtype Assoc
}
public extension InternalProto {} // expected-error {{extension of internal protocol cannot be declared public}} {{1-8=}}
internal extension InternalProto where Assoc == PublicStruct {}
internal extension InternalProto where Assoc == InternalStruct {}
internal extension InternalProto where Assoc == PrivateStruct {} // expected-error {{extension cannot be declared internal because its generic requirement uses a private type}}
private extension InternalProto where Assoc == PublicStruct {}
private extension InternalProto where Assoc == InternalStruct {}
private extension InternalProto where Assoc == PrivateStruct {}
public protocol PublicProto {
associatedtype Assoc
}
public extension PublicProto {}
public extension PublicProto where Assoc == PublicStruct {}
public extension PublicProto where Assoc == InternalStruct {} // expected-error {{extension cannot be declared public because its generic requirement uses an internal type}}
public extension PublicProto where Assoc == PrivateStruct {} // expected-error {{extension cannot be declared public because its generic requirement uses a private type}}
internal extension PublicProto where Assoc == PublicStruct {}
internal extension PublicProto where Assoc == InternalStruct {}
internal extension PublicProto where Assoc == PrivateStruct {} // expected-error {{extension cannot be declared internal because its generic requirement uses a private type}}
private extension PublicProto where Assoc == PublicStruct {}
private extension PublicProto where Assoc == InternalStruct {}
private extension PublicProto where Assoc == PrivateStruct {}
extension PublicProto where Assoc == InternalStruct {
public func foo() {} // expected-error {{cannot declare a public instance method in an extension with internal requirements}} {{3-9=internal}}
open func bar() {} // expected-error {{cannot declare an open instance method in an extension with internal requirements}} {{3-7=internal}}
}
extension InternalProto {
public func foo() {} // no effect, but no warning
}
extension InternalProto where Assoc == PublicStruct {
public func foo() {} // expected-error {{cannot declare a public instance method in an extension with internal requirements}} {{3-9=internal}}
open func bar() {} // expected-error {{cannot declare an open instance method in an extension with internal requirements}} {{3-7=internal}}
}
public struct GenericStruct<Param> {}
public extension GenericStruct where Param: InternalProto {} // expected-error {{extension cannot be declared public because its generic requirement uses an internal type}}
extension GenericStruct where Param: InternalProto {
public func foo() {} // expected-error {{cannot declare a public instance method in an extension with internal requirements}} {{3-9=internal}}
}
public class OuterClass {
class InnerClass {}
}
public protocol PublicProto2 {
associatedtype T
associatedtype U
}
// FIXME: With the current design, the below should not diagnose.
//
// However, it does, because we look at the bound decl in the
// TypeRepr first, and it happens to already be set.
//
// FIXME: Once we no longer do that, come up with another strategy
// to make the above diagnose.
extension PublicProto2 where Self.T : OuterClass, Self.U == Self.T.InnerClass {
public func cannotBePublic() {}
// expected-error@-1 {{cannot declare a public instance method in an extension with internal requirements}}
}
public extension OuterClass {
open convenience init(x: ()) { self.init() }
// expected-warning@-1 {{'open' modifier conflicts with extension's default access of 'public'}}
// expected-error@-2 {{only classes and overridable class members can be declared 'open'; use 'public'}}
}
| apache-2.0 | a1fe59f0bf4a77c8b490f0d6192f10da | 42.388186 | 176 | 0.734319 | 4.432328 | false | false | false | false |
bzatrok/iOSAssessment | BestBuy/Classes/Controllers/BBGridSelectorViewController.swift | 1 | 4527 | //
// BBGridSelectorViewController.swift
// BestBuy
//
// Created by Ben Zatrok on 28/02/17.
// Copyright © 2017 AmberGlass. All rights reserved.
//
import UIKit
class BBGridSelectorViewController: UIViewController
{
//MARK: Variables
var itemsList : [BBObject] = []
var SKUList : [Int]?
var selectedItem : BBObject?
let gridCellID = "gridCellID"
let emptyCellID = "emptyCellID"
let accessoryProductDetailSegue = "accessoryProductDetailSegue"
//MARK: IBOutlets
@IBOutlet weak var collectionView : UICollectionView!
//MARK: IBActions
//MARK: Life-Cycle
override func viewDidLoad()
{
super.viewDidLoad()
setupDelegation()
setupView()
}
//MARK: Functions
/**
Sets up required delegates
*/
func setupDelegation()
{
collectionView.delegate = self
collectionView.dataSource = self
}
/**
Sets up the view and fetches required data
*/
func setupView()
{
guard let SKUList = SKUList, SKUList.count > 0 else
{
return
}
BBRequestManager.shared.queryProducts(withSKUs: SKUList) { [weak self] success, responseProductsList in
guard let strongSelf = self, let responseProductsList = responseProductsList, success else
{
return
}
strongSelf.itemsList = responseProductsList
DispatchQueue.main.async {
strongSelf.collectionView.reloadData()
}
}
}
//MARK: Segue handling
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
guard let selectedProduct = selectedItem as? BBProduct,
let destination = segue.destination as? BBProductDetailViewController,
segue.identifier == accessoryProductDetailSegue else
{
return
}
destination.selectedProduct = selectedProduct
}
}
extension BBGridSelectorViewController: UICollectionViewDelegate
{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
selectedItem = itemsList[indexPath.row]
performSegue(withIdentifier: accessoryProductDetailSegue, sender: self)
}
}
extension BBGridSelectorViewController: UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return itemsList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: gridCellID, for: indexPath) as? BBGridCollectionViewCell,
let product = itemsList[indexPath.row] as? BBProduct else
{
return collectionView.dequeueReusableCell(withReuseIdentifier: emptyCellID, for: indexPath)
}
cell.backgroundImageView.contentMode = .scaleAspectFit
if let image_URL = product.image_URL
{
cell.backgroundImageView.kf.setImage(with: URL(string: image_URL), placeholder: nil, options: nil, progressBlock: nil) { Image, error, cacheType, url in
DispatchQueue.main.async {
cell.setNeedsLayout()
}
}
}
if let sale_price = product.sale_price,
let regular_price = product.regular_price
{
let salePriceString = NSMutableAttributedString(string: "$\(sale_price) ")
if sale_price != regular_price
{
let strikeThroughPriceString: NSMutableAttributedString = NSMutableAttributedString(string: "$\(regular_price)")
strikeThroughPriceString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, strikeThroughPriceString.length))
salePriceString.append(strikeThroughPriceString)
}
cell.priceLabel.attributedText = salePriceString
}
return cell
}
}
| mit | a431aaa2d823762dcf82bba43f980ae2 | 28.581699 | 164 | 0.601193 | 5.75827 | false | false | false | false |
dereknex/ios-charts | Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift | 42 | 11477 | //
// ChartXAxisRendererHorizontalBarChart.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/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 ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart
{
public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart)
}
public override func computeAxis(#xValAverageLength: Double, xValues: [String?])
{
_xAxis.values = xValues
var longest = _xAxis.getLongestLabel() as NSString
var longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont])
_xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5)
_xAxis.labelHeight = longestSize.height
}
public override func renderAxisLabels(#context: CGContext)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil)
{
return
}
var xoffset = _xAxis.xOffset
if (_xAxis.labelPosition == .Top)
{
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left)
}
else if (_xAxis.labelPosition == .Bottom)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right)
}
else if (_xAxis.labelPosition == .BottomInside)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left)
}
else if (_xAxis.labelPosition == .TopInside)
{
drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right)
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right)
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left)
}
}
/// draws the x-labels on the specified y-position
internal func drawLabels(#context: CGContext, pos: CGFloat, align: NSTextAlignment)
{
var labelFont = _xAxis.labelFont
var labelTextColor = _xAxis.labelTextColor
// pre allocate to save performance (dont allocate in loop)
var position = CGPoint(x: 0.0, y: 0.0)
var bd = _chart.data as! BarChartData
var step = bd.dataSetCount
for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus)
{
var label = _xAxis.values[i]
if (label == nil)
{
continue
}
position.x = 0.0
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0
// consider groups (center label for each group)
if (step > 1)
{
position.y += (CGFloat(step) - 1.0) / 2.0
}
transformer.pointValueToPixel(&position)
if (viewPortHandler.isInBoundsY(position.y))
{
ChartUtils.drawText(context: context, text: label!, point: CGPoint(x: pos, y: position.y - _xAxis.labelHeight / 2.0), align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
}
}
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderGridLines(#context: CGContext)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor)
CGContextSetLineWidth(context, _xAxis.gridLineWidth)
if (_xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
var position = CGPoint(x: 0.0, y: 0.0)
var bd = _chart.data as! BarChartData
// take into consideration that multiple DataSets increase _deltaX
var step = bd.dataSetCount
for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus)
{
position.x = 0.0
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5
transformer.pointValueToPixel(&position)
if (viewPortHandler.isInBoundsY(position.y))
{
_gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_gridLineSegmentsBuffer[0].y = position.y
_gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_gridLineSegmentsBuffer[1].y = position.y
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderAxisLine(#context: CGContext)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor)
CGContextSetLineWidth(context, _xAxis.axisLineWidth)
if (_xAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
if (_xAxis.labelPosition == .Top
|| _xAxis.labelPosition == .TopInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
if (_xAxis.labelPosition == .Bottom
|| _xAxis.labelPosition == .BottomInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
CGContextRestoreGState(context)
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderLimitLines(#context: CGContext)
{
var limitLines = _xAxis.limitLines
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
var trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for (var i = 0; i < limitLines.count; i++)
{
var l = limitLines[i]
position.x = 0.0
position.y = CGFloat(l.limit)
position = CGPointApplyAffineTransform(position, trans)
_limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_limitLineSegmentsBuffer[0].y = position.y
_limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_limitLineSegmentsBuffer[1].y = position.y
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor)
CGContextSetLineWidth(context, l.lineWidth)
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2)
var label = l.label
// if drawing the limit-value label is enabled
if (count(label) > 0)
{
var labelLineHeight = l.valueFont.lineHeight
let add = CGFloat(4.0)
var xOffset: CGFloat = add
var yOffset: CGFloat = l.lineWidth + labelLineHeight
if (l.labelPosition == .RightTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .RightBottom)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .LeftTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
}
}
CGContextRestoreGState(context)
}
} | apache-2.0 | df70d6f43db7ebc1e58f72d8ea6a821c | 37.13289 | 241 | 0.560164 | 5.606742 | false | false | false | false |
randallli/material-components-ios | components/TextFields/examples/TextFieldLegacyExample.swift | 1 | 16090 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// swiftlint:disable function_body_length
import MaterialComponents.MaterialTextFields
final class TextFieldLegacySwiftExample: UIViewController {
let scrollView = UIScrollView()
let name: MDCTextField = {
let name = MDCTextField()
name.translatesAutoresizingMaskIntoConstraints = false
name.autocapitalizationType = .words
return name
}()
let address: MDCTextField = {
let address = MDCTextField()
address.translatesAutoresizingMaskIntoConstraints = false
address.autocapitalizationType = .words
return address
}()
let city: MDCTextField = {
let city = MDCTextField()
city.translatesAutoresizingMaskIntoConstraints = false
city.autocapitalizationType = .words
return city
}()
let cityController: MDCTextInputControllerLegacyDefault
let state: MDCTextField = {
let state = MDCTextField()
state.translatesAutoresizingMaskIntoConstraints = false
state.autocapitalizationType = .allCharacters
return state
}()
let zip: MDCTextField = {
let zip = MDCTextField()
zip.translatesAutoresizingMaskIntoConstraints = false
return zip
}()
let zipController: MDCTextInputControllerLegacyDefault
let phone: MDCTextField = {
let phone = MDCTextField()
phone.translatesAutoresizingMaskIntoConstraints = false
return phone
}()
let message: MDCMultilineTextField = {
let message = MDCMultilineTextField()
message.translatesAutoresizingMaskIntoConstraints = false
return message
}()
var allTextFieldControllers = [MDCTextInputControllerLegacyDefault]()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
cityController = MDCTextInputControllerLegacyDefault(textInput: city)
zipController = MDCTextInputControllerLegacyDefault(textInput: zip)
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white:0.97, alpha: 1.0)
title = "Material Text Fields"
setupScrollView()
setupTextFields()
registerKeyboardNotifications()
addGestureRecognizer()
let styleButton = UIBarButtonItem(title: "Style",
style: .plain,
target: self,
action: #selector(buttonDidTouch(sender: )))
self.navigationItem.rightBarButtonItem = styleButton
}
func setupTextFields() {
scrollView.addSubview(name)
let nameController = MDCTextInputControllerLegacyDefault(textInput: name)
name.delegate = self
name.text = "Grace Hopper"
nameController.placeholderText = "Name"
nameController.helperText = "First and Last"
allTextFieldControllers.append(nameController)
scrollView.addSubview(address)
let addressController = MDCTextInputControllerLegacyDefault(textInput: address)
address.delegate = self
addressController.placeholderText = "Address"
allTextFieldControllers.append(addressController)
scrollView.addSubview(city)
city.delegate = self
cityController.placeholderText = "City"
allTextFieldControllers.append(cityController)
// In iOS 9+, you could accomplish this with a UILayoutGuide.
// TODO: (larche) add iOS version specific implementations
let stateZip = UIView()
stateZip.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stateZip)
stateZip.addSubview(state)
let stateController = MDCTextInputControllerLegacyDefault(textInput: state)
state.delegate = self
stateController.placeholderText = "State"
allTextFieldControllers.append(stateController)
stateZip.addSubview(zip)
zip.delegate = self
zipController.placeholderText = "Zip Code"
zipController.helperText = "XXXXX"
allTextFieldControllers.append(zipController)
scrollView.addSubview(phone)
let phoneController = MDCTextInputControllerLegacyDefault(textInput: phone)
phone.delegate = self
phoneController.placeholderText = "Phone Number"
allTextFieldControllers.append(phoneController)
scrollView.addSubview(message)
let messageController = MDCTextInputControllerLegacyDefault(textInput: message)
#if swift(>=3.2)
message.text = """
This is where you could put a multi-line message like an email.
It can even handle new lines.
"""
#else
message.text = "This is where you could put a multi-line message like an email. It can even handle new lines./n"
#endif
message.textView?.delegate = self
messageController.placeholderText = "Message"
allTextFieldControllers.append(messageController)
var tag = 0
for controller in allTextFieldControllers {
guard let textField = controller.textInput as? MDCTextField else { continue }
textField.tag = tag
tag += 1
}
let views = [ "name": name,
"address": address,
"city": city,
"stateZip": stateZip,
"phone": phone,
"message": message ]
var constraints = NSLayoutConstraint.constraints(withVisualFormat:
"V:[name]-[address]-[city]-[stateZip]-[phone]-[message]",
options: [.alignAllLeading, .alignAllTrailing],
metrics: nil,
views: views)
constraints += [NSLayoutConstraint(item: name,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leadingMargin,
multiplier: 1,
constant: 0)]
constraints += [NSLayoutConstraint(item: name,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailingMargin,
multiplier: 1,
constant: 0)]
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[name]|",
options: [],
metrics: nil,
views: views)
#if swift(>=3.2)
if #available(iOS 11.0, *) {
constraints += [NSLayoutConstraint(item: name,
attribute: .top,
relatedBy: .equal,
toItem: scrollView.contentLayoutGuide,
attribute: .top,
multiplier: 1,
constant: 20),
NSLayoutConstraint(item: message,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView.contentLayoutGuide,
attribute: .bottomMargin,
multiplier: 1,
constant: -20)]
} else {
constraints += [NSLayoutConstraint(item: name,
attribute: .top,
relatedBy: .equal,
toItem: scrollView,
attribute: .top,
multiplier: 1,
constant: 20),
NSLayoutConstraint(item: message,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView,
attribute: .bottomMargin,
multiplier: 1,
constant: -20)]
}
#else
constraints += [NSLayoutConstraint(item: name,
attribute: .top,
relatedBy: .equal,
toItem: scrollView,
attribute: .top,
multiplier: 1,
constant: 20),
NSLayoutConstraint(item: message,
attribute: .bottom,
relatedBy: .equal,
toItem: scrollView,
attribute: .bottomMargin,
multiplier: 1,
constant: -20)]
#endif
let stateZipViews = [ "state": state, "zip": zip ]
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[state(80)]-[zip]|",
options: [.alignAllTop],
metrics: nil,
views: stateZipViews)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[state]|",
options: [],
metrics: nil,
views: stateZipViews)
NSLayoutConstraint.activate(constraints)
}
func setupScrollView() {
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(
withVisualFormat: "V:|[scrollView]|",
options: [],
metrics: nil,
views: ["scrollView": scrollView]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|",
options: [],
metrics: nil,
views: ["scrollView": scrollView]))
let marginOffset: CGFloat = 16
let margins = UIEdgeInsets(top: 0, left: marginOffset, bottom: 0, right: marginOffset)
scrollView.layoutMargins = margins
}
func addGestureRecognizer() {
let tapRecognizer = UITapGestureRecognizer(target: self,
action: #selector(tapDidTouch(sender: )))
self.scrollView.addGestureRecognizer(tapRecognizer)
}
// MARK: - Actions
@objc func tapDidTouch(sender: Any) {
self.view.endEditing(true)
}
@objc func buttonDidTouch(sender: Any) {
let isFloatingEnabled = allTextFieldControllers.first?.isFloatingEnabled ?? false
let alert = UIAlertController(title: "Floating Labels",
message: nil,
preferredStyle: .actionSheet)
let defaultAction = UIAlertAction(title: "Default (Yes)" + (isFloatingEnabled ? " ✓" : ""),
style: .default) { _ in
self.allTextFieldControllers.forEach({ (controller) in
controller.isFloatingEnabled = true
})
}
alert.addAction(defaultAction)
let floatingAction = UIAlertAction(title: "No" + (isFloatingEnabled ? "" : " ✓"),
style: .default) { _ in
self.allTextFieldControllers.forEach({ (controller) in
controller.isFloatingEnabled = false
})
}
alert.addAction(floatingAction)
present(alert, animated: true, completion: nil)
}
}
extension TextFieldLegacySwiftExample: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
guard let rawText = textField.text else {
return true
}
let fullString = NSString(string: rawText).replacingCharacters(in: range, with: string)
if textField == zip {
if let range = fullString.rangeOfCharacter(from: CharacterSet.letters),
fullString[range].characterCount > 0 {
zipController.setErrorText("Error: Zip can only contain numbers",
errorAccessibilityValue: nil)
} else if fullString.characterCount > 5 {
zipController.setErrorText("Error: Zip can only contain five digits",
errorAccessibilityValue: nil)
} else {
zipController.setErrorText(nil, errorAccessibilityValue: nil)
}
} else if textField == city {
if let range = fullString.rangeOfCharacter(from: CharacterSet.decimalDigits),
fullString[range].characterCount > 0 {
cityController.setErrorText("Error: City can only contain letters",
errorAccessibilityValue: nil)
} else {
cityController.setErrorText(nil, errorAccessibilityValue: nil)
}
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let index = textField.tag
if index + 1 < allTextFieldControllers.count,
let nextField = allTextFieldControllers[index + 1].textInput {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
}
extension TextFieldLegacySwiftExample: UITextViewDelegate {
func textViewDidEndEditing(_ textView: UITextView) {
print(textView.text)
}
}
// MARK: - Keyboard Handling
extension TextFieldLegacySwiftExample {
func registerKeyboardNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillShow(notif:)),
name: .UIKeyboardWillShow,
object: nil)
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillShow(notif:)),
name: .UIKeyboardWillChangeFrame,
object: nil)
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillHide(notif:)),
name: .UIKeyboardWillHide,
object: nil)
}
@objc func keyboardWillShow(notif: Notification) {
guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
return
}
scrollView.contentInset = UIEdgeInsets(top: 0.0,
left: 0.0,
bottom: frame.height,
right: 0.0)
}
@objc func keyboardWillHide(notif: Notification) {
scrollView.contentInset = UIEdgeInsets()
}
}
// MARK: - Status Bar Style
extension TextFieldLegacySwiftExample {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension TextFieldLegacySwiftExample {
@objc class func catalogBreadcrumbs() -> [String] {
return ["Text Field", "[Legacy] Typical Use"]
}
}
| apache-2.0 | fd96794823360fe574078bb52d6fcea3 | 37.118483 | 118 | 0.569564 | 6.215611 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionUI/TransactionsRouter/TransactionsRouter.swift | 1 | 28055 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import BlockchainComponentLibrary
import BlockchainNamespace
import Combine
import DIKit
import ErrorsUI
import FeatureFormDomain
import FeatureKYCUI
import FeatureProductsDomain
import FeatureTransactionDomain
import Localization
import MoneyKit
import PlatformKit
import PlatformUIKit
import RIBs
import SwiftUI
import ToolKit
import UIComponentsKit
/// A protocol defining the API for the app's entry point to any `Transaction Flow`.
/// NOTE: Presenting a Transaction Flow can never fail because it's expected for any error to be handled within the flow.
/// Non-recoverable errors should force the user to abandon the flow.
public protocol TransactionsRouterAPI {
/// Some APIs may not have UIKit available. In this instance we use
/// `TopMostViewControllerProviding`.
func presentTransactionFlow(
to action: TransactionFlowAction
) -> AnyPublisher<TransactionFlowResult, Never>
func presentTransactionFlow(
to action: TransactionFlowAction,
from presenter: UIViewController
) -> AnyPublisher<TransactionFlowResult, Never>
}
public enum UserActionServiceResult: Equatable {
case canPerform
case cannotPerform(upgradeTier: KYC.Tier?)
case questions
}
public protocol UserActionServiceAPI {
func canPresentTransactionFlow(
toPerform action: TransactionFlowAction
) -> AnyPublisher<UserActionServiceResult, Never>
}
final class TransactionsRouter: TransactionsRouterAPI {
private let app: AppProtocol
private let analyticsRecorder: AnalyticsEventRecorderAPI
private let featureFlagsService: FeatureFlagsServiceAPI
private let pendingOrdersService: PendingOrderDetailsServiceAPI
private let eligibilityService: EligibilityServiceAPI
private let userActionService: UserActionServiceAPI
private let coincore: CoincoreAPI
private let kycRouter: PlatformUIKit.KYCRouting
private let kyc: FeatureKYCUI.Routing
private let alertViewPresenter: AlertViewPresenterAPI
private let topMostViewControllerProvider: TopMostViewControllerProviding
private let loadingViewPresenter: LoadingViewPresenting
private var transactionFlowBuilder: TransactionFlowBuildable
private let buyFlowBuilder: BuyFlowBuildable
private let sellFlowBuilder: SellFlowBuildable
private let signFlowBuilder: SignFlowBuildable
private let sendFlowBuilder: SendRootBuildable
private let interestFlowBuilder: InterestTransactionBuilder
private let withdrawFlowBuilder: WithdrawRootBuildable
private let depositFlowBuilder: DepositRootBuildable
private let receiveCoordinator: ReceiveCoordinator
private let fiatCurrencyService: FiatCurrencySettingsServiceAPI
private let productsService: FeatureProductsDomain.ProductsServiceAPI
@LazyInject var tabSwapping: TabSwapping
/// Currently retained RIBs router in use.
private var currentRIBRouter: RIBs.Routing?
private var cancellables: Set<AnyCancellable> = []
init(
app: AppProtocol = resolve(),
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
featureFlagsService: FeatureFlagsServiceAPI = resolve(),
pendingOrdersService: PendingOrderDetailsServiceAPI = resolve(),
eligibilityService: EligibilityServiceAPI = resolve(),
userActionService: UserActionServiceAPI = resolve(),
kycRouter: PlatformUIKit.KYCRouting = resolve(),
alertViewPresenter: AlertViewPresenterAPI = resolve(),
coincore: CoincoreAPI = resolve(),
topMostViewControllerProvider: TopMostViewControllerProviding = resolve(),
loadingViewPresenter: LoadingViewPresenting = LoadingViewPresenter(),
transactionFlowBuilder: TransactionFlowBuildable = TransactionFlowBuilder(),
buyFlowBuilder: BuyFlowBuildable = BuyFlowBuilder(analyticsRecorder: resolve()),
sellFlowBuilder: SellFlowBuildable = SellFlowBuilder(),
signFlowBuilder: SignFlowBuildable = SignFlowBuilder(),
sendFlowBuilder: SendRootBuildable = SendRootBuilder(),
interestFlowBuilder: InterestTransactionBuilder = InterestTransactionBuilder(),
withdrawFlowBuilder: WithdrawRootBuildable = WithdrawRootBuilder(),
depositFlowBuilder: DepositRootBuildable = DepositRootBuilder(),
receiveCoordinator: ReceiveCoordinator = ReceiveCoordinator(),
fiatCurrencyService: FiatCurrencySettingsServiceAPI = resolve(),
kyc: FeatureKYCUI.Routing = resolve(),
productsService: FeatureProductsDomain.ProductsServiceAPI = resolve()
) {
self.app = app
self.analyticsRecorder = analyticsRecorder
self.featureFlagsService = featureFlagsService
self.eligibilityService = eligibilityService
self.userActionService = userActionService
self.kycRouter = kycRouter
self.topMostViewControllerProvider = topMostViewControllerProvider
self.alertViewPresenter = alertViewPresenter
self.coincore = coincore
self.loadingViewPresenter = loadingViewPresenter
self.pendingOrdersService = pendingOrdersService
self.transactionFlowBuilder = transactionFlowBuilder
self.buyFlowBuilder = buyFlowBuilder
self.sellFlowBuilder = sellFlowBuilder
self.signFlowBuilder = signFlowBuilder
self.sendFlowBuilder = sendFlowBuilder
self.interestFlowBuilder = interestFlowBuilder
self.withdrawFlowBuilder = withdrawFlowBuilder
self.depositFlowBuilder = depositFlowBuilder
self.receiveCoordinator = receiveCoordinator
self.fiatCurrencyService = fiatCurrencyService
self.kyc = kyc
self.productsService = productsService
}
func presentTransactionFlow(
to action: TransactionFlowAction
) -> AnyPublisher<TransactionFlowResult, Never> {
guard let viewController = topMostViewControllerProvider.topMostViewController else {
fatalError("Expected a UIViewController")
}
return presentTransactionFlow(to: action, from: viewController)
}
func presentTransactionFlow(
to action: TransactionFlowAction,
from presenter: UIViewController
) -> AnyPublisher<TransactionFlowResult, Never> {
isUserEligible(for: action)
.handleEvents(
receiveSubscription: { [app] _ in
app.state.transaction { state in
state.set(blockchain.ux.transaction.id, to: action.asset.rawValue)
}
app.post(event: blockchain.ux.transaction.event.will.start)
}
)
.receive(on: DispatchQueue.main)
.flatMap { [weak self] ineligibility -> AnyPublisher<TransactionFlowResult, Never> in
guard let self = self else {
return .empty()
}
guard let ineligibility = ineligibility else {
// There is no 'ineligibility' reason, continue.
return self.continuePresentingTransactionFlow(
to: action,
from: presenter,
showKycQuestions: action.isCustodial
)
}
// There is a 'ineligibility' reason.
// Show KYC flow or 'blocked' flow.
switch ineligibility.type {
case .insufficientTier:
let tier: KYC.Tier = ineligibility.reason == .tier2Required ? .tier2 : .tier1
return self.presentKYCUpgradeFlow(from: presenter, requiredTier: tier)
default:
guard let presenter = self.topMostViewControllerProvider.topMostViewController else {
return .just(.abandoned)
}
let viewController = self.buildIneligibilityErrorView(ineligibility, from: presenter)
presenter.present(viewController, animated: true, completion: nil)
return .just(.abandoned)
}
}
.eraseToAnyPublisher()
}
private func isUserEligible(
for action: TransactionFlowAction
) -> AnyPublisher<ProductIneligibility?, Never> {
guard action.isCustodial, let productId = action.toProductIdentifier else {
return .just(nil)
}
return productsService
.fetchProducts()
.replaceError(with: [])
.flatMap { products -> AnyPublisher<ProductIneligibility?, Never> in
let product: ProductValue? = products.first { $0.id == productId }
return .just(product?.reasonNotEligible)
}
.eraseToAnyPublisher()
}
private func presentKYCUpgradeFlow(
from presenter: UIViewController,
requiredTier: KYC.Tier?
) -> AnyPublisher<TransactionFlowResult, Never> {
kycRouter.presentKYCUpgradeFlow(from: presenter)
.map { result in
switch result {
case .abandoned:
return .abandoned
case .completed, .skipped:
return .completed
}
}
.eraseToAnyPublisher()
}
/// Call this only after having checked that users can perform the requested action
private func continuePresentingTransactionFlow(
to action: TransactionFlowAction,
from presenter: UIViewController,
showKycQuestions: Bool
) -> AnyPublisher<TransactionFlowResult, Never> {
do {
let isKycQuestionsEmpty: Bool = try app.state.get(blockchain.ux.kyc.extra.questions.form.is.empty)
if showKycQuestions, !isKycQuestionsEmpty {
return presentKycQuestionsIfNeeded(
to: action,
from: presenter
)
}
} catch { /* ignore */ }
switch action {
case .buy:
return presentTradingCurrencySelectorIfNeeded(from: presenter)
.flatMap { result -> AnyPublisher<TransactionFlowResult, Never> in
guard result == .completed else {
return .just(result)
}
return self.presentBuyTransactionFlow(to: action, from: presenter)
}
.eraseToAnyPublisher()
case .sell,
.order,
.swap,
.interestTransfer,
.interestWithdraw,
.sign,
.send,
.receive,
.withdraw,
.deposit:
return presentNewTransactionFlow(action, from: presenter)
}
}
private func presentKycQuestionsIfNeeded(
to action: TransactionFlowAction,
from presenter: UIViewController
) -> AnyPublisher<TransactionFlowResult, Never> {
let subject = PassthroughSubject<TransactionFlowResult, Never>()
kyc.routeToKYC(
from: presenter,
requiredTier: .tier1,
flowCompletion: { [weak self] result in
guard let self = self else { return }
switch result {
case .abandoned:
subject.send(.abandoned)
case .completed, .skipped:
self.continuePresentingTransactionFlow(
to: action,
from: presenter,
showKycQuestions: false // if questions were skipped
)
.sink(receiveValue: subject.send)
.store(in: &self.cancellables)
}
}
)
return subject.eraseToAnyPublisher()
}
private func presentBuyTransactionFlow(
to action: TransactionFlowAction,
from presenter: UIViewController
) -> AnyPublisher<TransactionFlowResult, Never> {
eligibilityService.eligibility()
.receive(on: DispatchQueue.main)
.handleLoaderForLifecycle(loader: loadingViewPresenter)
.flatMap { [weak self] eligibility -> AnyPublisher<TransactionFlowResult, Error> in
guard let self = self else { return .empty() }
if eligibility.simpleBuyPendingTradesEligible {
return self.pendingOrdersService.pendingOrderDetails
.receive(on: DispatchQueue.main)
.flatMap { [weak self] orders -> AnyPublisher<TransactionFlowResult, Never> in
guard let self = self else { return .empty() }
let isAwaitingAction = orders.filter(\.isAwaitingAction)
if let order = isAwaitingAction.first {
return self.presentNewTransactionFlow(action, from: presenter)
.zip(
self.pendingOrdersService.cancel(order)
.receive(on: DispatchQueue.main)
.ignoreFailure()
)
.map(\.0)
.eraseToAnyPublisher()
} else {
return self.presentNewTransactionFlow(action, from: presenter)
}
}
.eraseError()
.eraseToAnyPublisher()
} else {
return self.presentTooManyPendingOrders(
count: eligibility.maxPendingDepositSimpleBuyTrades,
from: presenter
)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
}
.catch { [weak self] error -> AnyPublisher<TransactionFlowResult, Never> in
guard let self = self else { return .empty() }
return self.presentError(error: error, action: action, from: presenter)
}
.eraseToAnyPublisher()
}
}
extension TransactionsRouter {
// since we're not attaching a RIB to a RootRouter we have to retain the router and manually activate it
private func mimicRIBAttachment(router: RIBs.Routing) {
currentRIBRouter?.interactable.deactivate()
currentRIBRouter = router
router.load()
router.interactable.activate()
}
}
extension TransactionsRouter {
// swiftlint:disable:next cyclomatic_complexity
private func presentNewTransactionFlow(
_ action: TransactionFlowAction,
from presenter: UIViewController
) -> AnyPublisher<TransactionFlowResult, Never> {
switch action {
case .interestWithdraw(let cryptoAccount):
let listener = InterestTransactionInteractor(transactionType: .withdraw(cryptoAccount))
let router = interestFlowBuilder.buildWithInteractor(listener)
router.start()
mimicRIBAttachment(router: router)
return listener.publisher
case .interestTransfer(let cryptoAccount):
let listener = InterestTransactionInteractor(transactionType: .transfer(cryptoAccount))
let router = interestFlowBuilder.buildWithInteractor(listener)
router.start()
mimicRIBAttachment(router: router)
return listener.publisher
case .buy(let cryptoAccount):
let listener = BuyFlowListener(
kycRouter: kycRouter,
alertViewPresenter: alertViewPresenter
)
let interactor = BuyFlowInteractor()
let router = buyFlowBuilder.build(with: listener, interactor: interactor)
router.start(with: cryptoAccount, order: nil, from: presenter)
mimicRIBAttachment(router: router)
return listener.publisher
case .order(let order):
let listener = BuyFlowListener(
kycRouter: kycRouter,
alertViewPresenter: alertViewPresenter
)
let interactor = BuyFlowInteractor()
let router = buyFlowBuilder.build(with: listener, interactor: interactor)
router.start(with: nil, order: order, from: presenter)
mimicRIBAttachment(router: router)
return listener.publisher
case .sell(let cryptoAccount):
let listener = SellFlowListener()
let interactor = SellFlowInteractor()
let router = SellFlowBuilder().build(with: listener, interactor: interactor)
startSellRouter(router, cryptoAccount: cryptoAccount, from: presenter)
mimicRIBAttachment(router: router)
return listener.publisher
case .swap(let cryptoAccount):
let listener = SwapRootInteractor()
let router = transactionFlowBuilder.build(
withListener: listener,
action: .swap,
sourceAccount: cryptoAccount,
target: nil
)
presenter.present(router.viewControllable.uiviewController, animated: true)
mimicRIBAttachment(router: router)
return .empty()
case .sign(let sourceAccount, let destination):
let listener = SignFlowListener()
let interactor = SignFlowInteractor()
let router = signFlowBuilder.build(with: listener, interactor: interactor)
router.start(sourceAccount: sourceAccount, destination: destination, presenter: presenter)
mimicRIBAttachment(router: router)
return listener.publisher
case .send(let fromAccount, let target):
let router = sendFlowBuilder.build()
switch (fromAccount, target) {
case (.some(let fromAccount), let target):
router.routeToSend(sourceAccount: fromAccount, destination: target)
case (nil, _):
router.routeToSendLanding(navigationBarHidden: true)
}
presenter.present(router.viewControllable.uiviewController, animated: true)
mimicRIBAttachment(router: router)
return .empty()
case .receive(let account):
presenter.present(receiveCoordinator.builder.receive(), animated: true)
if let account = account {
receiveCoordinator.routeToReceive(sourceAccount: account)
}
return .empty()
case .withdraw(let fiatAccount):
let router = withdrawFlowBuilder.build(sourceAccount: fiatAccount)
router.start()
mimicRIBAttachment(router: router)
return .empty()
case .deposit(let fiatAccount):
let router = depositFlowBuilder.build(with: fiatAccount)
router.start()
mimicRIBAttachment(router: router)
return .empty()
}
}
private func startSellRouter(
_ router: SellFlowRouting,
cryptoAccount: CryptoAccount?,
from presenter: UIViewController
) {
@Sendable func startRouterOnMainThread(target: TransactionTarget?) async {
await MainActor.run {
router.start(with: cryptoAccount, target: target, from: presenter)
}
}
Task(priority: .userInitiated) {
do {
let currency: FiatCurrency = try await app.get(blockchain.user.currency.preferred.fiat.trading.currency)
let account = try await coincore
.account(where: { $0.currencyType == currency })
.values
.next()
.first as? TransactionTarget
await startRouterOnMainThread(target: account)
} catch {
await startRouterOnMainThread(target: nil)
}
}
}
private func presentTooManyPendingOrders(
count: Int,
from presenter: UIViewController
) -> AnyPublisher<TransactionFlowResult, Never> {
let subject = PassthroughSubject<TransactionFlowResult, Never>()
func dismiss() {
presenter.dismiss(animated: true) {
subject.send(.abandoned)
}
}
presenter.present(
PrimaryNavigationView {
TooManyPendingOrdersView(
count: count,
viewActivityAction: { [tabSwapping] in
tabSwapping.switchToActivity()
dismiss()
},
okAction: dismiss
)
.whiteNavigationBarStyle()
.trailingNavigationButton(.close, action: dismiss)
}
)
return subject.eraseToAnyPublisher()
}
/// Checks if the user has a valid trading currency set. If not, it presents a modal asking the user to select one.
///
/// If presented, the modal allows the user to select a trading fiat currency to be the base of transactions. This currency can only be one of the currencies supported for any of our official trading pairs.
/// At the time of this writing, the supported trading currencies are USD, EUR, and GBP.
///
/// The trading currency should be used to define the fiat inputs in the Enter Amount Screen and to show fiat values in the transaction flow.
///
/// - Note: Checking for a trading currency is only required for the Buy flow at this time. However, it may be required for other flows as well in the future.
///
/// - Returns: A `Publisher` whose result is `TransactionFlowResult.completed` if the user had or has successfully selected a trading currency.
/// Otherwise, it returns `TransactionFlowResult.abandoned`. In this case, the user should be prevented from entering the desired transaction flow.
private func presentTradingCurrencySelectorIfNeeded(
from presenter: UIViewController
) -> AnyPublisher<TransactionFlowResult, Never> {
let viewControllerGenerator = viewControllerForSelectingTradingCurrency
// 1. Fetch Trading Currency and supported trading currencies
return fiatCurrencyService.tradingCurrency
.zip(fiatCurrencyService.supportedFiatCurrencies)
.receive(on: DispatchQueue.main)
.flatMap { tradingCurrency, supportedTradingCurrencies -> AnyPublisher<TransactionFlowResult, Never> in
// 2a. If trading currency matches one of supported currencies, return .completed
guard !supportedTradingCurrencies.contains(tradingCurrency) else {
return .just(.completed)
}
// 2b. Otherwise, present new screen, with close => .abandoned, selectCurrency => settingsService.setTradingCurrency
let subject = PassthroughSubject<TransactionFlowResult, Never>()
let sortedCurrencies = Array(supportedTradingCurrencies)
.sorted(by: { $0.displayCode < $1.displayCode })
let viewController = viewControllerGenerator(tradingCurrency, sortedCurrencies) { result in
presenter.dismiss(animated: true) {
subject.send(result)
subject.send(completion: .finished)
}
}
presenter.present(viewController, animated: true, completion: nil)
return subject.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
private func viewControllerForSelectingTradingCurrency(
displayCurrency: FiatCurrency,
currencies: [FiatCurrency],
handler: @escaping (TransactionFlowResult) -> Void
) -> UIViewController {
UIHostingController(
rootView: TradingCurrencySelector(
store: .init(
initialState: .init(
displayCurrency: displayCurrency,
currencies: currencies
),
reducer: TradingCurrency.reducer,
environment: .init(
closeHandler: {
handler(.abandoned)
},
selectionHandler: { [weak self] selectedCurrency in
guard let self = self else {
return
}
self.fiatCurrencyService
.update(tradingCurrency: selectedCurrency, context: .simpleBuy)
.map(TransactionFlowResult.completed)
.receive(on: DispatchQueue.main)
.handleLoaderForLifecycle(loader: self.loadingViewPresenter)
.sink(receiveValue: handler)
.store(in: &self.cancellables)
},
analyticsRecorder: analyticsRecorder
)
)
)
)
}
private func presentError(
error: Error,
action: TransactionFlowAction,
from presenter: UIViewController
) -> AnyPublisher<TransactionFlowResult, Never> {
let subject = PassthroughSubject<TransactionFlowResult, Never>()
func dismiss() {
presenter.dismiss(animated: true) {
subject.send(.abandoned)
}
}
let state = TransactionErrorState.fatalError(.generic(error))
presenter.present(
NavigationView {
ErrorView(
ux: state.ux(action: action.asset),
fallback: {
Icon.globe.accentColor(.semantic.primary)
},
dismiss: dismiss
)
}
.app(app)
)
return subject.eraseToAnyPublisher()
}
private func buildIneligibilityErrorView(
_ reason: ProductIneligibility?,
from presenter: UIViewController
)
-> UIViewController
{
let error = UX.Error(
source: nil,
title: LocalizationConstants.MajorProductBlocked.title,
message: reason?.message ?? LocalizationConstants.MajorProductBlocked.defaultMessage,
actions: {
var actions: [UX.Action] = .default
if let learnMoreUrl = reason?.learnMoreUrl {
let newAction = UX.Action(
title: LocalizationConstants.MajorProductBlocked.ctaButtonLearnMore,
url: learnMoreUrl
)
actions.append(newAction)
}
return actions
}()
)
return UIHostingController(
rootView: ErrorView(
ux: error,
dismiss: { presenter.dismiss(animated: true) }
).app(app)
)
}
}
extension TransactionFlowAction {
/// https://www.notion.so/blockchaincom/Russia-Sanctions-10k-euro-limit-5th-EC-Sanctions-d07a493c9b014a25a83986f390e0ac35
fileprivate var toProductIdentifier: ProductIdentifier? {
switch self {
case .buy:
return .buy
case .sell:
return .sell
case .swap:
return .swap
case .deposit:
return .depositFiat
case .withdraw:
return .withdrawFiat
case .receive:
return .depositCrypto
case .send:
return .withdrawCrypto
case .interestTransfer:
return .depositInterest
case .interestWithdraw:
return .withdrawCrypto
default:
return nil
}
}
}
| lgpl-3.0 | 5e58f127d351452d8b50fe225b492ba1 | 40.93423 | 210 | 0.60519 | 6.07098 | false | false | false | false |
michaelhenry/card.io-iOS-SDK | SampleApp-Swift/SampleApp-Swift/ViewController.swift | 2 | 1488 | //
// ViewController.swift
// SampleApp-Swift
//
// Copyright (c) 2014 PayPal. All rights reserved.
//
import UIKit
class ViewController: UIViewController, CardIOPaymentViewControllerDelegate {
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
CardIOUtilities.preload()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func scanCard(sender: AnyObject) {
var cardIOVC = CardIOPaymentViewController(paymentDelegate: self)
cardIOVC.modalPresentationStyle = .FormSheet
presentViewController(cardIOVC, animated: true, completion: nil)
}
func userDidCancelPaymentViewController(paymentViewController: CardIOPaymentViewController!) {
resultLabel.text = "user canceled"
paymentViewController?.dismissViewControllerAnimated(true, completion: nil)
}
func userDidProvideCreditCardInfo(cardInfo: CardIOCreditCardInfo!, inPaymentViewController paymentViewController: CardIOPaymentViewController!) {
if let info = cardInfo {
let str = NSString(format: "Received card info.\n Number: %@\n expiry: %02lu/%lu\n cvv: %@.", info.redactedCardNumber, info.expiryMonth, info.expiryYear, info.cvv)
resultLabel.text = str
}
paymentViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 8ca127c22fececb90a7ee8a592ca92d9 | 34.428571 | 169 | 0.752016 | 4.769231 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/ResponseDetective/ResponseDetective/Sources/ResponseDetective.swift | 1 | 5129 | //
// ResponseDetective.swift
//
// Copyright © 2016-2017 Netguru Sp. z o.o. All rights reserved.
// Licensed under the MIT License.
//
import Foundation
/// ResponseDetective configuration cluster class that defines the behavior
/// of request interception and logging.
@objc(RDTResponseDetective) public final class ResponseDetective: NSObject {
// MARK: Properties
/// An output facility for reporting requests, responses and errors.
public static var outputFacility: OutputFacility = ConsoleOutputFacility()
/// A class of the URL protocol used to intercept requests.
public static let URLProtocolClass: Foundation.URLProtocol.Type = URLProtocol.self
/// A storage for request predicates.
private static var requestPredicates: [NSPredicate] = []
/// Body deserializers stored by a supported content type.
private static var customBodyDeserializers: [String: BodyDeserializer] = [:]
/// Default body deserializers provided by ResponseDetective.
private static let defaultBodyDeserializers: [String: BodyDeserializer] = [
"*/json": JSONBodyDeserializer(),
"*/xml": XMLBodyDeserializer(),
"*/html": HTMLBodyDeserializer(),
"*/x-www-form-urlencoded": URLEncodedBodyDeserializer(),
"image/*": ImageBodyDeserializer(),
"text/*": PlaintextBodyDeserializer(),
]
// MARK: Configuration
/// Resets the ResponseDetective mutable state.
public static func reset() {
outputFacility = ConsoleOutputFacility()
requestPredicates = []
customBodyDeserializers = [:]
}
/// Enables ResponseDetective in an URL session configuration.
///
/// - Parameters:
/// - configuration: The URL session configuration to enable the
/// session in.
@objc(enableInConfiguration:) public static func enable(inConfiguration configuration: URLSessionConfiguration) {
configuration.protocolClasses?.insert(URLProtocolClass, at: 0)
}
/// Ignores requests matching the given predicate. The predicate will be
/// evaluated with an instance of NSURLRequest.
///
/// - Parameters:
/// - predicate: A predicate for matching a request. If the
/// predicate evaluates to `false`, the request is not intercepted.
@objc(ignoreRequestsMatchingPredicate:) public static func ignoreRequests(matchingPredicate predicate: NSPredicate) {
requestPredicates.append(predicate)
}
/// Checks whether the given request can be incercepted.
///
/// - Parameters:
/// - request: The request to check.
///
/// - Returns: `true` if request can be intercepted, `false` otherwise.
@objc(canInterceptRequest:) public static func canIncercept(request: URLRequest) -> Bool {
return requestPredicates.reduce(true) {
return $0 && !$1.evaluate(with: request)
}
}
// MARK: Deserialization
/// Registers a body deserializer.
///
/// - Parameters:
/// - deserializer: The deserializer to register.
/// - contentType: The supported content type.
@objc(registerBodyDeserializer:forContentType:) public static func registerBodyDeserializer(_ deserializer: BodyDeserializer, forContentType contentType: String) {
customBodyDeserializers[contentType] = deserializer
}
/// Registers a body deserializer.
///
/// - Parameters:
/// - deserializer: The deserializer to register.
/// - contentTypes: The supported content types.
@objc(registerBodyDeserializer:forContentTypes:) public static func registerBodyDeserializer(_ deserializer: BodyDeserializer, forContentTypes contentTypes: [String]) {
for contentType in contentTypes {
registerBodyDeserializer(deserializer, forContentType: contentType)
}
}
/// Deserializes a HTTP body into a string.
///
/// - Parameters:
/// - body: The body to deserialize.
/// - contentType: The content type of the body.
///
/// - Returns: A deserialized body or `nil` if no serializer is capable of
/// deserializing body with the given content type.
@objc(deserializeBody:contentType:) public static func deserialize(body: Data, contentType: String) -> String? {
if let deserializer = findBodyDeserializer(forContentType: contentType) {
return deserializer.deserialize(body: body)
} else {
return nil
}
}
/// Finds a body deserializer by pattern.
///
/// - Parameters:
/// - contentType: The content type to find a deserializer for.
///
/// - Returns: A body deserializer for given `contentType` or `nil`.
@objc(findBodyDeserializerForContentType:) private static func findBodyDeserializer(forContentType contentType: String) -> BodyDeserializer? {
guard let trimmedContentType = contentType.components(separatedBy: ";").first?.trimmingCharacters(in: .whitespaces) else {
return nil
}
for (pattern, deserializer) in defaultBodyDeserializers.appending(elementsOf: customBodyDeserializers) {
let patternParts = pattern.components(separatedBy: "/")
let actualParts = trimmedContentType.components(separatedBy: "/")
guard patternParts.count == 2 && actualParts.count == 2 else {
return nil
}
if ["*" , actualParts[0]].contains(patternParts[0]) && ["*" , actualParts[1]].contains(patternParts[1]) {
return deserializer
}
}
return nil
}
}
| mit | e8cba5ea880ba8a3808a4b533cb6bdaf | 35.892086 | 169 | 0.729719 | 4.342083 | false | true | false | false |
konanxu/WeiBoWithSwift | WeiBo/WeiBo/Classes/Home/View/StatusPictureView.swift | 1 | 3958 | //
// StatusPictureView.swift
// WeiBo
//
// Created by Konan on 16/3/22.
// Copyright © 2016年 Konan. All rights reserved.
//
import UIKit
import SDWebImage
class StatusPictureView: UICollectionView {
var status:Status? {
didSet{
reloadData()
}
}
private var pictureViewLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
init() {
super.init(frame: CGRectZero, collectionViewLayout: pictureViewLayout)
//注册cell
registerClass(PictureViewCell.self, forCellWithReuseIdentifier: collectionCellIdentifier)
delegate = self
dataSource = self
//设置cell之间的间隙
pictureViewLayout.minimumInteritemSpacing = 10
pictureViewLayout.minimumLineSpacing = 10
//设置配图颜色
backgroundColor = UIColor.redColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func calculateImageSize() ->CGSize{
//1.取出配图数量
let count = status?.storedPicURLS?.count
//2.没有配图
if count == 0 || count == nil{
return CGSizeZero
}
//3.配图为一张
print("count:\(count)")
if count == 1{
// let key = status?.storedPicURLS!.first?.absoluteString
let key = status?.bmiddle_picUrl?.absoluteString
print("key:" + key!)
let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
let size = CGSizeMake(image.size.width * 0.5, image.size.height * 0.5)
return size
}
//4.配图为4张
let width = 90
let margin = 10
if count == 4{
let viewWidth = CGFloat(width * 2 + margin)
pictureViewLayout.itemSize = CGSize(width: width, height: width)
return CGSize(width: viewWidth, height: viewWidth)
}
//5.配图为其他张数
let colNumber = 3
let rowNumber = (count! - 1) / 3 + 1
let viewWidth = colNumber * width + (colNumber - 1) * margin
let viewHeight = rowNumber * width + (rowNumber - 1) * margin
// pictureViewLayout.itemSize = CGSize(width: width, height: width)
return CGSize(width: viewWidth, height: viewHeight)
}
}
extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return status?.storedPicURLS?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionCellIdentifier, forIndexPath: indexPath) as! PictureViewCell
cell.imageUrl = status?.storedPicURLS![indexPath.row]
cell.backgroundColor = UIColor.yellowColor()
return cell
}
}
class PictureViewCell:UICollectionViewCell{
var imageUrl:NSURL? {
didSet{
pictureImageView.sd_setImageWithURL(imageUrl)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setUpUI(){
self.addSubview(pictureImageView)
pictureImageView.snp_makeConstraints { (make) -> Void in
make.size.equalTo(pictureImageView.superview!)
make.center.equalTo(pictureImageView.superview!)
}
}
private lazy var pictureImageView:UIImageView = {
let view = UIImageView()
return view
}()
} | mit | 0b333611724d1889c0a4d7b8e99caf82 | 27.696296 | 143 | 0.608056 | 5.219677 | false | false | false | false |
yotao/YunkuSwiftSDKTEST | YunkuSwiftSDK/YunkuSwiftSDK/Class/Utils/CRC32.swift | 1 | 1124 | //
// Created by Brandon on 2017/8/4.
// Copyright (c) 2017 goukuai. All rights reserved.
//
import Foundation
final class CRC32 {
static let MPEG2:CRC32 = CRC32(polynomial: 0x04c11db7)
let table:[UInt32]
init(polynomial:UInt32) {
var table:[UInt32] = [UInt32](repeating: 0x00000000, count: 256)
for i in 0..<table.count {
var crc:UInt32 = UInt32(i) << 24
for _ in 0..<8 {
crc = (crc << 1) ^ ((crc & 0x80000000) == 0x80000000 ? polynomial : 0)
}
table[i] = crc
}
self.table = table
}
func calculate(_ data:Data) -> UInt32 {
return calculate(data, seed: nil)
}
func calculate(_ data:Data, seed:UInt32?) -> UInt32 {
var crc:UInt32 = seed ?? 0xffffffff
for i in 0..<data.count {
crc = (crc << 8) ^ table[Int((crc >> 24) ^ (UInt32(data[i]) & 0xff) & 0xff)]
}
return crc
}
}
extension CRC32: CustomStringConvertible {
// MARK: CustomStringConvertible
var description:String {
return Mirror(reflecting: self).description
}
} | mit | f13d75a7ae548beb4d833607e40bc221 | 25.785714 | 88 | 0.558719 | 3.579618 | false | false | false | false |
santidediego/Learning-Swif-on-my-own | My first playground.playground/Contents.swift | 1 | 1800 | //: Playground - noun: a place where people can play
import Cocoa
//String var
var str = "Hello, world"
let number_five : Int = 5
//Problem trying to change the value of number_five because it´s a constant
//number_five=4
str = str + " i´m fine"
//If you want to use a variable you must write \()
str = str + " \(number_five)"
//Arrays
var my_array = [1,2,3,4,5,6]
my_array.count
for var i=1;i<5;i++
{
my_array.append(0)
}
my_array
for index in 1...4
{
my_array.removeLast()
}
my_array
if my_array[4]==5
{
str="The fourth element is \(my_array[4])"
}
while my_array[0] != 6
{
my_array[0]++
}
my_array
//Optionals
//If we write ? we have a nil variable
var number: Int?
number
number=4
var str2="The number is \(number)"
//We have to write ! in order to show the variable, because it´s an optional
str2="The number is \(number!)"
//Classes and Structs
class vehicle
{
var identificate: Int
var model: String
var km: Int=0
init (identificate: Int, model: String)
{
self.identificate=identificate
self.model=model
}
}
//Now we can define:
class car: vehicle
{
let seats: Int=4
//It´s the same init because seats is a constant
override init(identificate: Int, model: String)
{
super.init(identificate: identificate, model: model)
}
}
class ship: vehicle {
var seats: Int
init(identificate: Int, model: String, seats: Int)
{
self.seats=seats
super.init(identificate: identificate, model: model)
}
}
//Protocols
protocol fix
{
var damaged: Bool {get}
}
class plane: vehicle, fix
{
var damaged : Bool
{
return super.km==100000
}
//In this case, the vehicle is damaged if it has 100000 km
let seats: Int=100
}
| mpl-2.0 | dc3d4b8240392988cd7199d1edb51c69 | 14.754386 | 76 | 0.629176 | 3.184397 | false | false | false | false |
vmachiel/swift | Concentration/Concentration/Concentration.swift | 1 | 5660 | //
// Concentration.swift
// Concentration
//
// Created by Machiel van Dorst on 24-03-18.
// Copyright © 2018 vmachiel. All rights reserved.
//
import Foundation
// The brain of the concentration game. Part of model in MVC. Name the file after the main class
// Think about what your public API should be like: get into the public/private design.
// Three states: none, one, or two cards face up (see methods)
struct Concentration {
// MARK: Properties
// Flipcout: how many cards you've flipped, and score.
var flipCount = 0
var score = 0
// The cards that are availible (defined in Card file). Inited as empty array.
// Private set, because a UI needs to see it, but don't set.
private(set) var cards = [Card]()
// variable that keeps track of the card that's currently faceup if one is faceup ready to be checked
// for a match against a newly chosen card. Optional: of none, or two cards are faceup, set to nil
// Make it a computed property: if get, look at all cards. If only one faceup, return that, else return nil
// if set, pass an index and set the value to that. Turn that card up, all other
// down. Use newValue (also the default local value) for the new value to use
// in the compute.
// Private implemtation.
private var indexOfOneAndOnlyFaceUpCard: Int? {
// Use a closure to get all the indexes of faceup cards. If there's one, one is faceup
// and you return that. If not, return nil
get {
let faceUpCardIndexes = cards.indices.filter{ cards[$0].isFaceUp } // trailing closure syntax!
return faceUpCardIndexes.count == 1 ? faceUpCardIndexes.first : nil
}
// Again if a one and only face up index is set, set all the faceUp properties to false EXCEPT the one
// corresponding to the index.
set(newValue) {
for index in cards.indices {
cards[index].isFaceUp = (index == newValue) // true for only the right index, others will be false
}
}
}
// Init for the Concentration class. Make a card with an ID and add two of them to cards array.
// Do this for the number of pairs you want. This will create two identical cards (same emoji in the
// view, same identifier here). Set flipcount and score to 0, and suffle the cards
init(numberOfPairsOfCards: Int) {
for _ in 0..<numberOfPairsOfCards {
let card = Card() // The unique ID is made here! See Card.swift
cards.append(card)
cards.append(card)
// You do this because Card is a struct, and thus a seperate copy is made (same id).
}
flipCount = 0
score = 0
// Shuffle cards. Take random index using the Int extention
for _ in 1...100 {
for index in cards.indices {
let randomIndex = cards.count.arc4random
let tempCard = cards[index]
cards[index] = cards [randomIndex]
cards[randomIndex] = tempCard
}
}
}
// MARK: Methods
// Main public function: the method that gets called when a user picks a card.
// Three options 1: no cards faceup: just flip the card
// 2: two cards face up (matching or not): face them both down and a new one up,
// starting a new match
// 3: one card face up: face up the new card and check if they match
mutating func chooseCard(at index: Int) {
// Demo assert: check if the index passed is actually one of the indexes of the cards
assert(cards.indices.contains(index), "Concentration.chooseCard(at \(index): index not in cards")
// Only act if card hasn't matched yet.
if !cards[index].isMatched{
flipCount += 1
// Case if there is already one matched, not just one card/chose the same card again
// (if you did this, it ignores and nothing happens and you need to tap another card)
if let matchIndex = indexOfOneAndOnlyFaceUpCard, matchIndex != index {
// match? set isMatched and update score. (no need to update seenBefore.
if cards[matchIndex].identifier == cards[index].identifier {
cards[matchIndex].isMatched = true
cards[index].isMatched = true
score += 2
// not a match? Check if seen before and lower score. Set seen before for both
} else {
if cards[matchIndex].seenBefore || cards[index].seenBefore {
score -= 1
}
cards[matchIndex].seenBefore = true
cards[index].seenBefore = true
}
// Now the check is done, face up the card you just chose (so the controller can update view)
// the indexOfOneAndOnlyFaceUpCard DOESN'T need to be set to nil, because every time it is
// referenced, the property's value is computed based on the current state.
cards[index].isFaceUp = true
// none or two cards face up so can't match, so set the chosen index as
// indexOfOneAndOnlyFaceUpCard. The isFaceUp state of all the cards is updated
// because of the set method of indexOfOneAndOnlyFaceUpCard (computed property)
} else {
indexOfOneAndOnlyFaceUpCard = index
}
}
}
}
| mit | d70dc2dad7a43cec8a6f2e184c5ec3ad | 42.198473 | 115 | 0.599399 | 4.704073 | false | false | false | false |
edmw/Volumio_ios | Pods/Eureka/Source/Core/BaseRow.swift | 4 | 9534 | // BaseRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class BaseRow : BaseRowType {
var callbackOnChange: (()-> Void)?
var callbackCellUpdate: (()-> Void)?
var callbackCellSetup: Any?
var callbackCellOnSelection: (()-> Void)?
var callbackOnExpandInlineRow: Any?
var callbackOnCollapseInlineRow: Any?
var callbackOnCellHighlightChanged: (()-> Void)?
var callbackOnRowValidationChanged: (() -> Void)?
var _inlineRow: BaseRow?
public var validationOptions: ValidationOptions = .validatesOnBlur
// validation state
public internal(set) var validationErrors = [ValidationError]() {
didSet {
guard validationErrors != oldValue else { return }
RowDefaults.onRowValidationChanged["\(type(of: self))"]?(baseCell, self)
callbackOnRowValidationChanged?()
}
}
public internal(set) var wasBlurred = false
public internal(set) var wasChanged = false
public var isValid: Bool { return validationErrors.isEmpty }
public var isHighlighted: Bool = false
/// The title will be displayed in the textLabel of the row.
public var title: String?
/// Parameter used when creating the cell for this row.
public var cellStyle = UITableViewCellStyle.value1
/// String that uniquely identifies a row. Must be unique among rows and sections.
public var tag: String?
/// The untyped cell associated to this row.
public var baseCell: BaseCell! { return nil }
/// The untyped value of this row.
public var baseValue: Any? {
set {}
get { return nil }
}
public func validate() -> [ValidationError] {
return []
}
public static var estimatedRowHeight: CGFloat = 44.0
/// Condition that determines if the row should be disabled or not.
public var disabled : Condition? {
willSet { removeFromDisabledRowObservers() }
didSet { addToDisabledRowObservers() }
}
/// Condition that determines if the row should be hidden or not.
public var hidden : Condition? {
willSet { removeFromHiddenRowObservers() }
didSet { addToHiddenRowObservers() }
}
/// Returns if this row is currently disabled or not
public var isDisabled : Bool { return disabledCache }
/// Returns if this row is currently hidden or not
public var isHidden : Bool { return hiddenCache }
/// The section to which this row belongs.
public weak var section: Section?
public required init(tag: String? = nil){
self.tag = tag
}
/**
Method that reloads the cell
*/
open func updateCell() {}
/**
Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell.
*/
open func didSelect() {}
open func prepare(for segue: UIStoryboardSegue) {}
/**
Returns the IndexPath where this row is in the current form.
*/
public final var indexPath: IndexPath? {
guard let sectionIndex = section?.index, let rowIndex = section?.index(of: self) else { return nil }
return IndexPath(row: rowIndex, section: sectionIndex)
}
var hiddenCache = false
var disabledCache = false {
willSet {
if newValue == true && disabledCache == false {
baseCell.cellResignFirstResponder()
}
}
}
}
extension BaseRow {
/**
Evaluates if the row should be hidden or not and updates the form accordingly
*/
public final func evaluateHidden() {
guard let h = hidden, let form = section?.form else { return }
switch h {
case .function(_ , let callback):
hiddenCache = callback(form)
case .predicate(let predicate):
hiddenCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
if hiddenCache {
section?.hide(row: self)
}
else{
section?.show(row: self)
}
}
/**
Evaluates if the row should be disabled or not and updates it accordingly
*/
public final func evaluateDisabled() {
guard let d = disabled, let form = section?.form else { return }
switch d {
case .function(_ , let callback):
disabledCache = callback(form)
case .predicate(let predicate):
disabledCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
updateCell()
}
final func wasAddedTo(section: Section) {
self.section = section
if let t = tag {
assert(section.form?.rowsByTag[t] == nil, "Duplicate tag \(t)")
self.section?.form?.rowsByTag[t] = self
self.section?.form?.tagToValues[t] = baseValue != nil ? baseValue! : NSNull()
}
addToRowObservers()
evaluateHidden()
evaluateDisabled()
}
final func addToHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func addToDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func addToRowObservers(){
addToHiddenRowObservers()
addToDisabledRowObservers()
}
final func willBeRemovedFromForm(){
(self as? BaseInlineRowType)?.collapseInlineRow()
if let t = tag {
section?.form?.rowsByTag[t] = nil
section?.form?.tagToValues[t] = nil
}
removeFromRowObservers()
}
final func removeFromHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func removeFromDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func removeFromRowObservers(){
removeFromHiddenRowObservers()
removeFromDisabledRowObservers()
}
}
extension BaseRow: Equatable, Hidable, Disableable {}
extension BaseRow {
public func reload(with rowAnimation: UITableViewRowAnimation = .none) {
guard let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView, let indexPath = indexPath else { return }
tableView.reloadRows(at: [indexPath], with: rowAnimation)
}
public func deselect(animated: Bool = true) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.deselectRow(at: indexPath, animated: animated)
}
public func select(animated: Bool = false) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: .none)
}
}
public func ==(lhs: BaseRow, rhs: BaseRow) -> Bool{
return lhs === rhs
}
| gpl-3.0 | 62b675d88359c119a5ca63b513d33752 | 34.574627 | 177 | 0.64034 | 5.123052 | false | false | false | false |
liuweicode/LinkimFoundation | Example/LinkimFoundation/Foundation/UI/Component/TextField/PasswordTextField.swift | 1 | 1185 | //
// PasswordTextField.swift
// LinkimFoundation
//
// Created by 刘伟 on 16/7/8.
// Copyright © 2016年 CocoaPods. All rights reserved.
//
import UIKit
let kPasswordMaxLen = 20 // 密码最大长度限制
class PasswordTextField: BaseTextField,UITextFieldDelegate,BaseTextFieldDelegate {
func initTextData() {
self.placeholder = "请输入密码"
self.keyboardType = .Default
self.font = UIFont.systemFontOfSize(16)
self.secureTextEntry = true
self.clearButtonMode = .WhileEditing
self.translatesAutoresizingMaskIntoConstraints = false
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
self.delegate?.textField!(textField, shouldChangeCharactersInRange: range, replacementString: string)
let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
return newString.length <= kPasswordMaxLen
}
func textFieldDidEndEditing(textField: UITextField) {
self.delegate?.textFieldDidEndEditing?(textField)
}
}
| mit | 93da34a040f9b7384408804a0147f3b1 | 30.135135 | 132 | 0.705729 | 5.165919 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxSwift/RxSwift/Traits/Completable+AndThen.swift | 4 | 4909 | //
// Completable+AndThen.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/2/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Never {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Single<E>) -> Single<E> {
let completable = self.primitiveSequence.asObservable()
return Single(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Maybe<E>) -> Maybe<E> {
let completable = self.primitiveSequence.asObservable()
return Maybe(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen(_ second: Completable) -> Completable {
let completable = self.primitiveSequence.asObservable()
return Completable(raw: ConcatCompletable(completable: completable, second: second.asObservable()))
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func andThen<E>(_ second: Observable<E>) -> Observable<E> {
let completable = self.primitiveSequence.asObservable()
return ConcatCompletable(completable: completable, second: second.asObservable())
}
}
final private class ConcatCompletable<Element>: Producer<Element> {
fileprivate let _completable: Observable<Never>
fileprivate let _second: Observable<Element>
init(completable: Observable<Never>, second: Observable<Element>) {
self._completable = completable
self._second = second
}
override func run<O>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O : ObserverType, O.E == Element {
let sink = ConcatCompletableSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final private class ConcatCompletableSink<O: ObserverType>
: Sink<O>
, ObserverType {
typealias E = Never
typealias Parent = ConcatCompletable<O.E>
private let _parent: Parent
private let _subscription = SerialDisposable()
init(parent: Parent, observer: O, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
case .next:
break
case .completed:
let otherSink = ConcatCompletableSinkOther(parent: self)
self._subscription.disposable = self._parent._second.subscribe(otherSink)
}
}
func run() -> Disposable {
let subscription = SingleAssignmentDisposable()
self._subscription.disposable = subscription
subscription.setDisposable(self._parent._completable.subscribe(self))
return self._subscription
}
}
final private class ConcatCompletableSinkOther<O: ObserverType>
: ObserverType {
typealias E = O.E
typealias Parent = ConcatCompletableSink<O>
private let _parent: Parent
init(parent: Parent) {
self._parent = parent
}
func on(_ event: Event<O.E>) {
self._parent.forwardOn(event)
if event.isStopEvent {
self._parent.dispose()
}
}
}
| apache-2.0 | 7f1953ac79ef04be466ea6dd1cfa8c25 | 36.181818 | 148 | 0.682559 | 4.792969 | false | false | false | false |
lucaslimapoa/NewsAPISwift | Source/Provider/URLRequestBuilder.swift | 1 | 709 | //
// URLRequestBuilder.swift
// NewsAPISwift
//
// Created by Lucas Lima on 22/06/18.
// Copyright © 2018 Lucas Lima. All rights reserved.
//
import Foundation
class URLRequestBuilder {
var url: URL?
var headers: [String: String]?
init(url: URL? = nil, headers: [String: String]? = nil) {
self.url = url
self.headers = headers
}
}
extension URLRequest {
typealias BuilderClosure = ((URLRequestBuilder) -> ())
init?(builder: URLRequestBuilder) {
guard let url = builder.url else { return nil }
self.init(url: url)
if let headers = builder.headers {
self.allHTTPHeaderFields = headers
}
}
}
| mit | 286e05bd33cacf6bab6bd8bdae12a89b | 21.125 | 61 | 0.596045 | 4.068966 | false | false | false | false |
apple/swift-nio | Tests/NIOPosixTests/NIOThreadPoolTest+XCTest.swift | 1 | 1184 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// NIOThreadPoolTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension NIOThreadPoolTest {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (NIOThreadPoolTest) -> () throws -> Void)] {
return [
("testThreadNamesAreSetUp", testThreadNamesAreSetUp),
("testThreadPoolStartsMultipleTimes", testThreadPoolStartsMultipleTimes),
]
}
}
| apache-2.0 | 45f6421b1da6fc6c98b3ef7f38cb99f6 | 32.828571 | 162 | 0.61402 | 5.038298 | false | true | false | false |
gregomni/swift | test/DebugInfo/inout.swift | 10 | 2583 | // RUN: %target-swift-frontend %s -emit-ir -g -module-name inout -o %t.ll
// RUN: cat %t.ll | %FileCheck %s
// RUN: cat %t.ll | %FileCheck %s --check-prefix=PROMO-CHECK
// RUN: cat %t.ll | %FileCheck %s --check-prefix=FOO-CHECK
// LValues are direct values, too. They are reference types, though.
func Close(_ fn: () -> Int64) { fn() }
typealias MyFloat = Float
// CHECK: define hidden swiftcc void @"$s5inout13modifyFooHeap{{[_0-9a-zA-Z]*}}F"
// CHECK: %[[ALLOCA:.*]] = alloca %Ts5Int64V*
// CHECK: call void @llvm.dbg.declare(metadata
// CHECK-SAME: %[[ALLOCA]], metadata ![[A:[0-9]+]]
// Closure with promoted capture.
// PROMO-CHECK: define {{.*}}@"$s5inout13modifyFooHeapyys5Int64Vz_SftFADyXEfU_"
// PROMO-CHECK: call void @llvm.dbg.declare(metadata %Ts5Int64V** %
// PROMO-CHECK-SAME: metadata ![[A1:[0-9]+]], metadata !DIExpression(DW_OP_deref))
// PROMO-CHECK: ![[INT:.*]] = !DICompositeType({{.*}}identifier: "$ss5Int64VD"
// PROMO-CHECK: ![[A1]] = !DILocalVariable(name: "a", arg: 1,{{.*}} type: ![[INT]]
func modifyFooHeap(_ a: inout Int64,
// CHECK-DAG: ![[A]] = !DILocalVariable(name: "a", arg: 1{{.*}} line: [[@LINE-1]],{{.*}} type: ![[RINT:[0-9]+]]
// CHECK-DAG: ![[RINT]] = !DICompositeType({{.*}}identifier: "$ss5Int64VD"
_ b: MyFloat)
{
let b = b
if (b > 2.71) {
a = a + 12// Set breakpoint here
}
// Close over the variable to disable promotion of the inout shadow.
Close({ a })
}
// Inout reference type.
// FOO-CHECK: define {{.*}}@"$s5inout9modifyFooyys5Int64Vz_SftF"
// FOO-CHECK: call void @llvm.dbg.declare(metadata %Ts5Int64V** %
// FOO-CHECK-SAME: metadata ![[U:[0-9]+]], metadata !DIExpression(DW_OP_deref))
func modifyFoo(_ u: inout Int64,
// FOO-CHECK-DAG: !DILocalVariable(name: "v", arg: 2{{.*}} line: [[@LINE+3]],{{.*}} type: ![[LET_MYFLOAT:[0-9]+]]
// FOO-CHECK-DAG: [[U]] = !DILocalVariable(name: "u", arg: 1,{{.*}} line: [[@LINE-2]],{{.*}} type: ![[RINT:[0-9]+]]
// FOO-CHECK-DAG: ![[RINT]] = !DICompositeType({{.*}}identifier: "$ss5Int64VD"
_ v: MyFloat)
// FOO-CHECK-DAG: ![[LET_MYFLOAT]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[MYFLOAT:[0-9]+]])
// FOO-CHECK-DAG: ![[MYFLOAT]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s5inout7MyFloataD",{{.*}} baseType: ![[FLOAT:[0-9]+]]
// FOO-CHECK-DAG: ![[FLOAT]] = !DICompositeType({{.*}}identifier: "$sSfD"
{
if (v > 2.71) {
u = u - 41
}
}
func main() -> Int64 {
var c = 11 as Int64
modifyFoo(&c, 3.14)
var d = 64 as Int64
modifyFooHeap(&d, 1.41)
return 0
}
main()
| apache-2.0 | a7a0de26c0d1c8695caecf64414cb2dc | 38.738462 | 130 | 0.593883 | 3.006985 | false | false | false | false |
SimonFairbairn/Stormcloud | Tests/StormcloudTests/StormcloudCoreDataTests.swift | 1 | 19247 | //
// StormcloudCoreDataTests.swift
// Stormcloud
//
// Created by Simon Fairbairn on 21/10/2015.
// Copyright © 2015 Simon Fairbairn. All rights reserved.
//
import CoreData
import XCTest
@testable import Stormcloud
enum StormcloudTestError : Error {
case invalidContext
case couldntCreateManagedObject
}
class StormcloudCoreDataTests: StormcloudTestsBaseClass, StormcloudRestoreDelegate {
let totalTags = 4
let totalClouds = 2
let totalRaindrops = 2
var stack : CoreDataStack!
override func setUp() {
self.fileExtension = "json"
stack = CoreDataStack(modelName: "clouds")
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func insertCloudWithNumber(_ number : Int) throws -> Cloud {
if let context = self.stack.managedObjectContext {
do {
let didRain : Bool? = ( number % 2 == 0 ) ? true : nil
return try Cloud.insertCloudWithName("Cloud \(number)", order: number, didRain: didRain, inContext: context)
} catch {
XCTFail("Couldn't create cloud")
throw StormcloudTestError.couldntCreateManagedObject
}
} else {
throw StormcloudTestError.invalidContext
}
}
func insertTagWithName(_ name : String ) throws -> Tag {
if let context = self.stack.managedObjectContext {
do {
return try Tag.insertTagWithName(name, inContext: context)
} catch {
XCTFail("Couldn't create drop")
throw StormcloudTestError.couldntCreateManagedObject
}
} else {
throw StormcloudTestError.invalidContext
}
}
func insertDropWithType(_ type : RaindropType, cloud : Cloud ) throws -> Raindrop {
if let context = self.stack.managedObjectContext {
do {
return try Raindrop.insertRaindropWithType(type, withCloud: cloud, inContext: context)
} catch {
XCTFail("Couldn't create drop")
throw StormcloudTestError.couldntCreateManagedObject
}
} else {
throw StormcloudTestError.invalidContext
}
}
func setupStack() {
let expectation = self.expectation(description: "Stack Setup")
stack.setupStore { () -> Void in
XCTAssertNotNil(self.stack.managedObjectContext)
expectation.fulfill()
}
waitForExpectations(timeout: 4.0, handler: nil)
}
func addTags() -> [Tag] {
print("Adding tags")
var tags : [Tag] = []
do {
let tag1 = try self.insertTagWithName("Wet")
let tag2 = try self.insertTagWithName("Windy")
let tag3 = try self.insertTagWithName("Dark")
let tag4 = try self.insertTagWithName("Thundery")
tags.append(tag1)
tags.append(tag2)
tags.append(tag3)
tags.append(tag4)
} catch {
XCTFail("Failed to insert tags")
}
return tags
}
func addObjectsWithNumber(_ number : Int, tags : [Tag] = []) {
let cloud : Cloud
do {
cloud = try self.insertCloudWithNumber(number)
let drop1 = try self.insertDropWithType(RaindropType.Heavy, cloud: cloud)
let drop2 = try self.insertDropWithType(RaindropType.Light, cloud: cloud)
cloud.addToRaindrops(drop1)
cloud.addToRaindrops(drop2)
if tags.count > 0 {
cloud.tags = NSSet(array: tags)
}
} catch {
XCTFail("Failed to create data: \(error)")
}
}
func backupCoreData(with manager : Stormcloud) {
guard let context = self.stack.managedObjectContext else {
XCTFail("Context not available")
return
}
let expectation = self.expectation(description: "Insert expectation")
self.stack.save()
manager.backupCoreDataEntities(in: context) { (error, metadata) -> () in
if let _ = error {
XCTFail("Failed to back up Core Data entites")
}
expectation.fulfill()
}
waitForExpectations(timeout: 4.0, handler: nil)
}
func test_setupCoreData() {
let manager = Stormcloud()
manager.delegate = self
self.setupStack()
let tags = self.addTags()
self.addObjectsWithNumber(5, tags: tags)
}
func testThatBackingUpIndividualObjectsWorks() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
self.setupStack()
let tags = self.addTags()
self.addObjectsWithNumber(5, tags: tags)
waitForFiles(manager)
guard let context = self.stack.managedObjectContext else {
XCTFail("Context not available")
return
}
self.stack.save()
let expectation = self.expectation(description: "Insert expectation")
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
let objects = try! context.fetch(request)
manager.backupCoreDataObjects( objects: objects) { (error, metadata) -> () in
if let hasError = error {
XCTFail("Failed to back up Core Data entites: \(hasError)")
}
expectation.fulfill()
}
waitForExpectations(timeout: 30.0, handler: nil)
let items = self.listItemsAtURL()
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
}
func testThatBackingUpCoreDataCreatesFile() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
self.setupStack()
self.addObjectsWithNumber(1)
waitForFiles(manager)
self.backupCoreData(with: manager)
let items = self.listItemsAtURL()
sleep(1)
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
}
func testThatBackingUpCoreDataCreatesCorrectFormat() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
self.setupStack()
let tags = self.addTags()
for i in 1...totalClouds {
self.addObjectsWithNumber(i, tags: tags)
}
waitForFiles(manager)
self.backupCoreData(with: manager)
let items = self.listItemsAtURL()
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
let url = items[0]
let data = try? Data(contentsOf: url as URL)
var jsonObjects : Any = [:]
if let hasData = data {
do {
jsonObjects = try JSONSerialization.jsonObject(with: hasData, options: JSONSerialization.ReadingOptions.allowFragments)
} catch {
XCTFail("Invalid JSON")
}
} else {
XCTFail("Couldn't read data")
}
XCTAssertEqual((jsonObjects as AnyObject).count, (totalRaindrops * totalClouds) + totalClouds + totalTags)
if let objects = jsonObjects as? [String : AnyObject] {
for (key, value) in objects {
if key.contains("Cloud") {
if let isDict = value as? [String : AnyObject], let type = isDict[StormcloudEntityKeys.EntityType.rawValue] as? String {
XCTAssertEqual(type, "Cloud")
// Assert that the keys exist
XCTAssertNotNil(isDict["order"])
XCTAssertNotNil(isDict["added"])
if let name = isDict["name"] as? String , name == "Cloud 1" {
if let _ = isDict["didRain"] as? Int {
XCTFail("Cloud 1's didRain property should be nil")
} else {
XCTAssertEqual(name, "Cloud 1")
}
}
if let name = isDict["name"] as? String , name == "Cloud 2" {
if let _ = isDict["didRain"] as? Int {
XCTAssertEqual(name, "Cloud 2")
} else {
XCTFail("Cloud 1's didRain property should be set")
}
}
if let value = isDict["chanceOfRain"] as? Float {
XCTAssertEqual(value, 0.45)
} else {
XCTFail("Chance of Rain poperty doesn't exist or is not float")
}
if let relationship = isDict["raindrops"] as? [String] {
XCTAssertEqual(relationship.count, 2)
} else {
XCTFail("Relationship doesn't exist")
}
} else {
XCTFail("Wrong type stored in dictionary")
}
}
if key.contains("Raindrop") {
if let isDict = value as? [String : AnyObject], let type = isDict[StormcloudEntityKeys.EntityType.rawValue] as? String {
XCTAssertEqual(type, "Raindrop")
if let _ = isDict["type"] as? String {
} else {
XCTFail("Type poperty doesn't exist")
}
if let _ = isDict["colour"] as? String {
} else {
XCTFail("Colour poperty doesn't exist")
}
if let value = isDict["timesFallen"] as? NSNumber {
XCTAssertEqual(value, 10)
} else {
XCTFail("Times Fallen poperty doesn't exist or is not number")
}
if let decimalValue = isDict["raindropValue"] as? String {
XCTAssertEqual(decimalValue, "10.54")
} else {
XCTFail("Value poperty doesn't exist or is not number")
}
if let relationship = isDict["cloud"] as? [String] {
XCTAssertEqual(relationship.count, 1)
XCTAssert(relationship[0].contains("Cloud"))
} else {
XCTFail("Relationship doesn't exist")
}
} else {
XCTFail("Wrong type stored in dictionary")
}
}
}
} else {
XCTFail("JSON object invalid")
}
// Read JSON
}
func testThatRestoringRestoresThingsCorrectly() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
waitForFiles(manager)
// Keep a copy of all the data and make sure it's the same when it gets back in to the DB
// Give it a chance to catch up
self.setupStack()
let tags = self.addTags()
self.addObjectsWithNumber(1, tags: tags)
self.addObjectsWithNumber(2, tags: tags)
self.backupCoreData(with: manager)
let items = self.listItemsAtURL()
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
guard manager.items(for: .json).count > 0 else {
XCTFail("Invalid number of items")
return
}
let exp = self.expectation(description: "Restore expectation")
manager.restoreCoreDataBackup(from: manager.items(for: .json)[0], to: stack.managedObjectContext!) { (success) -> () in
XCTAssertNil(success)
XCTAssertEqual(Thread.current, Thread.main)
exp.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
if let context = self.stack.managedObjectContext {
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)]
let clouds : [Cloud]
do {
clouds = try context.fetch(request)
} catch {
clouds = []
}
XCTAssertEqual(clouds.count, 2)
if clouds.count > 1 {
let cloud1 = clouds[0]
XCTAssertEqual(cloud1.tags?.count, totalTags)
XCTAssertEqual(cloud1.raindrops?.count, totalRaindrops)
XCTAssertEqual(cloud1.name, "Cloud 1")
XCTAssertEqual(cloud1.chanceOfRain?.floatValue, Float( 0.45))
XCTAssertNil(cloud1.didRain)
if let raindrop = cloud1.raindrops?.anyObject() as? Raindrop {
XCTAssertEqual(raindrop.raindropValue?.stringValue, "10.54")
XCTAssertEqual(raindrop.timesFallen, 10)
}
let cloud2 = clouds[1]
XCTAssertEqual(cloud2.tags?.count, totalTags)
if let raindrops = cloud2.raindrops?.allObjects {
XCTAssertEqual(raindrops.count, totalRaindrops)
}
XCTAssertEqual(cloud2.name, "Cloud 2")
XCTAssertEqual(cloud2.chanceOfRain?.floatValue, Float(0.45))
if let bool = cloud2.didRain?.boolValue {
XCTAssert(bool)
}
if let raindrop = cloud2.raindrops?.anyObject() as? Raindrop {
XCTAssertEqual(raindrop.cloud, cloud2)
XCTAssertEqual(raindrop.raindropValue?.stringValue, "10.54")
XCTAssertEqual(raindrop.timesFallen, 10)
}
} else {
XCTFail("Not enough clouds in DB")
}
}
}
func testThatRestoringIndividualItemsWorks() {
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
// Keep a copy of all the data and make sure it's the same when it gets back in to the DB
self.copyItems(extra: true)
self.setupStack()
let items = self.listItemsAtURL()
waitForFiles(manager)
XCTAssertEqual(items.count, 3)
manager.restoreDelegate = self
guard let context = stack.managedObjectContext else {
XCTFail("Context not ready")
return
}
guard let file = items.filter( { $0.path.contains("fragment") } ).first else {
XCTFail("Couldn't find correct file")
return
}
do {
let jsonData = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
if let isJSON = json as? [String : AnyObject] {
let exp = expectation(description: "Individual Restore Expectation")
manager.insertIndividualObjectsWithContext(context, data: isJSON, completion: { (success) in
guard success else {
XCTFail("Failed to restore objects")
return
}
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
let objects = try! context.fetch(request)
XCTAssertEqual(objects.count, 1)
if let cloud = objects.first {
XCTAssertEqual(cloud.raindrops!.count, 2)
if let raindrops = cloud.raindrops as? Set<Raindrop> {
let heavy = raindrops.filter() { $0.type == "Heavy" }
XCTAssertEqual(heavy.count, 1, "There should be one heavy raindrop")
}
}
exp.fulfill()
})
waitForExpectations(timeout: 3, handler: nil)
} else {
XCTFail("Invalid Format")
}
} catch {
XCTFail("Failed to read contents")
}
}
func testWeirdStrings() {
// Keep a copy of all the data and make sure it's the same when it gets back in to the DB
let manager = Stormcloud(with: TestDocumentProvider())
manager.delegate = self
self.setupStack()
if let context = self.stack.managedObjectContext {
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)]
let clouds : [Cloud]
do {
clouds = try context.fetch(request)
} catch {
clouds = []
}
XCTAssertEqual(clouds.count, 0)
}
if let context = self.stack.managedObjectContext {
do {
_ = try Cloud.insertCloudWithName("\("String \" With 😀🐼🐵⸘&§@$€¥¢£₽₨₩৲₦₴₭₱₮₺฿৳૱௹﷼₹₲₪₡₥₳₤₸₢₵៛₫₠₣₰₧₯₶₷")", order: 0, didRain: true, inContext: context)
} catch {
print("Error inserting cloud")
}
}
waitForFiles(manager)
self.backupCoreData(with: manager)
let items = self.listItemsAtURL()
XCTAssertEqual(items.count, 1)
XCTAssertEqual(manager.items(for: .json).count, 1)
guard items.count == 1 else {
XCTFail("Incorrect count for items")
return
}
print(manager.urlForItem(manager.items(for: .json)[0]) ?? "No metadata item found")
let expectation = self.expectation(description: "Restore expectation")
manager.restoreCoreDataBackup(from: manager.items(for: .json)[0], to: stack.managedObjectContext!) { (success) -> () in
XCTAssertNil(success)
XCTAssertEqual(Thread.current, Thread.main)
expectation.fulfill()
}
waitForExpectations(timeout: 10.0, handler: nil)
if let context = self.stack.managedObjectContext {
let request = NSFetchRequest<Cloud>(entityName: "Cloud")
request.sortDescriptors = [NSSortDescriptor(key: "order", ascending: true)]
let clouds : [Cloud]
do {
clouds = try context.fetch(request)
} catch {
clouds = []
}
XCTAssertEqual(clouds.count, 1)
if clouds.count == 1 {
let cloud1 = clouds[0]
XCTAssertEqual("\("String \" With 😀🐼🐵⸘&§@$€¥¢£₽₨₩৲₦₴₭₱₮₺฿৳૱௹﷼₹₲₪₡₥₳₤₸₢₵៛₫₠₣₰₧₯₶₷")", cloud1.name)
}
}
}
func stormcloud(stormcloud: Stormcloud, shouldRestore objects: [String : AnyObject], toEntityWithName name: String) -> Bool {
return true
}
}
| mit | a3620c25c00818d82e9263ade538307d | 31.497445 | 164 | 0.530457 | 4.856415 | false | false | false | false |
LYM-mg/MGDYZB | MGDYZB/MGDYZB/Class/Home/Controller/FunnyViewController.swift | 1 | 5456 | //
// FunnyViewController.swift
// MGDYZB
//
// Created by ming on 16/10/25.
// Copyright © 2016年 ming. All rights reserved.
//
import UIKit
import SafariServices
private let kTopMargin : CGFloat = 8
class FunnyViewController: BaseViewController {
// MARK: 懒加载ViewModel对象
fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel()
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
// 1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize.zero
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: self!.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.scrollsToTop = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: kItemMargin, bottom: kItemMargin, right: kItemMargin)
// 3.注册
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func setUpMainView() {
contentView = collectionView
view.addSubview(collectionView)
super.setUpMainView()
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension FunnyViewController {
func loadData() {
// 1.请求数据
funnyVM.loadFunnyData {
// 1.1.刷新表格
self.collectionView.reloadData()
// 1.2.数据请求完成
self.loadDataFinished()
}
}
}
// MARK: - UICollectionViewDataSource
extension FunnyViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return funnyVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return funnyVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
/// 其他组数据
// 1.取出Cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
// 2.给cell设置数据
cell.anchor = funnyVM.anchorGroups[(indexPath as NSIndexPath).section].anchors[(indexPath as NSIndexPath).item]
return cell
}
}
// MARK: - UICollectionViewDelegate
extension FunnyViewController: UICollectionViewDelegate {
@objc(collectionView:viewForSupplementaryElementOfKind:atIndexPath:) func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.给HeaderView设置数据
headerView.group = funnyVM.anchorGroups[(indexPath as NSIndexPath).section]
return headerView
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1.取出对应的主播信息
let anchor = funnyVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// 2.判断是秀场房间&普通房间
anchor.isVertical == 0 ? pushNormalRoomVc(anchor: anchor) : presentShowRoomVc(anchor: anchor)
}
fileprivate func presentShowRoomVc(anchor: AnchorModel) {
if #available(iOS 9.0, *) {
// 1.创建SFSafariViewController
let safariVC = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true)
// 2.以Modal方式弹出
present(safariVC, animated: true, completion: nil)
} else {
let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
present(webVC, animated: true, completion: nil)
}
}
fileprivate func pushNormalRoomVc(anchor: AnchorModel) {
// 1.创建WebViewController
let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl)
webVC.navigationController?.setNavigationBarHidden(true, animated: true)
// 2.以Push方式弹出
navigationController?.pushViewController(webVC, animated: true)
}
}
| mit | 07e861f916ea6f1ff224a7e99e4a69f8 | 36.302817 | 231 | 0.688692 | 5.789071 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/generic_existentials/main.swift | 2 | 1131 | class MyClass {
var x: Int
init(_ x: Int) {
self.x = x
}
}
func f<T>(_ x : T) -> T {
return x //%self.expect("frame var -d run-target -- x", substrs=['(a.MyClass) x', '(x = 23)'])
//%self.expect("expr -d run-target -- x", substrs=['(a.MyClass) $R', '(x = 23)'])
}
f(MyClass(23) as Any)
f(MyClass(23) as AnyObject)
func g<T>(_ x : T) -> T {
return x //%self.expect("frame var -d run-target -- x", substrs=['(a.MyStruct) x', '(x = 23)'])
//%self.expect("expr -d run-target -- x", substrs=['(a.MyStruct) $R', '(x = 23)'])
}
struct MyStruct {
var x: Int
init(_ x: Int) {
self.x = x
}
}
g(MyStruct(23) as Any)
func h<T>(_ x : T) -> T {
return x //%self.expect("frame var -d run-target -- x", substrs=['(a.MyBigStruct) x', '(x = 23, y = 24, z = 25, w = 26)'])
//%self.expect("expr -d run-target -- x", substrs=['(a.MyBigStruct) $R', '(x = 23, y = 24, z = 25, w = 26)'])
}
struct MyBigStruct {
var x: Int
var y: Int
var z: Int
var w: Int
init(_ x: Int) {
self.x = x
self.y = x + 1
self.z = x + 2
self.w = x + 3
}
}
h(MyBigStruct(23) as Any)
| apache-2.0 | 37960839d6a95c5727692bb87203d9d8 | 21.62 | 124 | 0.504863 | 2.686461 | false | false | false | false |
elumalaiIvan/hello-world | TestCoreData/TestCoreData/AppDelegate.swift | 1 | 4616 | //
// AppDelegate.swift
// TestCoreData
//
// Created by Elumalai Ramalingam on 11/05/17.
// Copyright © 2017 Elumalai Ramalingam. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "TestCoreData")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 56e1d21e76b8c6d6d9f0921ffcd2f6cb | 48.623656 | 285 | 0.687324 | 5.812343 | false | false | false | false |
apple/swift-tools-support-core | Sources/TSCUtility/BuildFlags.swift | 1 | 1252 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
// FIXME: This belongs somewhere else, but we don't have a layer specifically
// for BuildSupport style logic yet.
//
/// Build-tool independent flags.
@available(*, deprecated, message: "replace with SwiftPM `PackageModel.BuildFlags`")
public struct BuildFlags: Encodable {
/// Flags to pass to the C compiler.
public var cCompilerFlags: [String]
/// Flags to pass to the C++ compiler.
public var cxxCompilerFlags: [String]
/// Flags to pass to the linker.
public var linkerFlags: [String]
/// Flags to pass to the Swift compiler.
public var swiftCompilerFlags: [String]
public init(
xcc: [String]? = nil,
xcxx: [String]? = nil,
xswiftc: [String]? = nil,
xlinker: [String]? = nil
) {
cCompilerFlags = xcc ?? []
cxxCompilerFlags = xcxx ?? []
linkerFlags = xlinker ?? []
swiftCompilerFlags = xswiftc ?? []
}
}
| apache-2.0 | db8ea5a9d84a8a7fcee576e07d5ebbe6 | 29.536585 | 84 | 0.664537 | 4.215488 | false | false | false | false |
DavidSkrundz/Lua | Sources/Lua/Value/Table.swift | 1 | 2086 | //
// Table.swift
// Lua
//
/// Represent a table within Lua
public class Table {
private let lua: Lua
internal let reference: Reference
public var hashValue: Int {
return Int(self.reference.rawValue)
}
/// Create a new `Table` by popping the top value from the stack
internal init(lua: Lua) {
self.lua = lua
self.reference = self.lua.popWithReference()
}
deinit {
self.lua.release(self.reference)
}
/// Access a field within the `Table`
///
/// - Precondition: `key` cannot be `Nil`
public subscript(key: Value) -> Value {
get {
precondition(!(key is Nil))
self.lua.push(value: self)
self.lua.push(value: key)
self.lua.raw.getTable(atIndex: SecondIndex)
defer { self.lua.raw.pop(1) }
return self.lua.pop()
}
set {
precondition(!(key is Nil))
self.lua.push(value: self)
self.lua.push(value: key)
self.lua.push(value: newValue)
self.lua.raw.setTable(atIndex: ThirdIndex)
self.lua.raw.pop(1)
}
}
/// Calls the given closure on each key-value pair in the table
public func forEach(body: (TableKey, Value) -> Void) {
self.lua.push(value: self)
self.lua.raw.pushNil()
while self.lua.raw.next(atIndex: SecondIndex) {
let value = self.lua.pop()
let key = self.lua.get(atIndex: TopIndex)
body(TableKey(key), value)
}
}
/// Uses `self.forEach` to construct a `[TableKey : Value]` and returns it
public func toDictionary() -> [TableKey : Value] {
var dict = [TableKey : Value]()
self.forEach { (key, value) in dict[key] = value }
return dict
}
/// Perform equality between two `Table`s
///
/// - Parameter rhs: The `Table` to compare to
///
/// - Returns: `true` if the `Table`s are the same object
fileprivate func isEqual(to other: Table) -> Bool {
self.lua.push(value: self)
self.lua.push(value: other)
defer { self.lua.raw.pop(2) }
return self.lua.raw.compare(index1: TopIndex, index2: SecondIndex,
comparator: .Equal)
}
}
extension Table: Equatable {}
public func ==(lhs: Table, rhs: Table) -> Bool {
return lhs.isEqual(to: rhs)
}
| lgpl-3.0 | ce439753f02795ee3337a9b1a034c0be | 24.13253 | 75 | 0.652445 | 3.023188 | false | false | false | false |
HakkiYigitYener/HurriyetApiSDKSwift | HurriyetApiSDKSwift/Classes/Models/HAPath.swift | 1 | 610 | //
// HAPath.swift
// HurriyetApiSwiftSDK
//
// Created by Hakkı Yiğit Yener on 17.12.2016.
// Copyright © 2016 Hurriyet. All rights reserved.
//
import UIKit
class HAPath: NSObject {
//Dizin id'sini temsil eder.
public var Id:String? = ""
//Dizini temsil eder.
public var Path:String? = ""
//Dizin başlığını temsil eder.
public var Title:String? = ""
init(dictionary: Dictionary<String, Any>) {
super.init()
Id = dictionary["Id"] as! String?;
Path = dictionary["Path"] as! String?
Title = dictionary["Title"] as! String?
}
}
| mit | caa08e8370e6b6bbd0e58d8ec33ce0ca | 22.153846 | 51 | 0.609635 | 3.151832 | false | false | false | false |
Zeacone/FXSVG | src/SVGElement.swift | 1 | 3796 | //
// SVGElement.swift
// iPet
//
// Created by mac on 2017/10/26.
// Copyright © 2017年 zeacone. All rights reserved.
//
import UIKit
struct Stack<T> {
var items = [T]()
mutating func pop() -> T {
return items.removeLast()
}
mutating func push(_ item: T) {
items.append(item)
}
func top() -> T? {
return items.last
}
}
class SVGElement: NSObject {
// Element's parent
var parent: SVGElement?
// Element's children
var children = [SVGElement]()
// Element's name
var name: String!
var attr: [String: String]!
/// Element's id to find this element easily.
var id: String?
var clipPath: String?
var filter: String?
var fillRule: String?
var transform: CGAffineTransform?
/// Element's title. If this property is not nil, then we should show a text element on it.
var title: String?
/// A bezier path to draw element.
lazy var path: UIBezierPath = UIBezierPath()
/// Stroke color
var strokeColor: UIColor?
/// Fill color
var fillColor: UIColor?
/// A property to decide if this element is selectable.
var clickable: Bool = false
/// A transform string to generate real transform.
var transformString: String? {
get {
return nil
}
set {
if let value = newValue {
let transform = SVGTransformParser.transfrom(value)
self.path.apply(transform)
}
}
}
/// I don't know how this works.
var className: String?
/// Initializer
///
/// - Parameter attr: Some properties.
required init(name: String, attr: [String: String]) {
super.init()
self.name = name
self.readProperty(attr)
self.draw(attr: attr)
}
/// Read some public properties from attribute collections.
///
/// - Parameter attr: Some properties.
func readProperty(_ attr: [String: String]) {
self.title = attr["title"]
self.id = attr["id"]
self.strokeColor = self.hexColorString(attr["stroke"])
self.fillColor = self.hexColorString(attr["fill"])
self.transformString = attr["transform"]
self.className = attr["class"]
self.filter = attr["filter"]
self.clipPath = attr["clip-path"]
}
/// Convert hex string to UIColor.
///
/// - Parameter hex: A hex string.
/// - Returns: Destination color.
func hexColorString(_ hex: String?) -> UIColor {
guard var string = hex else { return UIColor.clear }
if string.hasPrefix("#") {
string.removeFirst(1)
}
if string.hasPrefix("0x") {
string.removeFirst(2)
}
let scanner = Scanner(string: string)
var hexColor: UInt32 = 0
if scanner.scanHexInt32(&hexColor) {
return self.hexColor(Int(hexColor))
}
return UIColor.clear
}
/// Parse color from a hex integer.
///
/// - Parameter hex: A hex integer.
/// - Returns: Destination color.
func hexColor(_ hex: Int) -> UIColor {
let red = CGFloat(hex >> 16 & 0xFF) / 255.0
let green = CGFloat(hex >> 8 & 0xFF) / 255.0
let blue = CGFloat(hex & 0xFF) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1)
}
/// Provide a super function but do nothing. It will be implemented by it's subclass.
///
/// - Parameter attr: Some properties.
func draw(attr: [String: String]) {
}
}
| gpl-3.0 | def530ad3bd7e629d9a5478378a7b000 | 22.269939 | 95 | 0.540733 | 4.462353 | false | false | false | false |
torinmb/Routinely | Routinely/TaskTableViewController.swift | 1 | 6918 | //
// TaskTableViewController.swift
// Routinely
//
// Created by Torin Blankensmith on 4/7/15.
// Copyright (c) 2015 Torin Blankensmith. All rights reserved.
import UIKit
class TaskTableViewController: RoutineTableViewController {
var tasks : [String]
required init(coder aDecoder: NSCoder) {
tasks = [String]()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(navigationController?.navigationBarHidden == false, animated: false)
self.tableView.backgroundColor = UIColor(white: 0, alpha: 1)
let pinch = UIPinchGestureRecognizer(target: self, action: "handlePinch:")
self.tableView.addGestureRecognizer(pinch)
// 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 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return tasks.count + 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("start", forIndexPath: indexPath) as! UITableViewCell
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
cell.textLabel?.backgroundColor = UIColor.clearColor()
cell.delegate = self
cell.routineItem = Routine(text: tasks[indexPath.row - 1])
return cell
}
// Configure the cell...
}
// MARK: - pinch methods
struct TouchPoints {
var upper: CGPoint
var lower: CGPoint
}
// the indices of the upper and lower cells that are being pinched
var upperCellIndex = -100
var lowerCellIndex = -100
// the location of the touch points when the pinch began
var initialTouchPoints: TouchPoints!
// indicates that the pinch was big enough to cause a new item to be added
var pinchExceededRequiredDistance = false
var pinchInProgress = false
func handlePinch(recognizer: UIPinchGestureRecognizer) {
switch recognizer.state {
case .Began:
performSegueWithIdentifier("unwindSegue", sender: self)
// pinchStarted(recognizer)
case .Changed :
if pinchInProgress && recognizer.numberOfTouches() == 2 {
pinchChanged(recognizer)
}
case .Ended:
pinchEnded(recognizer)
default:
break
}
}
func pinchStarted(recognizer: UIPinchGestureRecognizer) {
}
func pinchChanged(recognizer: UIPinchGestureRecognizer) {
}
func pinchEnded(recognizer: UIPinchGestureRecognizer) {
}
// returns the two touch points, ordering them to ensure that
// upper and lower are correctly identified.
func getNormalizedTouchPoints(recognizer: UIGestureRecognizer) -> TouchPoints {
var pointOne = recognizer.locationOfTouch(0, inView: tableView)
var pointTwo = recognizer.locationOfTouch(1, inView: tableView)
// ensure pointOne is the top-most
if pointOne.y > pointTwo.y {
let temp = pointOne
pointOne = pointTwo
pointTwo = temp
}
return TouchPoints(upper: pointOne, lower: pointTwo)
}
func viewContainsPoint(view: UIView, point: CGPoint) -> Bool {
let frame = view.frame
return (frame.origin.y < point.y) && (frame.origin.y + (frame.size.height) > point.y)
}
// override func cellDidBeginEditing(editingCell: TableViewCell) {
// cellSaveState = editingCell.label.text
// }
// override func cellDidEndEditing(editingCell: TableViewCell) {
// if editingCell.label.text != cellSaveState {
// let index = find(tasks, cellSaveState)
//// routineItems[index!] = editingCell.label.text
// }
// }
/*
// 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?) {
if segue.identifier == "presentCardViewSegue" {
let view = segue.destinationViewController as! CardViewController
NSLog(navigationItem.title!)
view.groupTitle = navigationItem.title!
NSLog(tasks.count.description)
view.tasks = self.tasks
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
}
}
| mit | b4d9bb30e66947b98240148ee6d7b3b4 | 35.219895 | 157 | 0.656982 | 5.354489 | false | false | false | false |
antlr/antlr4 | runtime/Swift/Sources/Antlr4/atn/SingletonPredictionContext.swift | 4 | 2190 | ///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
public class SingletonPredictionContext: PredictionContext {
public final let parent: PredictionContext?
public final let returnState: Int
init(_ parent: PredictionContext?, _ returnState: Int) {
//TODO assert
//assert ( returnState=ATNState.INVALID_STATE_NUMBER,"Expected: returnState!/=ATNState.INVALID_STATE_NUMBER");
self.parent = parent
self.returnState = returnState
super.init(parent.map { PredictionContext.calculateHashCode($0, returnState) } ?? PredictionContext.calculateEmptyHashCode())
}
public static func create(_ parent: PredictionContext?, _ returnState: Int) -> SingletonPredictionContext {
if returnState == PredictionContext.EMPTY_RETURN_STATE && parent == nil {
// someone can pass in the bits of an array ctx that mean $
return EmptyPredictionContext.Instance
}
return SingletonPredictionContext(parent, returnState)
}
override
public func size() -> Int {
return 1
}
override
public func getParent(_ index: Int) -> PredictionContext? {
assert(index == 0, "Expected: index==0")
return parent
}
override
public func getReturnState(_ index: Int) -> Int {
assert(index == 0, "Expected: index==0")
return returnState
}
override
public var description: String {
let up = parent?.description ?? ""
if up.isEmpty {
if returnState == PredictionContext.EMPTY_RETURN_STATE {
return "$"
}
return String(returnState)
}
return String(returnState) + " " + up
}
}
public func ==(lhs: SingletonPredictionContext, rhs: SingletonPredictionContext) -> Bool {
if lhs === rhs {
return true
}
if lhs.hashValue != rhs.hashValue {
return false
}
if lhs.returnState != rhs.returnState {
return false
}
return lhs.parent == rhs.parent
}
| bsd-3-clause | 06cafd61ea9fbb97ad854a814fccf3af | 27.076923 | 133 | 0.63105 | 4.921348 | false | false | false | false |
Mogendas/apiproject | apiproject/SettingsVC.swift | 1 | 4109 | //
// SettingsVC.swift
// apiproject
//
// Created by Johan Wejdenstolpe on 2017-05-15.
// Copyright © 2017 Johan Wejdenstolpe. All rights reserved.
//
import UIKit
class SettingsVC: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
let searchResults = (1...10).map { $0 * 5 }
let searchRadius = (5...20).map { $0 * 100 }
let moveRadius = (1...10).map { $0 * 50 }
let userSettings = UserDefaults()
var pickerArray: [Int] = [Int]()
var selectedRow: Int = 0
@IBOutlet weak var settingsPickerView: UIPickerView!
@IBOutlet weak var lblSearchResult: UILabel!
@IBOutlet weak var lblSearchRadius: UILabel!
@IBOutlet weak var lblMoveRadius: UILabel!
@IBOutlet weak var pickerLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
settingsPickerView.delegate = self
settingsPickerView.dataSource = self
if let results = userSettings.string(forKey: "SearchResult") {
lblSearchResult.text = "\(results) st"
}
if let radius = userSettings.string(forKey: "SearchRadius") {
lblSearchRadius.text = "\(radius) m"
}
if let radiusMove = userSettings.string(forKey: "MoveRadius") {
lblMoveRadius.text = "\(radiusMove) m"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func searchResultTapped(_ sender: UITapGestureRecognizer) {
pickerArray = searchResults
if let results = Int(userSettings.string(forKey: "SearchResult")!) {
if let row = pickerArray.index(of: results) {
selectedRow = row
}
}
pickerLabel.text = "Välj antal sökresultat"
showPickerView()
}
@IBAction func viewTap(_ sender: UITapGestureRecognizer) {
settingsPickerView.isHidden = true
pickerLabel.isHidden = true
}
@IBAction func searchRadiusTapped(_ sender: UITapGestureRecognizer) {
pickerArray = searchRadius
if let radius = Int(userSettings.string(forKey: "SearchRadius")!) {
if let row = pickerArray.index(of: radius) {
selectedRow = row
}
}
pickerLabel.text = "Välj sökradie"
showPickerView()
}
@IBAction func moveRadiusTapped(_ sender: UITapGestureRecognizer) {
pickerArray = moveRadius
if let radiusMove = Int(userSettings.string(forKey: "MoveRadius")!) {
if let row = pickerArray.index(of: radiusMove) {
selectedRow = row
}
}
pickerLabel.text = "Välj uppdateringsradie"
showPickerView()
}
func showPickerView(){
settingsPickerView.reloadAllComponents()
settingsPickerView.selectRow(selectedRow, inComponent: 0, animated: true)
pickerLabel.isHidden = false
settingsPickerView.isHidden = false
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerArray.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return "\(pickerArray[row])"
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerArray.last == 50{
lblSearchResult.text = "\(pickerArray[row]) st"
userSettings.setValue("\(pickerArray[row])", forKey: "SearchResult")
}
if pickerArray.last == 2000{
lblSearchRadius.text = "\(pickerArray[row]) m"
userSettings.setValue("\(pickerArray[row])", forKey: "SearchRadius")
}
if pickerArray.last == 500{
lblMoveRadius.text = "\(pickerArray[row]) m"
userSettings.setValue("\(pickerArray[row])", forKey: "MoveRadius")
}
}
}
| gpl-3.0 | c370aa99fe4e9bfd9b6b0f95a62a5212 | 33.191667 | 111 | 0.618816 | 4.93149 | false | false | false | false |
terflogag/BadgeSegmentControl | Example/Exemple/ViewController.swift | 1 | 8367 | //
// ViewController.swift
// Exemple
//
// Created by Florian Gabach on 22/08/2017.
// Copyright © 2017 Florian Gabach. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK : - IBOutlet
@IBOutlet weak var segmentView: BadgeSegmentControl!
@IBOutlet weak var simpleSegmentView: BadgeSegmentControl!
@IBOutlet weak var imageSegmentView: BadgeSegmentControl!
@IBOutlet weak var simpleSegmentViewWithBar: BadgeSegmentControl!
// MARK: - Var
fileprivate let mainColor = UIColor(red:1.00, green:0.62, blue:0.22, alpha:1.00)
fileprivate var firstBadgeValue: Int = 0
fileprivate var secondBadgeValue: Int = 0
fileprivate var programaticallySegmentedControl: BadgeSegmentControl?
fileprivate let firstSegmentName = "Emojiraf"
fileprivate let secondSegmentName = "Messages"
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Background color
self.view.backgroundColor = self.mainColor
// Prepare two segment for demo
self.prepareTextAndImageSegment()
self.prepareSimpleSegment()
self.prepareOnlyImageSegment()
self.addWithoutStoryboard()
self.prepareSegmentWithBar()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Prepare segment
/// Prepare the first segment without image and badge
func prepareSimpleSegment() {
self.simpleSegmentView.segmentAppearance = SegmentControlAppearance.appearance()
// Add segments
self.simpleSegmentView.addSegmentWithTitle(self.firstSegmentName)
self.simpleSegmentView.addSegmentWithTitle(self.secondSegmentName)
self.simpleSegmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.simpleSegmentView.selectedSegmentIndex = 0
}
/// Prepare the second segment with image and badge
func prepareTextAndImageSegment() {
self.segmentView.segmentAppearance = SegmentControlAppearance.appearance()
// Add segments
self.segmentView.addSegmentWithTitle(self.firstSegmentName,
onSelectionImage: UIImage(named: "emoji")?.imageWithColor(self.mainColor),
offSelectionImage: UIImage(named: "emoji")?.imageWithColor(UIColor.white))
self.segmentView.addSegmentWithTitle(self.secondSegmentName,
onSelectionImage: UIImage(named: "message")?.imageWithColor(self.mainColor),
offSelectionImage: UIImage(named: "message")?.imageWithColor(UIColor.white))
self.segmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.segmentView.selectedSegmentIndex = 0
}
/// Prepare the second segment with image and badge
func prepareOnlyImageSegment() {
self.imageSegmentView.segmentAppearance = SegmentControlAppearance.appearance()
// Add segments
self.imageSegmentView.addSegmentWithTitle("",
onSelectionImage: UIImage(named: "emoji")?.imageWithColor(self.mainColor),
offSelectionImage: UIImage(named: "emoji")?.imageWithColor(UIColor.white))
self.imageSegmentView.addSegmentWithTitle("",
onSelectionImage: UIImage(named: "message")?.imageWithColor(self.mainColor),
offSelectionImage: UIImage(named: "message")?.imageWithColor(UIColor.white))
self.imageSegmentView.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.imageSegmentView.selectedSegmentIndex = 0
}
/// Prepare the segment with bar
func prepareSegmentWithBar() {
self.simpleSegmentViewWithBar.segmentAppearance = SegmentControlBarAppearence.appearance()
// Add segments
self.simpleSegmentViewWithBar.addSegmentWithTitle("",
onSelectionImage: UIImage(named: "emoji")?.imageWithColor(UIColor.white),
offSelectionImage: UIImage(named: "emoji")?.imageWithColor(UIColor.white.withAlphaComponent(0.3)))
self.simpleSegmentViewWithBar.addSegmentWithTitle("",
onSelectionImage: UIImage(named: "message")?.imageWithColor(UIColor.white),
offSelectionImage: UIImage(named: "message")?.imageWithColor(UIColor.white.withAlphaComponent(0.3)))
self.simpleSegmentViewWithBar.addTarget(self, action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.simpleSegmentViewWithBar.selectedSegmentIndex = 0
}
func addWithoutStoryboard() {
let padding: CGFloat = 50
self.programaticallySegmentedControl = BadgeSegmentControl(frame: CGRect(x: padding / 2,
y: self.view.frame.height - (padding * 2),
width: self.view.frame.width - padding,
height: padding))
self.programaticallySegmentedControl?.segmentAppearance = SegmentControlAppearance.appearance()
// Add segments
self.programaticallySegmentedControl?.addSegmentWithTitle("First")
self.programaticallySegmentedControl?.addSegmentWithTitle("Second")
self.programaticallySegmentedControl?.addTarget(self,
action: #selector(selectSegmentInSegmentView(segmentView:)),
for: .valueChanged)
// Set segment with index 0 as selected by default
self.programaticallySegmentedControl?.selectedSegmentIndex = 0
// Add to subview
if let segmentControl = self.programaticallySegmentedControl {
self.view.addSubview(segmentControl)
}
}
// MARK: - Action
@IBAction func doUpdateFirstBadgeClick(_ sender: Any) {
self.firstBadgeValue += 1
self.segmentView.updateBadge(forValue: self.firstBadgeValue,
andSection: 0)
self.imageSegmentView.updateBadge(forValue: self.firstBadgeValue,
andSection: 0)
self.simpleSegmentView.updateBadge(forValue: self.firstBadgeValue,
andSection: 0)
}
@IBAction func doUpdateSecondBadgeClick(_ sender: Any) {
self.secondBadgeValue += 1
self.segmentView.updateBadge(forValue: self.secondBadgeValue,
andSection: 1)
self.imageSegmentView.updateBadge(forValue: self.secondBadgeValue,
andSection: 1)
self.simpleSegmentView.updateBadge(forValue: self.secondBadgeValue,
andSection: 1)
}
// Segment selector for .ValueChanged
@objc func selectSegmentInSegmentView(segmentView: BadgeSegmentControl) {
print("Select segment at index: \(segmentView.selectedSegmentIndex)")
}
}
| mit | 6336e3560e8c9da09537e09811b4d1c8 | 43.5 | 158 | 0.586541 | 6.644956 | false | false | false | false |
mitchellporter/Cheetah | Cheetah/CheetahLayerProperties.swift | 1 | 3261 | //
// CheetahLayerProperties.swift
// Cheetah
//
// Created by Suguru Namura on 2015/08/20.
// Copyright © 2015年 Suguru Namura.
//
import UIKit
class CheetahLayerPositionProperty: CheetahCGPointProperty {
init(view: UIView!, position: CGPoint, relative: Bool = false) {
super.init()
self.view = view
self.relative = relative
to = position
}
override func prepare() {
super.prepare()
from = view.layer.position
}
override func update() {
view.layer.position = calculateCGPoint(from: from, to: toCalc)
}
}
class CheetahLayerRotationProperty: CheetahCGFloatProperty {
var last: CGFloat = 0
init(view: UIView!, rotation: CGFloat, relative: Bool = false) {
super.init()
self.view = view
self.relative = relative
to = rotation
}
override func prepare() {
super.prepare()
from = atan2(view.layer.transform.m12, view.layer.transform.m11)
}
override func update() {
let curr = calculateCGFloat(from: from, to: toCalc)
transform = CATransform3DMakeRotation(curr, 0, 0, 1)
}
}
class CheetahLayerScaleProperty: CheetahCGPointProperty {
var last: CGPoint = CGPointZero
init(view: UIView!, scale: CGPoint) {
super.init()
self.view = view
to = scale
}
override func prepare() {
super.prepare()
let t = view.layer.transform
from.x = sqrt((t.m11 * t.m11) + (t.m12 * t.m12) + (t.m13 * t.m13))
from.y = sqrt((t.m21 * t.m21) + (t.m22 * t.m22) + (t.m23 * t.m23))
}
override func update() {
let curr = calculateCGPoint(from: from, to: toCalc)
transform = CATransform3DMakeScale(curr.x, curr.y, 1)
}
}
class CheetahLayerBorderWidthProperty: CheetahCGFloatProperty {
init(view: UIView!, borderWidth: CGFloat) {
super.init()
self.view = view
to = borderWidth
}
override func prepare() {
super.prepare()
from = view.layer.borderWidth
}
override func update() {
view.layer.borderWidth = calculateCGFloat(from: from, to: toCalc)
}
}
class CheetahLayerCornerRadiusProperty: CheetahCGFloatProperty {
init(view: UIView!, cornerRadius: CGFloat) {
super.init()
self.view = view
to = cornerRadius
}
override func prepare() {
super.prepare()
from = view.layer.cornerRadius
}
override func update() {
view.layer.cornerRadius = calculateCGFloat(from: from, to: toCalc)
}
}
class CheetahLayerBorderColorProperty: CheetahUIColorProperty {
init(view: UIView!, borderColor: UIColor) {
super.init()
self.view = view
self.to = borderColor
}
override func prepare() {
super.prepare()
if let borderColor = view.layer.borderColor {
from = UIColor(CGColor: borderColor)
} else {
from = UIColor.blackColor()
}
}
override func update() {
let color = calculateUIColor(from: from, to: toCalc)
view.layer.borderColor = color.CGColor
}
}
| mit | 9a5f45388f069c8b77e0e2ebdd4dc5a6 | 22.608696 | 74 | 0.586556 | 4.155612 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/Models/UserGuideViewController.swift | 1 | 3061 | //
// UserGuideViewController.swift
// WePeiYang
//
// Created by Allen X on 4/29/16.
// Copyright © 2016 Qin Yubo. All rights reserved.
//
import UIKit
import SnapKit
let NOTIFICATION_GUIDE_DISMISSED = "NOTIFICATION_GUIDE_DISMISSED"
class UserGuideViewController: UIViewController {
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var startButton: UIButton!
private var scrollView: UIScrollView!
private let numberOfPages = 4
override func viewDidLoad() {
super.viewDidLoad()
let frame = self.view.bounds
scrollView = UIScrollView(frame: frame)
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
scrollView.contentOffset = CGPointZero
scrollView.contentSize = CGSize(width: frame.size.width * CGFloat(numberOfPages), height: frame.size.height)
scrollView.delegate = self
for page in 0 ..< numberOfPages {
var imageView = UIImageView()
imageView = UIImageView(image: UIImage(named: "guide\(page + 1)"))
imageView.frame = CGRect(x: frame.size.width * CGFloat(page), y: 0, width: frame.size.width, height: frame.size.height)
scrollView.addSubview(imageView)
}
self.view.insertSubview(scrollView, atIndex: 0)
startButton.layer.cornerRadius = 2.0
startButton.alpha = 0.0
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func shouldAutorotate() -> Bool {
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func dismissSelf() {
self.dismissViewControllerAnimated(true, completion: {
NSNotificationCenter.defaultCenter().postNotificationName(NOTIFICATION_GUIDE_DISMISSED, object: nil)
})
}
/*
// 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: - UIScrollViewDelegate
extension UserGuideViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
let offset = scrollView.contentOffset
pageControl.currentPage = Int(offset.x / view.bounds.width)
if pageControl.currentPage == numberOfPages - 1 {
UIView.animateWithDuration(0.5) {
self.startButton.alpha = 1.0
}
} else {
UIView.animateWithDuration(0.2) {
self.startButton.alpha = 0.0
}
}
}
}
| mit | b3f9bb39c51b7f0cfc81b18124f30c99 | 30.546392 | 131 | 0.652941 | 5.142857 | false | false | false | false |
brentdax/swift | test/IDE/complete_multiple_files.swift | 30 | 2065 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=T1 \
// RUN: %S/Inputs/multiple-files-1.swift %S/Inputs/multiple-files-2.swift | %FileCheck %s -check-prefix=T1
//
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=T2 \
// RUN: %S/Inputs/multiple-files-1.swift %S/Inputs/multiple-files-2.swift | %FileCheck %s -check-prefix=T2
//
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TOP_LEVEL_1 \
// RUN: %S/Inputs/multiple-files-1.swift %S/Inputs/multiple-files-2.swift | %FileCheck %s -check-prefix=TOP_LEVEL_1
//
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=MODULE_SCOPED %S/Inputs/multiple-files-1.swift %S/Inputs/multiple-files-2.swift | %FileCheck %s -check-prefix=MODULE_SCOPED
func testObjectExpr() {
fooObject.#^T1^#
}
// T1: Begin completions
// T1-NEXT: Keyword[self]/CurrNominal: self[#FooStruct#]; name=self
// T1-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// T1-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}}
// T1-NEXT: End completions
func testGenericObjectExpr() {
genericFooObject.#^T2^#
}
// T2: Begin completions
// T2-NEXT: Keyword[self]/CurrNominal: self[#GenericFooStruct<Void>#]; name=self
// T2-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// T2-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}}
// T2-NEXT: End completions
func topLevel1() {
#^TOP_LEVEL_1^#
}
// TOP_LEVEL_1: Begin completions
// TOP_LEVEL_1-NOT: ERROR
// TOP_LEVEL_1: Literal[Boolean]/None: true[#Bool#]{{; name=.+$}}
// TOP_LEVEL_1-NOT: true
// TOP_LEVEL_1-NOT: ERROR
// TOP_LEVEL_1: End completions
func moduleScoped() {
swift_ide_test.#^MODULE_SCOPED^#
}
// MODULE_SCOPED: Begin completions
// MODULE_SCOPED-NOT: ERROR
// MODULE_SCOPED: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// MODULE_SCOPED-NOT: ERROR
// MODULE_SCOPED: End completions
| apache-2.0 | 096e2219ab974bc563df0aa85d48b22a | 42.93617 | 214 | 0.698789 | 3.181818 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | SnapshotTestsHostApp/SceneDelegate.swift | 1 | 2676 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import SwiftUI
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| lgpl-3.0 | 099f31f8d20de551521d12098c639d30 | 48.537037 | 147 | 0.708037 | 5.492813 | false | false | false | false |
AdaptiveMe/adaptive-arp-darwin | adaptive-arp-rt/Source/Sources.Common/Core/ServiceHandler.swift | 1 | 4478 | /*
* =| ADAPTIVE RUNTIME PLATFORM |=======================================================================================
*
* (C) Copyright 2013-2014 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
*
* 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.
*
* Original author:
*
* * Carlos Lozano Diez
* <http://github.com/carloslozano>
* <http://twitter.com/adaptivecoder>
* <mailto:[email protected]>
*
* Contributors:
*
* * Ferran Vila Conesa
* <http://github.com/fnva>
* <http://twitter.com/ferran_vila>
* <mailto:[email protected]>
*
* =====================================================================================================================
*/
import Foundation
import AdaptiveArpApi
public class ServiceHandler:NSObject {
/// Logging variable
let logger:ILogging = AppRegistryBridge.sharedInstance.getLoggingBridge()
let loggerTag:String = "ServiceHandler"
/// Singleton instance
public class var sharedInstance : ServiceHandler {
struct Static {
static let instance : ServiceHandler = ServiceHandler()
}
return Static.instance
}
/// Constructor
public override init() {
}
/// Method that executes the method with the parameters from the APIRequest object send it by the Typescript. This method could return some data in the syncronous methods or execute some callback/listeners in the asyncronous ones
/// :param: apiRequest API Request object
/// :return: Data for returning the syncronous responses
public func handleServiceUrl(apiRequest:APIRequest) -> APIResponse {
if let bridgeType:String = apiRequest.getBridgeType() {
// Get the bridge
if let bridge:APIBridge = AppRegistryBridge.sharedInstance.getBridge(bridgeType) {
//logger.log(ILoggingLogLevel.Info, category: loggerTag, message: "ASYNC ID: \(apiRequest.getAsyncId())")
if apiRequest.getAsyncId() != -1 {
// let asyncId:Int64? = apiRequest.getAsyncId()
// async methods (executed in a background queue)
dispatch_async(GCD.backgroundQueue(), {
bridge.invoke(apiRequest)
/*if let result:APIResponse = bridge.invoke(apiRequest) {
} else {
self.logger.log(ILoggingLogLevel.Error, category: self.loggerTag, message: "There is an error executing the asyncronous method: \(apiRequest.getMethodName())")
}*/
})
} else {
// sync methods (executed in the main queue)
if let result:APIResponse = bridge.invoke(apiRequest) {
//logger.log(ILoggingLogLevel.Info, category: loggerTag, message: "SYNC SERVICE RESULT: \(result)")
return result
} else {
self.logger.log(ILoggingLogLevel.Error, category: self.loggerTag, message: "There is an error executing the syncronous method: \(apiRequest.getMethodName())")
}
}
} else {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "There is no bridge with the identifier: \(bridgeType)")
}
} else {
logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "There is no bridge type inside the API Request object")
}
// Asynchronous responses
return APIResponse(response: "", statusCode: 200, statusMessage: "Please see native platform log for details.")
}
}
| apache-2.0 | 190db6fad3260690ce88c29b59b31f13 | 42.475728 | 233 | 0.560295 | 5.408213 | false | false | false | false |
zdima/ZDMatrixPopover | ZDMatrixPopover/ViewController.swift | 1 | 1626 | //
// ViewController.swift
// ZDMatrixPopover
//
// Created by Dmitriy Zakharkin on 1/7/17.
// Copyright © 2017 Dmitriy Zakharkin. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, ZDMatrixPopoverDelegate {
@IBOutlet var popover: ZDMatrixPopover!
@IBAction func clickMe(_ sender: Any) {
guard let button = sender as? NSView else {return}
if popover == nil {
popover = ZDMatrixPopover()
}
if popover!.isShown {
do { try popover!.close() } catch { print("exception:\(error)") }
return
}
let rightAlign: NSMutableParagraphStyle = NSMutableParagraphStyle()
rightAlign.alignment = .right
do {
try popover!.show(data: [
["1", "2 aa", "3", "x"],
["4 aaa", "5", NSAttributedString(string: "6", attributes: [
NSForegroundColorAttributeName: NSColor.red,
NSParagraphStyleAttributeName: rightAlign
]), "x"],
["7", "8", "9 a", "NSParagraphStyleAttributeName"]
], title: "Test popover with long title",
relativeTo: button.frame, of: button.superview!, preferredEdge: .maxY)
} catch { print("exception:\(error)") }
}
func getColumnFormatter(column: Int) -> Formatter? {
return nil
}
func getColumnAlignment(column: Int) -> NSTextAlignment {
if column == 2 {
return .right
}
return .left
}
func getColumnWidth(column: Int) -> Int {
return -1
}
}
| mit | 33bcf71b338147a54920556082c3ebab | 27.017241 | 89 | 0.558769 | 4.79351 | false | false | false | false |
filom/ASN1Decoder | ASN1DecoderTests/ASN1DecoderExtensions.swift | 1 | 11107 | //
// ASN1DecoderExtensions.swift
// ASN1DecoderTests
//
// Copyright © 2020 Filippo Maguolo.
//
// 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 XCTest
@testable import ASN1Decoder
class ASN1DecoderX509Extensions: XCTestCase {
func getCertificate() throws -> X509Certificate {
let certificateData = samplePEMcertificate.data(using: .utf8)!
return try X509Certificate(data: certificateData)
}
func testAuthorityKeyIdentifier() {
do {
let x509 = try getCertificate()
if let ext = x509.extensionObject(oid: .authorityKeyIdentifier) as? X509Certificate.AuthorityKeyIdentifierExtension {
XCTAssertEqual(ext.keyIdentifier?.hexEncodedString(), "76028647F1F6A396C9BFD22D8E300E28398C588B")
XCTAssertEqual(ext.serialNumber?.hexEncodedString(), "5FA31045")
let certificateIssuer = ext.certificateIssuer
XCTAssertTrue(certificateIssuer?.contains("www.hostname.net") == true)
XCTAssertTrue(certificateIssuer?.contains("192.168.1.99") == true)
XCTAssertTrue(certificateIssuer?.contains("CN=EXTENSION TEST") == true)
}
} catch {
XCTFail("\(error)")
}
}
func testBasicConstraint() {
do {
let x509 = try getCertificate()
if let ext = x509.extensionObject(oid: .basicConstraints) as? X509Certificate.BasicConstraintExtension {
XCTAssertEqual(ext.isCA, true)
XCTAssertEqual(ext.pathLenConstraint, 3)
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
func testExtKeyUsage() {
do {
let x509 = try getCertificate()
let extKeyUsage = x509.extendedKeyUsage
XCTAssert(extKeyUsage.contains("1.3.6.1.5.5.7.3.2")) // TLS Web Client Authentication
XCTAssert(extKeyUsage.contains("1.3.6.1.5.5.7.3.4")) // E-mail Protection
XCTAssert(extKeyUsage.contains("1.3.6.1.4.1.311.10.3.4")) // Encrypted File System
} catch {
XCTFail("\(error)")
}
}
func testSubjectKeyIdentifier() {
do {
let x509 = try getCertificate()
if let ext = x509.extensionObject(oid: .subjectKeyIdentifier), let value = ext.value as? Data {
XCTAssertEqual(value.hexEncodedString(), "76028647F1F6A396C9BFD22D8E300E28398C588B")
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
func testCertificatePolicies() {
do {
let certificateData = samplePEMcertificateApple.data(using: .utf8)!
let x509 = try X509Certificate(data: certificateData)
if let ext = x509.extensionObject(oid: .certificatePolicies) as? X509Certificate.CertificatePoliciesExtension,
let policies = ext.policies {
XCTAssertEqual(policies[0].oid, "2.16.840.1.114412.2.1")
XCTAssertEqual(policies[0].qualifiers?[0].oid, "1.3.6.1.5.5.7.2.1")
XCTAssertEqual(policies[0].qualifiers?[0].value, "https://www.digicert.com/CPS")
XCTAssertEqual(policies[1].oid, "2.23.140.1.1")
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
func testCertificateCRL() {
do {
let certificateData = samplePEMcertificateApple.data(using: .utf8)!
let x509 = try X509Certificate(data: certificateData)
if let ext = x509.extensionObject(oid: .cRLDistributionPoints) as? X509Certificate.CRLDistributionPointsExtension,
let crls = ext.crls {
XCTAssertTrue(crls.contains("http://crl3.digicert.com/DigiCertSHA2ExtendedValidationServerCA-3.crl"))
XCTAssertTrue(crls.contains("http://crl4.digicert.com/DigiCertSHA2ExtendedValidationServerCA-3.crl"))
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
func testAuthorityInfoAccess() {
do {
let certificateData = samplePEMcertificateApple.data(using: .utf8)!
let x509 = try X509Certificate(data: certificateData)
if let ext = x509.extensionObject(oid: .authorityInfoAccess) as? X509Certificate.AuthorityInfoAccessExtension,
let infoAccess = ext.infoAccess {
XCTAssertEqual(infoAccess[0].method, "1.3.6.1.5.5.7.48.1")
XCTAssertEqual(infoAccess[0].location, "http://ocsp.digicert.com")
XCTAssertEqual(infoAccess[1].method, "1.3.6.1.5.5.7.48.2")
XCTAssertEqual(infoAccess[1].location, "http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA-3.crt")
} else {
XCTFail("Extension not found")
}
} catch {
XCTFail("\(error)")
}
}
let samplePEMcertificate = """
-----BEGIN CERTIFICATE-----
MIIDejCCAmKgAwIBAgIEX6MQRTANBgkqhkiG9w0BAQsFADAZMRcwFQYDVQQDDA5F
WFRFTlNJT04gVEVTVDAeFw0yMDExMDQyMDM0MTNaFw0yMTExMDQyMDM0MTNaMBkx
FzAVBgNVBAMMDkVYVEVOU0lPTiBURVNUMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEA0Q9U9Qd7ELpyx46zI6tL7UtIGDv48BaDKPO7JkcOyXE2OunO+/Rd
U7nrJP4t7KVoFDYAbzHfy3ViaCN/zzcHUQV5VLtg3ydaM3ruJ8lWZjj1nsH2hPxl
Rth6BttV64mRSUGc4w+OEoj/WMrErCS6uXs0Xjd/1+6h3MUnBua5pwhh59Wj9dCo
8Dn8gcsnFHy/GVMSfwSdSxWpuMfyPNfzQ4jffoneZv/xYpeYqFYdqs5cODqPsfqr
t8+T8Xh30pbDAVwQ0t7EMb+IH5oXIkujEDx+FViyqya/H+E5IXuMecFshD4Rebp5
f/9eE9Ct7BbfEeBOglzyYxB118+CswtcIwIDAQABo4HJMIHGMA8GA1UdEwQIMAYB
Af8CAQMwXAYDVR0jBFUwU4AUdgKGR/H2o5bJv9ItjjAOKDmMWIuhNaQbMBkxFzAV
BgNVBAMMDkVYVEVOU0lPTiBURVNUghB3d3cuaG9zdG5hbWUubmV0hwTAqAFjggRf
oxBFMB0GA1UdDgQWBBR2AoZH8fajlsm/0i2OMA4oOYxYizApBgNVHSUEIjAgBggr
BgEFBQcDAgYIKwYBBQUHAwQGCisGAQQBgjcKAwQwCwYDVR0PBAQDAgEGMA0GCSqG
SIb3DQEBCwUAA4IBAQBBVNtPF++n2KnL3sdezfx0BN1Thzz/k2D/amUnNcMNrUUj
T4k0Nu6ZQZPxnjH8VNAel7eFpRaLOS/zS9B63695lFnOOzJSKec2i0uyl9hRAMf5
HCoowRijyM9KfIHF8UQ2TSBJkL0Dbdhw6Yszq7JcGUj0g4mX/6c9MlsZFRfJ6S6I
mavDHwPsTf6Abz9em4rMF4HVoDpoky/srDh5JsFHZ37uiWtlyUpk87UgNZI+1xA+
3wCZU9yLMOYO7a2j7mLFSJobrN2BZPZYoFjto38XOkPpZxJSUWOPHekig1bH6Nwy
EBbHNd47ucLIF9f7UWBbBxnl1tjp8VVqX6IBsYuS
-----END CERTIFICATE-----
"""
let samplePEMcertificateApple = """
-----BEGIN CERTIFICATE-----
MIIIBTCCBu2gAwIBAgIQA44/ngnX7cexgD90p0w1qzANBgkqhkiG9w0BAQsFADB5
MQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xGTAXBgNVBAsT
EHd3dy5kaWdpY2VydC5jb20xNjA0BgNVBAMTLURpZ2lDZXJ0IFNIQTIgRXh0ZW5k
ZWQgVmFsaWRhdGlvbiBTZXJ2ZXIgQ0EtMzAeFw0yMDEwMDcwMDAwMDBaFw0yMTEw
MDgxMjAwMDBaMIHHMR0wGwYDVQQPDBRQcml2YXRlIE9yZ2FuaXphdGlvbjETMBEG
CysGAQQBgjc8AgEDEwJVUzEbMBkGCysGAQQBgjc8AgECEwpDYWxpZm9ybmlhMREw
DwYDVQQFEwhDMDgwNjU5MjELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3Ju
aWExEjAQBgNVBAcTCUN1cGVydGlubzETMBEGA1UEChMKQXBwbGUgSW5jLjEWMBQG
A1UEAxMNd3d3LmFwcGxlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAMobHCF4FT1Az6N5P53PslOrqUH/PgahKWmKBEae+8QNVnrK5oDnr8bAv4tg
ccqa6HYMBsibd7jzG+p+5zqEy6OIpZMEP2lmd8+uBtHZ4RAIeuAkmOdWlw9zaHtN
aUYoJv8FgQzA2vwhcYFlmjnJ6Wg2NgJfgYC3fopb/jTQznYt2Ys+1BPA7OsPLHet
Hnsg9tqSmP2J86fLUxYusLlivsjDKEDPjFxhd4+SPS8j8gqrZYIiuJjOusgAleRn
NG525dHTLVGRvO/AyN74e8xGRQB22cswMelW/Q5o9Db5G1+IYWKPYKjeQ3tcwRVz
1AYSboWbUJwkv1/89GiVZ9W/RHECAwEAAaOCBDgwggQ0MB8GA1UdIwQYMBaAFM+F
8bw4GHg6VTP0VsrAaa13bruTMB0GA1UdDgQWBBQmH7tn0rlB7VcS548sc00Xi2tw
jjA8BgNVHREENTAzghBpbWFnZXMuYXBwbGUuY29tgg13d3cuYXBwbGUuY29tghB3
d3cuYXBwbGUuY29tLmNuMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEF
BQcDAQYIKwYBBQUHAwIwgaUGA1UdHwSBnTCBmjBLoEmgR4ZFaHR0cDovL2NybDMu
ZGlnaWNlcnQuY29tL0RpZ2lDZXJ0U0hBMkV4dGVuZGVkVmFsaWRhdGlvblNlcnZl
ckNBLTMuY3JsMEugSaBHhkVodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGlnaUNl
cnRTSEEyRXh0ZW5kZWRWYWxpZGF0aW9uU2VydmVyQ0EtMy5jcmwwSwYDVR0gBEQw
QjA3BglghkgBhv1sAgEwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNl
cnQuY29tL0NQUzAHBgVngQwBATCBigYIKwYBBQUHAQEEfjB8MCQGCCsGAQUFBzAB
hhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wVAYIKwYBBQUHMAKGSGh0dHA6Ly9j
YWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFNIQTJFeHRlbmRlZFZhbGlkYXRp
b25TZXJ2ZXJDQS0zLmNydDAJBgNVHRMEAjAAMIIB9gYKKwYBBAHWeQIEAgSCAeYE
ggHiAeAAdwD2XJQv0XcwIhRUGAgwlFaO400TGTO/3wwvIAvMTvFk4wAAAXUE5RIw
AAAEAwBIMEYCIQDfwCPGlYS5Fzl5E9qSJfXEJZKk3Bocy3gRZ3VnSetQ9wIhAJTV
W7NpwxMvgje6f3Bl4pD/8LONvdNOfQhA/RRf/mZgAHUAXNxDkv7mq0VEsV6a1Fbm
EDf71fpH3KFzlLJe5vbHDsoAAAF1BOUShAAABAMARjBEAiBym6EmF1g6CDmqOaKZ
LiOpKJ310wVgWfezVSZoqZCUTQIgbMkp3ZqwIJlxECUiFNCcWvOvXDnRjTmZRNnU
gl9wFj8AdgBWFAaaL9fC7NP14b1Esj7HRna5vJkRXMDvlJhV1onQ3QAAAXUE5RQW
AAAEAwBHMEUCIQDtvAk0Fs6QOodDRWXG8pwviOAD0A3P8MrepljlmvCC+AIgaYPc
dA2gwQbMR+muIHIw6zzpDE2rgBYUmmirGfGXGq8AdgCkuQmQtBhYFIe7E6LMZ3AK
PDWYBPkb37jjd80OyA3cEAAAAXUE5RThAAAEAwBHMEUCIQDVJYiGuX96WaI2ry/P
uChTJsmpiTxPwJItHL0YMJ+HmQIga60LicX5sIxA7jVWLe1skZQvA8SM8dTY9mjf
5qpP9U8wDQYJKoZIhvcNAQELBQADggEBACLAg6hBZGjc2m3vB0YyMlclnv5dQ0vy
F8JfHobkrFQ7O+mW35LiDY/ZIF9KBLGY5eOtHSYX8+Ktt1bcRilwq9Vjip80Atb4
Wpzq9tM6zFx+oxVGv1YsOWdCir94838tP0d0ILqoyqUWVu6HgyJBu3ZEABaSZcIx
4TjJ9LhOtzyO44mcHqgNXiA7IdK3TPs39iAmVx3+3PQmwjbGGjKgR0rORIGUuCa6
YVqR0ad1wWG4M24HgTR/+d40C4JNVY3FFptUvCCw4yD5Jzk2duFsAmC9bZxpTbzc
hoOQIW3CEt8hUquiqBBvOv+7YI3JrMHBsLt9T44YYiKC+XkFnh7yG9E=
-----END CERTIFICATE-----
"""
}
| mit | c45c158265bf333034e5ce2fa823a95d | 47.684211 | 130 | 0.704054 | 2.797379 | false | true | false | false |
googleads/googleads-mobile-ios-examples | Swift/admob/InterstitialExample/InterstitialExample/ViewController.swift | 1 | 5279 | //
// Copyright (C) 2015 Google, 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 GoogleMobileAds
import UIKit
class ViewController: UIViewController, GADFullScreenContentDelegate {
enum GameState: NSInteger {
case notStarted
case playing
case paused
case ended
}
/// The game length.
static let gameLength = 5
/// The interstitial ad.
var interstitial: GADInterstitialAd?
/// The countdown timer.
var timer: Timer?
/// The amount of time left in the game.
var timeLeft = gameLength
/// The state of the game.
var gameState = GameState.notStarted
/// The date that the timer was paused.
var pauseDate: Date?
/// The last fire date before a pause.
var previousFireDate: Date?
/// The countdown timer label.
@IBOutlet weak var gameText: UILabel!
/// The play again button.
@IBOutlet weak var playAgainButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Pause game when application enters background.
NotificationCenter.default.addObserver(
self,
selector: #selector(ViewController.pauseGame),
name: UIApplication.didEnterBackgroundNotification, object: nil)
// Resume game when application becomes active.
NotificationCenter.default.addObserver(
self,
selector: #selector(ViewController.resumeGame),
name: UIApplication.didBecomeActiveNotification, object: nil)
startNewGame()
}
// MARK: - Game Logic
fileprivate func startNewGame() {
loadInterstitial()
gameState = .playing
timeLeft = ViewController.gameLength
playAgainButton.isHidden = true
updateTimeLeft()
timer = Timer.scheduledTimer(
timeInterval: 1.0,
target: self,
selector: #selector(ViewController.decrementTimeLeft(_:)),
userInfo: nil,
repeats: true)
}
fileprivate func loadInterstitial() {
let request = GADRequest()
GADInterstitialAd.load(
withAdUnitID: "ca-app-pub-3940256099942544/4411468910", request: request
) { (ad, error) in
if let error = error {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
return
}
self.interstitial = ad
self.interstitial?.fullScreenContentDelegate = self
}
}
fileprivate func updateTimeLeft() {
gameText.text = "\(timeLeft) seconds left!"
}
@objc func decrementTimeLeft(_ timer: Timer) {
timeLeft -= 1
updateTimeLeft()
if timeLeft == 0 {
endGame()
}
}
@objc func pauseGame() {
if gameState != .playing {
return
}
gameState = .paused
// Record the relevant pause times.
pauseDate = Date()
previousFireDate = timer?.fireDate
// Prevent the timer from firing while app is in background.
timer?.fireDate = Date.distantFuture
}
@objc func resumeGame() {
if gameState != .paused {
return
}
gameState = .playing
// Calculate amount of time the app was paused.
let pauseTime = (pauseDate?.timeIntervalSinceNow)! * -1
// Set the timer to start firing again.
timer?.fireDate = (previousFireDate?.addingTimeInterval(pauseTime))!
}
fileprivate func endGame() {
gameState = .ended
timer?.invalidate()
timer = nil
let alert = UIAlertController(
title: "Game Over",
message: "You lasted \(ViewController.gameLength) seconds",
preferredStyle: .alert)
let alertAction = UIAlertAction(
title: "OK",
style: .cancel,
handler: { [weak self] action in
if let ad = self?.interstitial {
ad.present(fromRootViewController: self!)
} else {
print("Ad wasn't ready")
}
self?.playAgainButton.isHidden = false
})
alert.addAction(alertAction)
self.present(alert, animated: true, completion: nil)
}
// MARK: - Interstitial Button Actions
@IBAction func playAgain(_ sender: AnyObject) {
startNewGame()
}
// MARK: - GADFullScreenContentDelegate
func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
print("Ad will present full screen content.")
}
func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error)
{
print("Ad failed to present full screen content with error \(error.localizedDescription).")
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
print("Ad did dismiss full screen content.")
}
// MARK: - deinit
deinit {
NotificationCenter.default.removeObserver(
self,
name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.removeObserver(
self,
name: UIApplication.didBecomeActiveNotification, object: nil)
}
}
| apache-2.0 | e244b4743d22d99afac40c60a47eb309 | 25.395 | 99 | 0.680811 | 4.743037 | false | false | false | false |
SuPair/edhita | Edhita/Models/SettingsForm.swift | 1 | 1704 | //
// SettingsForm.swift
// Edhita
//
// Created by Tatsuya Tobioka on 10/9/14.
// Copyright (c) 2014 tnantoka. All rights reserved.
//
import UIKit
public class SettingsForm: NSObject, FXForm {
private struct Defaults {
static let accessoryViewKey = "SettingsForm.Defaults.accessoryViewKey"
}
public class var sharedForm: SettingsForm {
struct Singleton {
static let sharedForm = SettingsForm()
}
return Singleton.sharedForm
}
override init() {
super.init()
var defaults = [String: AnyObject]()
defaults[Defaults.accessoryViewKey] = true
NSUserDefaults.standardUserDefaults().registerDefaults(defaults)
self.accessoryView = NSUserDefaults.standardUserDefaults().boolForKey(Defaults.accessoryViewKey)
}
var accessoryView: Bool = true {
didSet {
NSUserDefaults.standardUserDefaults().setBool(self.accessoryView, forKey: Defaults.accessoryViewKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
public func extraFields() -> [AnyObject]! {
return [
[
FXFormFieldHeader : "",
FXFormFieldType : FXFormFieldTypeLabel,
FXFormFieldAction : "fontDidTap:",
FXFormFieldTitle : NSLocalizedString("Font", comment: ""),
],
[
FXFormFieldHeader : "",
FXFormFieldType : FXFormFieldTypeLabel,
FXFormFieldAction : "acknowledgementsDidTap:",
FXFormFieldTitle : NSLocalizedString("Acknowledgements", comment: ""),
],
]
}
}
| mit | 847e4a0db1cc3413629e2c8d7f4bf325 | 28.894737 | 112 | 0.600939 | 5.776271 | false | false | false | false |
kinyong/KYWeiboDemo-Swfit | AYWeibo/AYWeibo/classes/Home/ComposeToolbar.swift | 1 | 1463 | //
// ComposeToolbar.swift
// AYWeibo
//
// Created by Jinyong on 16/7/24.
// Copyright © 2016年 Ayong. All rights reserved.
//
import UIKit
class ComposeToolbar: UIToolbar {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// 接受外界传入的textView
var textView: UITextView?
/// 接受键盘视图
var keyboardView: UIView?
// MARK: - 内部控制方法
func setupUI() {
}
// 表情按钮
@IBAction func emotionBtnClick(sender: AnyObject) {
/*
通过观察发现,如果是系统默认的键盘inputView = nil
如果不是系统自带的键盘,那么inputView != nil
注意点:要切换键盘,必须先关闭键盘,切换之后再打开
*/
assert(textView != nil, "实现表情按钮textView不能为nil,需要外界传入textview")
// 1.先关闭键盘
textView?.resignFirstResponder()
// 2.判断inputView是否为nil,进行切换
if textView?.inputView != nil {
// 切换为系统键盘
textView?.inputView = nil
} else {
// 切换为自定义键盘
textView?.inputView = keyboardView
}
// 3.切换后打开键盘
textView?.becomeFirstResponder()
}
}
| apache-2.0 | de3cc008fe3bd49e61b8ca884ac0ed2e | 19.982456 | 70 | 0.550167 | 4.068027 | false | false | false | false |
RobotRebels/SwiftLessons | chapter1/lesson1/11.05.2017.playground/Contents.swift | 1 | 688 | //: Playground - noun: a place where people can play
import Foundation
var peremennaia: Int = 1
//var имя_переменной = значение переменной
var myBirthday: Float
var testStr = "123"
var optionalNumber1: Int?
var optionalNumber3: Int?
optionalNumber3 = 5
//print(optionalNumber3)
//var optionalNumber2 = optionalNumber3!
//var number: Int = optionalNumber3 ?? 0
let number123: Int? = nil
print(number123)
func add(arg1: Double, arg2: Double) -> Double {
return arg1 + arg2
}
var value1: Float = 0.1
var value2 = 0.2
var result: Double
result = add(arg1: Double(value1), arg2: value2)
var a1: String = "123t"
var a2: Int = Int(a1) ?? 0
| mit | 6749bb56dce3604625582509caa84332 | 13.6 | 52 | 0.701674 | 2.986364 | false | false | false | false |
mxcl/swift-package-manager | Sources/Basic/TerminalController.swift | 1 | 4354 | /*
This source file is part of the Swift.org open source project
Copyright 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import libc
import func POSIX.getenv
/// A class to have better control on tty output streams: standard output and standard error.
/// Allows operations like cursor movement and colored text output on tty.
public final class TerminalController {
/// Terminal color choices.
public enum Color {
case noColor
case red
case green
case yellow
case cyan
case white
case black
case grey
/// Returns the color code which can be prefixed on a string to display it in that color.
fileprivate var string: String {
switch self {
case .noColor: return ""
case .red: return "\u{001B}[31m"
case .green: return "\u{001B}[32m"
case .yellow: return "\u{001B}[33m"
case .cyan: return "\u{001B}[36m"
case .white: return "\u{001B}[37m"
case .black: return "\u{001B}[30m"
case .grey: return "\u{001B}[30;1m"
}
}
}
/// Pointer to output stream to operate on.
private var stream: LocalFileOutputByteStream
/// Width of the terminal.
public let width: Int
/// Code to clear the line on a tty.
private let clearLineString = "\u{001B}[2K"
/// Code to end any currently active wrapping.
private let resetString = "\u{001B}[0m"
/// Code to make string bold.
private let boldString = "\u{001B}[1m"
/// Constructs the instance if the stream is a tty.
public init?(stream: LocalFileOutputByteStream) {
// Make sure this file stream is tty.
guard isatty(fileno(stream.fp)) != 0 else {
return nil
}
width = TerminalController.terminalWidth() ?? 80 // Assume default if we are not able to determine.
self.stream = stream
}
/// Tries to get the terminal width first using COLUMNS env variable and
/// if that fails ioctl method testing on stdout stream.
///
/// - Returns: Current width of terminal if it was determinable.
public static func terminalWidth() -> Int? {
// Try to get from enviornment.
if let columns = POSIX.getenv("COLUMNS"), let width = Int(columns) {
return width
}
// Try determining using ioctl.
var ws = winsize()
if ioctl(1, UInt(TIOCGWINSZ), &ws) == 0 {
return Int(ws.ws_col)
}
return nil
}
/// Flushes the stream.
public func flush() {
stream.flush()
}
/// Clears the current line and moves the cursor to beginning of the line..
public func clearLine() {
stream <<< clearLineString <<< "\r"
flush()
}
/// Moves the cursor y columns up.
public func moveCursor(y: Int) {
stream <<< "\u{001B}[\(y)A"
flush()
}
/// Writes a string to the stream.
public func write(_ string: String, inColor color: Color = .noColor, bold: Bool = false) {
writeWrapped(string, inColor: color, bold: bold, stream: stream)
flush()
}
/// Inserts a new line character into the stream.
public func endLine() {
stream <<< "\n"
flush()
}
/// Wraps the string into the color mentioned.
public func wrap(_ string: String, inColor color: Color, bold: Bool = false) -> String {
let stream = BufferedOutputByteStream()
writeWrapped(string, inColor: color, bold: bold, stream: stream)
guard let string = stream.bytes.asString else {
fatalError("Couldn't get string value from stream.")
}
return string
}
private func writeWrapped(_ string: String, inColor color: Color, bold: Bool = false, stream: OutputByteStream) {
// Don't wrap if string is empty or color is no color.
guard !string.isEmpty && color != .noColor else {
stream <<< string
return
}
stream <<< color.string <<< (bold ? boldString : "") <<< string <<< resetString
}
}
| apache-2.0 | 1aa0c9df210f178499348167d7aa94eb | 31.014706 | 117 | 0.598989 | 4.424797 | false | false | false | false |
roambotics/swift | test/Concurrency/preconcurrency_typealias.swift | 2 | 1603 | // RUN: %target-swift-frontend -typecheck -verify %s
// REQUIRES: concurrency
@preconcurrency @MainActor func f() { }
// expected-note@-1 2{{calls to global function 'f()' from outside of its actor context are implicitly asynchronous}}
@preconcurrency typealias FN = @Sendable () -> Void
struct Outer {
@preconcurrency typealias FN = @Sendable () -> Void
}
@preconcurrency func preconcurrencyFunc(callback: FN) {}
func test() {
var _: Outer.FN = {
f()
}
var _: FN = {
f()
print("Hello")
}
var mutableVariable = 0
preconcurrencyFunc {
mutableVariable += 1 // no sendable warning
}
mutableVariable += 1
}
@available(SwiftStdlib 5.1, *)
func testAsync() async {
var _: Outer.FN = {
f() // expected-error{{call to main actor-isolated global function 'f()' in a synchronous nonisolated context}}
}
var _: FN = {
f() // expected-error{{call to main actor-isolated global function 'f()' in a synchronous nonisolated context}}
print("Hello")
}
var mutableVariable = 0
preconcurrencyFunc {
mutableVariable += 1 // expected-warning{{mutation of captured var 'mutableVariable' in concurrently-executing code; this is an error in Swift 6}}
}
mutableVariable += 1
}
// rdar://99518344 - @Sendable in nested positions
@preconcurrency typealias OtherHandler = @Sendable () -> Void
@preconcurrency typealias Handler = (@Sendable () -> OtherHandler?)?
@preconcurrency func f(arg: Int, withFn: Handler?) {}
class C {
func test() {
f(arg: 5, withFn: { [weak self] () -> OtherHandler? in
_ = self
return nil
})
}
}
| apache-2.0 | 0f00dbe654d1d2964a34743b9d5cf043 | 24.854839 | 150 | 0.660636 | 3.997506 | false | false | false | false |
RadioBear/CalmKit | CalmKit/Animators/BRBCalmKitCircleFlipAnimator.swift | 1 | 2748 | //
// BRBCalmKitCircleFlipAnimator.swift
// CalmKit
//
// Copyright (c) 2016 RadioBear
//
// 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 BRBCalmKitCircleFlipAnimator: BRBCalmKitAnimator {
func setupAnimation(inLayer layer : CALayer, withSize size : CGSize, withColor color : UIColor) {
let circle = CALayer()
circle.frame = CGRectInset(CGRectMake(0.0, 0.0, size.width, size.height), 2.0, 2.0)
circle.backgroundColor = color.CGColor
circle.cornerRadius = circle.bounds.height * 0.5
circle.anchorPoint = CGPointMake(0.5, 0.5)
circle.anchorPointZ = 0.5
circle.shouldRasterize = true
circle.rasterizationScale = UIScreen.mainScreen().scale
layer.addSublayer(circle)
let anim = CAKeyframeAnimation(keyPath: "transform")
anim.removedOnCompletion = false
anim.repeatCount = HUGE
anim.duration = 1.2
anim.keyTimes = [0.0, 0.5, 1.0]
anim.timingFunctions = [
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
]
anim.values = [
NSValue(CATransform3D: p_transform3DRotationWithPerspective(1.0/120.0, 0, 0, 0, 0)),
NSValue(CATransform3D: p_transform3DRotationWithPerspective(1.0/120.0, CGFloat(M_PI), 0.0, 1.0, 0.0)),
NSValue(CATransform3D: p_transform3DRotationWithPerspective(1.0/120.0, CGFloat(M_PI), 0.0, 0.0, 1.0)),
]
circle.addAnimation(anim, forKey:"calmkit-anim")
}
}
| mit | 9840b5ef8373fb53346795a46d8b61ec | 41.9375 | 114 | 0.693959 | 4.403846 | false | false | false | false |
material-components/material-components-ios-codelabs | MDC-103/Swift/Starter/Shrine/Shrine/CustomLayout.swift | 4 | 5364 | /*
Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
private let HORIZONTAL_PADDING: CGFloat = 0.10
class CustomLayout: UICollectionViewLayout {
var itemASize: CGSize = .zero
var itemBSize: CGSize = .zero
var itemCSize: CGSize = .zero
var itemAOffset: CGPoint = .zero
var itemBOffset: CGPoint = .zero
var itemCOffset: CGPoint = .zero
var tripleSize: CGSize = .zero
var frameCache = [NSValue]()
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepare() {
super.prepare()
var parentFrame = self.collectionView!.bounds.standardized
parentFrame = UIEdgeInsetsInsetRect(parentFrame, self.collectionView!.adjustedContentInset)
let contentHeight = parentFrame.size.height -
(self.collectionView!.contentInset.top + self.collectionView!.contentInset.bottom)
let contentWidth = parentFrame.size.width
let landscapeItemSize = CGSize(width: contentWidth * 0.46, height: contentHeight * 0.32)
let portaitItemSize = CGSize(width: contentWidth * 0.3, height: contentHeight * 0.54)
self.itemASize = landscapeItemSize
self.itemBSize = landscapeItemSize
self.itemCSize = portaitItemSize
self.itemAOffset = CGPoint(x: contentWidth * HORIZONTAL_PADDING, y: contentHeight * 0.66)
self.itemBOffset = CGPoint(x: contentWidth * 0.3, y: contentHeight * 0.16)
self.itemCOffset = CGPoint(x: self.itemBOffset.x + self.itemBSize.width + contentWidth * HORIZONTAL_PADDING, y: contentHeight * 0.2)
self.tripleSize = CGSize(width: self.itemCOffset.x + self.itemCSize.width, height: contentHeight)
self.frameCache.removeAll()
for itemIndex in 0..<self.collectionView!.numberOfItems(inSection:0) {
let tripleCount = itemIndex / 3
let internalIndex = itemIndex % 3
var itemFrame: CGRect = .zero
if (internalIndex == 2) {
itemFrame.size = self.itemCSize
} else if (internalIndex == 1) {
itemFrame.size = self.itemBSize
} else {
itemFrame.size = self.itemASize
}
itemFrame.origin.x = self.tripleSize.width * CGFloat(tripleCount)
if (internalIndex == 2) {
itemFrame.origin.x += self.itemCOffset.x
itemFrame.origin.y = self.itemCOffset.y
} else if (internalIndex == 1) {
itemFrame.origin.x += self.itemBOffset.x
itemFrame.origin.y = self.itemBOffset.y
} else {
itemFrame.origin.x += self.itemAOffset.x
itemFrame.origin.y = self.itemAOffset.y
}
let frameValue: NSValue = NSValue(cgRect: itemFrame)
self.frameCache.append(frameValue)
}
}
override var collectionViewContentSize: CGSize {
get {
var contentSize: CGSize = .zero
contentSize.height = self.tripleSize.height
let lastItemFrameValue: NSValue = self.frameCache.last!
let lastItemFrame = lastItemFrameValue.cgRectValue
contentSize.width = lastItemFrame.maxX + HORIZONTAL_PADDING * self.collectionView!.frame.width
return contentSize
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()
for itemIndex in 0..<self.frameCache.count {
let itemFrame = self.frameCache[itemIndex].cgRectValue
if rect.intersects(itemFrame) {
let indexPath = IndexPath(row: itemIndex, section: 0)
let attributes = self.collectionView!.layoutAttributesForItem(at: indexPath)!
attributes.frame = itemFrame
visibleLayoutAttributes.append(attributes)
}
}
return visibleLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let tripleCount = indexPath.row / 3
let internalIndex = indexPath.row % 3
var itemFrame: CGRect = .zero
if (internalIndex == 2) {
itemFrame.size = self.itemCSize
} else if (internalIndex == 1) {
itemFrame.size = self.itemBSize
} else {
itemFrame.size = self.itemASize
}
itemFrame.origin.x = self.tripleSize.width * CGFloat(tripleCount)
if (internalIndex == 2) {
itemFrame.origin.x += self.itemCOffset.x
itemFrame.origin.y = self.itemCOffset.y
} else if (internalIndex == 1) {
itemFrame.origin.x += self.itemBOffset.x
itemFrame.origin.y = self.itemBOffset.y
} else {
itemFrame.origin.x += self.itemAOffset.x
itemFrame.origin.y = self.itemAOffset.y
}
let attributes = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
attributes.frame = itemFrame
return attributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
| apache-2.0 | 7a6169a623174b203c2fd90702c3e440 | 33.165605 | 136 | 0.704139 | 4.451452 | false | false | false | false |
sgr-ksmt/PullToDismiss | Sources/PullToDismiss.swift | 1 | 9349 | //
// PullToDismiss.swift
// PullToDismiss
//
// Created by Suguru Kishimoto on 11/13/16.
// Copyright © 2016 Suguru Kishimoto. All rights reserved.
//
import Foundation
import UIKit
open class PullToDismiss: NSObject {
public struct Defaults {
private init() {}
public static let dismissableHeightPercentage: CGFloat = 0.33
}
open var backgroundEffect: BackgroundEffect? = ShadowEffect.default
open var edgeShadow: EdgeShadow? = EdgeShadow.default
public var dismissAction: (() -> Void)?
public weak var delegate: UIScrollViewDelegate? {
didSet {
var delegates: [UIScrollViewDelegate] = [self]
if let delegate = delegate {
delegates.append(delegate)
}
proxy = ScrollViewDelegateProxy(delegates: delegates)
}
}
public var dismissableHeightPercentage: CGFloat = Defaults.dismissableHeightPercentage {
didSet {
dismissableHeightPercentage = min(max(0.0, dismissableHeightPercentage), 1.0)
}
}
fileprivate var viewPositionY: CGFloat = 0.0
fileprivate var dragging: Bool = false
fileprivate var previousContentOffsetY: CGFloat = 0.0
fileprivate weak var viewController: UIViewController?
private var __scrollView: UIScrollView?
private var proxy: ScrollViewDelegateProxy? {
didSet {
__scrollView?.delegate = proxy
}
}
private var panGesture: UIPanGestureRecognizer?
private var backgroundView: UIView?
private var navigationBarHeight: CGFloat = 0.0
private var blurSaturationDeltaFactor: CGFloat = 1.8
convenience public init?(scrollView: UIScrollView) {
guard let viewController = type(of: self).viewControllerFromScrollView(scrollView) else {
print("a scrollView must be on the view controller.")
return nil
}
self.init(scrollView: scrollView, viewController: viewController)
}
public init(scrollView: UIScrollView, viewController: UIViewController, navigationBar: UIView? = nil) {
super.init()
self.proxy = ScrollViewDelegateProxy(delegates: [self])
self.__scrollView = scrollView
self.__scrollView?.delegate = self.proxy
self.viewController = viewController
if let navigationBar = navigationBar ?? viewController.navigationController?.navigationBar {
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
navigationBar.addGestureRecognizer(gesture)
self.navigationBarHeight = navigationBar.frame.height
self.panGesture = gesture
}
}
deinit {
if let panGesture = panGesture {
panGesture.view?.removeGestureRecognizer(panGesture)
}
proxy = nil
__scrollView?.delegate = nil
__scrollView = nil
}
fileprivate var targetViewController: UIViewController? {
return viewController?.navigationController ?? viewController
}
private var haveShadowEffect: Bool {
return backgroundEffect != nil || edgeShadow != nil
}
fileprivate func dismiss() {
targetViewController?.dismiss(animated: true, completion: nil)
}
// MARK: - shadow view
private func makeBackgroundView() {
deleteBackgroundView()
guard let backgroundEffect = backgroundEffect else {
return
}
let backgroundView = backgroundEffect.makeBackgroundView()
backgroundView.frame = targetViewController?.view.bounds ?? .zero
switch backgroundEffect.target {
case .targetViewController:
targetViewController?.view.addSubview(backgroundView)
backgroundView.superview?.sendSubviewToBack(backgroundView)
backgroundView.frame = targetViewController?.view.bounds ?? .zero
case .presentingViewController:
targetViewController?.presentingViewController?.view.addSubview(backgroundView)
backgroundView.frame = targetViewController?.presentingViewController?.view.bounds ?? .zero
}
self.backgroundView = backgroundView
}
private func updateBackgroundView(rate: CGFloat) {
guard let backgroundEffect = backgroundEffect else {
return
}
backgroundEffect.applyEffect(view: backgroundView, rate: rate)
}
private func deleteBackgroundView() {
backgroundView?.removeFromSuperview()
backgroundView = nil
targetViewController?.view.clipsToBounds = true
}
private func resetBackgroundView() {
guard let backgroundEffect = backgroundEffect else {
return
}
backgroundEffect.applyEffect(view: backgroundView, rate: 1.0)
}
@objc private func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .began:
startDragging()
case .changed:
let diff = gesture.translation(in: gesture.view).y
updateViewPosition(offset: diff)
gesture.setTranslation(.zero, in: gesture.view)
case .ended:
finishDragging(withVelocity: .zero)
default:
break
}
}
fileprivate func startDragging() {
targetViewController?.view.layer.removeAllAnimations()
backgroundView?.layer.removeAllAnimations()
viewPositionY = 0.0
makeBackgroundView()
targetViewController?.view.applyEdgeShadow(edgeShadow)
if haveShadowEffect {
targetViewController?.view.clipsToBounds = false
}
}
fileprivate func updateViewPosition(offset: CGFloat) {
var addOffset: CGFloat = offset
// avoid statusbar gone
if viewPositionY >= 0 && viewPositionY < 0.05 {
addOffset = min(max(-0.01, addOffset), 0.01)
}
viewPositionY += addOffset
targetViewController?.view.frame.origin.y = max(0.0, viewPositionY)
if case .some(.targetViewController) = backgroundEffect?.target {
backgroundView?.frame.origin.y = -(targetViewController?.view.frame.origin.y ?? 0.0)
}
let targetViewOriginY: CGFloat = targetViewController?.view.frame.origin.y ?? 0.0
let targetViewHeight: CGFloat = targetViewController?.view.frame.height ?? 0.0
let rate: CGFloat = (1.0 - (targetViewOriginY / (targetViewHeight * dismissableHeightPercentage)))
updateBackgroundView(rate: rate)
targetViewController?.view.updateEdgeShadow(edgeShadow, rate: rate)
}
fileprivate func finishDragging(withVelocity velocity: CGPoint) {
let originY = targetViewController?.view.frame.origin.y ?? 0.0
let dismissableHeight = (targetViewController?.view.frame.height ?? 0.0) * dismissableHeightPercentage
if originY > dismissableHeight || originY > 0 && velocity.y < 0 {
deleteBackgroundView()
targetViewController?.view.detachEdgeShadow()
proxy = nil
_ = dismissAction?() ?? dismiss()
} else if originY != 0.0 {
UIView.perform(.delete, on: [], options: [.allowUserInteraction], animations: { [weak self] in
self?.targetViewController?.view.frame.origin.y = 0.0
self?.resetBackgroundView()
self?.targetViewController?.view.updateEdgeShadow(self?.edgeShadow, rate: 1.0)
}) { [weak self] finished in
if finished {
self?.deleteBackgroundView()
self?.targetViewController?.view.detachEdgeShadow()
}
}
} else {
self.deleteBackgroundView()
}
viewPositionY = 0.0
}
private static func viewControllerFromScrollView(_ scrollView: UIScrollView) -> UIViewController? {
var responder: UIResponder? = scrollView
while let r = responder {
if let viewController = r as? UIViewController {
return viewController
}
responder = r.next
}
return nil
}
}
extension PullToDismiss: UITableViewDelegate {
}
extension PullToDismiss: UICollectionViewDelegate {
}
extension PullToDismiss: UICollectionViewDelegateFlowLayout {
}
extension PullToDismiss: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if dragging {
let diff = -(scrollView.contentOffset.y - previousContentOffsetY)
if scrollView.contentOffset.y < -scrollView.contentInset.top || (targetViewController?.view.frame.origin.y ?? 0.0) > 0.0 {
updateViewPosition(offset: diff)
scrollView.contentOffset.y = -scrollView.contentInset.top
}
previousContentOffsetY = scrollView.contentOffset.y
}
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startDragging()
dragging = true
previousContentOffsetY = scrollView.contentOffset.y
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
finishDragging(withVelocity: velocity)
dragging = false
previousContentOffsetY = 0.0
}
}
| mit | acf27575356ae43f49b7d513e9adbabc | 35.092664 | 155 | 0.652439 | 5.627935 | false | false | false | false |
LamineNdy/SampleApp | SampleApp/Classes/Services/ResponseSerializer.swift | 1 | 2955 | //
// ResponseSerializer.swift
// Pods
//
// Created by Lamine NDIAYE on 30/11/16.
//
//
import Foundation
import Alamofire
enum BackendError: Error {
case network(error: Error) // Capture any underlying Error from the URLSession API
case dataSerialization(error: Error)
case jsonSerialization(error: Error)
case xmlSerialization(error: Error)
case objectSerialization(reason: String)
}
public protocol ResponseObjectSerializable {
init?(response: HTTPURLResponse, representation: AnyObject)
}
extension DataRequest {
func responseObject<T: ResponseObjectSerializable>(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<T>) -> Void)
-> Self
{
let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonResponseSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response, let responseObject = T(response: response, representation: jsonObject as AnyObject) else {
return .failure(BackendError.objectSerialization(reason: "JSON could not be serialized: \(jsonObject)"))
}
return .success(responseObject)
}
return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
protocol ResponseCollectionSerializable {
static func collection(from response: HTTPURLResponse, withRepresentation representation: Any) -> [Self]
}
extension DataRequest {
@discardableResult
func responseCollection<T: ResponseCollectionSerializable>(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self
{
let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response else {
let reason = "Response collection could not be serialized due to nil response."
return .failure(BackendError.objectSerialization(reason: reason))
}
return .success(T.collection(from: response, withRepresentation: jsonObject))
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
| mit | e85290092d99a5ba77894162f4d08e56 | 35.036585 | 127 | 0.722504 | 5.121317 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/01060-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 1580 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class a {
type b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
func a<T>() -> (T, T -> T) -> T {
var b: ((T, T -> T) -> T)!
return b
}
func ^(a: Boolean, Bool) -> Bool {
return !(a)
}
protocol A {
}
struct B : A {
}
struct C<D, E: A where D.C == E> {
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
class A: A {
}
class B : C {
}
typealias C = B
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
func c<d {
enum c {
func e
var _ = e
}
}
protocol A {
typealias E
}
struct B<T : A> {
let h: T
let i: T.E
}
protocol C {
typealias F
func g<T where T.E == F>(f: B<T>)
}
struct D : C {
typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
func some<S: Sequence, T where Optional<T> == S.Iterator.Element>(xs : S) -> T? {
for (mx : T?) in xs {
if let x = mx {
return x
}
}
return nil
}
let xs : [Int?] = [nil, 4, nil]
print(some(xs))
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
| apache-2.0 | d008bdd37dba3362e5a9fb44b7014065 | 15.808511 | 81 | 0.581646 | 2.540193 | false | false | false | false |
fgengine/quickly | Quickly/Views/Fields/MultiText/QMultiTextField.swift | 1 | 23511 | //
// Quickly
//
public protocol IQMultiTextFieldObserver : class {
func beginEditing(multiTextField: QMultiTextField)
func editing(multiTextField: QMultiTextField)
func endEditing(multiTextField: QMultiTextField)
func pressed(multiTextField: QMultiTextField, action: QFieldAction)
func changed(multiTextField: QMultiTextField, height: CGFloat)
}
open class QMultiTextFieldStyleSheet : QDisplayStyleSheet {
public var validator: IQStringValidator?
public var form: IQFieldForm?
public var textInsets: UIEdgeInsets
public var textStyle: IQTextStyle?
public var placeholderInsets: UIEdgeInsets
public var placeholder: IQText?
public var maximumNumberOfCharecters: UInt
public var maximumNumberOfLines: UInt
public var minimumHeight: CGFloat
public var maximumHeight: CGFloat
public var autocapitalizationType: UITextAutocapitalizationType
public var autocorrectionType: UITextAutocorrectionType
public var spellCheckingType: UITextSpellCheckingType
public var keyboardType: UIKeyboardType
public var keyboardAppearance: UIKeyboardAppearance
public var returnKeyType: UIReturnKeyType
public var enablesReturnKeyAutomatically: Bool
public var isSecureTextEntry: Bool
public var textContentType: UITextContentType!
public var isEnabled: Bool
public var toolbarStyle: QToolbarStyleSheet?
public var toolbarActions: QFieldAction
public init(
validator: IQStringValidator? = nil,
form: IQFieldForm? = nil,
textInsets: UIEdgeInsets = UIEdgeInsets.zero,
textStyle: IQTextStyle? = nil,
placeholderInsets: UIEdgeInsets = UIEdgeInsets.zero,
placeholder: IQText? = nil,
maximumNumberOfCharecters: UInt = 0,
maximumNumberOfLines: UInt = 0,
minimumHeight: CGFloat = 0,
maximumHeight: CGFloat = 0,
autocapitalizationType: UITextAutocapitalizationType = .none,
autocorrectionType: UITextAutocorrectionType = .default,
spellCheckingType: UITextSpellCheckingType = .default,
keyboardType: UIKeyboardType = .default,
keyboardAppearance: UIKeyboardAppearance = .default,
returnKeyType: UIReturnKeyType = .default,
enablesReturnKeyAutomatically: Bool = true,
isSecureTextEntry: Bool = false,
textContentType: UITextContentType! = nil,
isEnabled: Bool = true,
toolbarStyle: QToolbarStyleSheet? = nil,
toolbarActions: QFieldAction = [ .done ],
backgroundColor: UIColor? = nil,
tintColor: UIColor? = nil,
cornerRadius: QViewCornerRadius = .none,
border: QViewBorder = .none,
shadow: QViewShadow? = nil
) {
self.validator = validator
self.form = form
self.textInsets = textInsets
self.textStyle = textStyle
self.placeholderInsets = placeholderInsets
self.placeholder = placeholder
self.maximumNumberOfCharecters = maximumNumberOfCharecters
self.maximumNumberOfLines = maximumNumberOfLines
self.minimumHeight = minimumHeight
self.maximumHeight = maximumHeight
self.autocapitalizationType = autocapitalizationType
self.autocorrectionType = autocorrectionType
self.spellCheckingType = spellCheckingType
self.keyboardType = keyboardType
self.keyboardAppearance = keyboardAppearance
self.returnKeyType = returnKeyType
self.enablesReturnKeyAutomatically = enablesReturnKeyAutomatically
self.isSecureTextEntry = isSecureTextEntry
self.textContentType = textContentType
self.isEnabled = isEnabled
self.toolbarStyle = toolbarStyle
self.toolbarActions = toolbarActions
super.init(
backgroundColor: backgroundColor,
tintColor: tintColor,
cornerRadius: cornerRadius,
border: border,
shadow: shadow
)
}
public init(_ styleSheet: QMultiTextFieldStyleSheet) {
self.validator = styleSheet.validator
self.form = styleSheet.form
self.textInsets = styleSheet.textInsets
self.textStyle = styleSheet.textStyle
self.placeholderInsets = styleSheet.placeholderInsets
self.placeholder = styleSheet.placeholder
self.maximumNumberOfCharecters = styleSheet.maximumNumberOfCharecters
self.maximumNumberOfLines = styleSheet.maximumNumberOfLines
self.minimumHeight = styleSheet.minimumHeight
self.maximumHeight = styleSheet.maximumHeight
self.autocapitalizationType = styleSheet.autocapitalizationType
self.autocorrectionType = styleSheet.autocorrectionType
self.spellCheckingType = styleSheet.spellCheckingType
self.keyboardType = styleSheet.keyboardType
self.keyboardAppearance = styleSheet.keyboardAppearance
self.returnKeyType = styleSheet.returnKeyType
self.enablesReturnKeyAutomatically = styleSheet.enablesReturnKeyAutomatically
self.isSecureTextEntry = styleSheet.isSecureTextEntry
self.textContentType = styleSheet.textContentType
self.isEnabled = styleSheet.isEnabled
self.toolbarStyle = styleSheet.toolbarStyle
self.toolbarActions = styleSheet.toolbarActions
super.init(styleSheet)
}
}
public class QMultiTextField : QDisplayView, IQField {
public typealias ShouldClosure = (_ multiTextField: QMultiTextField) -> Bool
public typealias ActionClosure = (_ multiTextField: QMultiTextField, _ action: QFieldAction) -> Void
public typealias Closure = (_ multiTextField: QMultiTextField) -> Void
public var validator: IQStringValidator? {
willSet { self._field.delegate = nil }
didSet {self._field.delegate = self._fieldDelegate }
}
public var form: IQFieldForm? {
didSet(oldValue) {
if self.form !== oldValue {
if let form = oldValue {
form.remove(field: self)
}
if let form = self.form {
form.add(field: self)
}
}
}
}
public var textStyle: IQTextStyle? {
didSet {
self._field.font = self.textStyle?.font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize)
self._field.textColor = self.textStyle?.color ?? UIColor.black
self._field.textAlignment = self.textStyle?.alignment ?? .left
self.textHeight = self._textHeight()
}
}
public var textInsets: UIEdgeInsets {
set(value) {
if self._field.textContainerInset != value {
self._field.textContainerInset = value
self.textHeight = self._textHeight()
}
}
get { return self._field.textContainerInset }
}
public var text: String {
set(value) {
if self._field.text != value {
self._field.text = value
self._updatePlaceholderVisibility()
self.textHeight = self._textHeight()
if let form = self.form {
form.validation()
}
}
}
get { return self._field.text }
}
public var unformatText: String {
set(value) {
self._field.text = value
self._updatePlaceholderVisibility()
self.textHeight = self._textHeight()
if let form = self.form {
form.validation()
}
}
get {
if let text = self._field.text {
return text
}
return ""
}
}
public var placeholderInsets: UIEdgeInsets = UIEdgeInsets.zero {
didSet(oldValue) {
if self.placeholderInsets != oldValue {
self.setNeedsUpdateConstraints()
}
}
}
public var selectedRange: NSRange {
set(value) { self._field.selectedRange = value }
get { return self._field.selectedRange }
}
public var maximumNumberOfCharecters: UInt = 0
public var maximumNumberOfLines: UInt = 0
public var minimumHeight: CGFloat = 0 {
didSet(oldValue) {
if self.minimumHeight != oldValue {
self.textHeight = self._textHeight()
}
}
}
public var maximumHeight: CGFloat = 0 {
didSet(oldValue) {
if self.maximumHeight != oldValue {
self.textHeight = self._textHeight()
}
}
}
public private(set) var textHeight: CGFloat = 0
public var isValid: Bool {
get {
guard let validator = self.validator else { return true }
return validator.validate(self.unformatText).isValid
}
}
public var placeholder: IQText? {
set(value) {
self._placeholderLabel.text = value
self._updatePlaceholderVisibility()
}
get { return self._placeholderLabel.text }
}
public var isEditable: Bool {
set(value) { self._field.isEditable = value }
get { return self._field.isEditable }
}
public var isSelectable: Bool {
set(value) { self._field.isSelectable = value }
get { return self._field.isSelectable }
}
public var isEnabled: Bool {
set(value) { self._field.isUserInteractionEnabled = value }
get { return self._field.isUserInteractionEnabled }
}
public var isEditing: Bool {
get { return self._field.isFirstResponder }
}
public lazy var toolbar: QToolbar = {
let items = self._toolbarItems()
let view = QToolbar(items: items)
view.isHidden = items.isEmpty
return view
}()
public var toolbarActions: QFieldAction = [] {
didSet(oldValue) {
if self.toolbarActions != oldValue {
let items = self._toolbarItems()
self.toolbar.items = items
self.toolbar.isHidden = items.isEmpty
self.reloadInputViews()
}
}
}
public var onShouldBeginEditing: ShouldClosure?
public var onBeginEditing: Closure?
public var onEditing: Closure?
public var onShouldEndEditing: ShouldClosure?
public var onEndEditing: Closure?
public var onPressedAction: ActionClosure?
public var onChangedHeight: Closure?
private var _placeholderLabel: QLabel!
private var _field: Field!
private var _fieldDelegate: FieldDelegate!
private var _observer: QObserver< IQMultiTextFieldObserver > = QObserver< IQMultiTextFieldObserver >()
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.removeConstraints(self._constraints) }
didSet { self.addConstraints(self._constraints) }
}
open override func setup() {
super.setup()
self.backgroundColor = UIColor.clear
self._fieldDelegate = FieldDelegate(field: self)
self._placeholderLabel = QLabel(frame: self.bounds.inset(by: self.placeholderInsets))
self._placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self._placeholderLabel)
self._field = Field(frame: self.bounds)
self._field.translatesAutoresizingMaskIntoConstraints = false
self._field.textContainer.lineFragmentPadding = 0
self._field.layoutManager.usesFontLeading = false
self._field.inputAccessoryView = self.toolbar
self._field.delegate = self._fieldDelegate
self.insertSubview(self._field, aboveSubview: self._placeholderLabel)
self.textHeight = self._textHeight()
}
open override func updateConstraints() {
super.updateConstraints()
self._constraints = [
self._placeholderLabel.topLayout == self.topLayout.offset(self.placeholderInsets.top),
self._placeholderLabel.leadingLayout == self.leadingLayout.offset(self.placeholderInsets.left),
self._placeholderLabel.trailingLayout == self.trailingLayout.offset(-self.placeholderInsets.right),
self._placeholderLabel.bottomLayout == self.bottomLayout.offset(-self.placeholderInsets.bottom),
self._field.topLayout == self.topLayout,
self._field.leadingLayout == self.leadingLayout,
self._field.trailingLayout == self.trailingLayout,
self._field.bottomLayout == self.bottomLayout
]
}
public func add(observer: IQMultiTextFieldObserver, priority: UInt) {
self._observer.add(observer, priority: priority)
}
public func remove(observer: IQMultiTextFieldObserver) {
self._observer.remove(observer)
}
open func beginEditing() {
self._field.becomeFirstResponder()
}
public func apply(_ styleSheet: QMultiTextFieldStyleSheet) {
self.apply(styleSheet as QDisplayStyleSheet)
self.validator = styleSheet.validator
self.form = styleSheet.form
self.textInsets = styleSheet.textInsets
self.textStyle = styleSheet.textStyle
self.placeholderInsets = styleSheet.placeholderInsets
self.placeholder = styleSheet.placeholder
self.maximumNumberOfCharecters = styleSheet.maximumNumberOfCharecters
self.maximumNumberOfLines = styleSheet.maximumNumberOfLines
self.minimumHeight = styleSheet.minimumHeight
self.maximumHeight = styleSheet.maximumHeight
self.autocapitalizationType = styleSheet.autocapitalizationType
self.autocorrectionType = styleSheet.autocorrectionType
self.spellCheckingType = styleSheet.spellCheckingType
self.keyboardType = styleSheet.keyboardType
self.keyboardAppearance = styleSheet.keyboardAppearance
self.returnKeyType = styleSheet.returnKeyType
self.enablesReturnKeyAutomatically = styleSheet.enablesReturnKeyAutomatically
self.isSecureTextEntry = styleSheet.isSecureTextEntry
if #available(iOS 10.0, *) {
self.textContentType = styleSheet.textContentType
}
self.isEnabled = styleSheet.isEnabled
if let style = styleSheet.toolbarStyle {
self.toolbar.apply(style)
}
self.toolbarActions = styleSheet.toolbarActions
}
}
// MARK: Private
private extension QMultiTextField {
func _updatePlaceholderVisibility() {
self._placeholderLabel.isHidden = self._field.text.count > 0
}
func _textHeight() -> CGFloat {
let textContainerInset = self._field.textContainerInset
let textRect = self._field.layoutManager.usedRect(for: self._field.textContainer)
var height = textContainerInset.top + textRect.height + textContainerInset.bottom
if self.minimumHeight > CGFloat.leastNonzeroMagnitude {
height = max(height, self.minimumHeight)
}
if self.maximumHeight > CGFloat.leastNonzeroMagnitude {
height = min(height, self.maximumHeight)
}
return height
}
private func _toolbarItems() -> [UIBarButtonItem] {
var items: [UIBarButtonItem] = []
if self.toolbarActions.isEmpty == false {
if self.toolbarActions.contains(.cancel) == true {
items.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self._pressedCancel(_:))))
}
items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil))
if self.toolbarActions.contains(.done) == true {
items.append(UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self._pressedDone(_:))))
}
}
return items
}
@objc
func _pressedCancel(_ sender: Any) {
self._pressed(action: .cancel)
self.endEditing(false)
}
@objc
func _pressedDone(_ sender: Any) {
self._pressed(action: .done)
self.endEditing(false)
}
func _pressed(action: QFieldAction) {
if let closure = self.onPressedAction {
closure(self, action)
}
self._observer.notify({ (observer) in
observer.pressed(multiTextField: self, action: action)
})
}
}
// MARK: Private • Field
private extension QMultiTextField {
class Field : UITextView, IQView {
public override var inputAccessoryView: UIView? {
set(value) { super.inputAccessoryView = value }
get {
guard let view = super.inputAccessoryView else { return nil }
return view.isHidden == true ? nil : view
}
}
required init() {
super.init(
frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40),
textContainer: nil
)
self.setup()
}
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(
frame: frame,
textContainer: nil
)
self.setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.setup()
}
open func setup() {
self.backgroundColor = UIColor.clear
}
}
}
// MARK: Private • FieldDelegate
private extension QMultiTextField {
class FieldDelegate : NSObject, UITextViewDelegate {
public weak var field: QMultiTextField?
public init(field: QMultiTextField?) {
self.field = field
super.init()
}
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
guard let field = self.field, let closure = field.onShouldBeginEditing else { return true }
return closure(field)
}
public func textViewDidBeginEditing(_ textView: UITextView) {
guard let field = self.field else { return }
if let closure = field.onBeginEditing {
closure(field)
}
field._observer.notify({ (observer) in
observer.beginEditing(multiTextField: field)
})
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
guard let field = self.field, let closure = field.onShouldEndEditing else { return true }
return closure(field)
}
public func textViewDidEndEditing(_ textView: UITextView) {
guard let field = self.field else { return }
if let closure = field.onEndEditing {
closure(field)
}
field._observer.notify({ (observer) in
observer.endEditing(multiTextField: field)
})
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let field = self.field else { return true }
var sourceText = textView.text ?? ""
if let sourceTextRange = sourceText.range(from: range) {
sourceText = sourceText.replacingCharacters(in: sourceTextRange, with: text)
}
var isValid: Bool = true
if let font = textView.font, field.maximumNumberOfCharecters > 0 || field.maximumNumberOfLines > 0 {
if field.maximumNumberOfCharecters > 0 {
if sourceText.count > field.maximumNumberOfCharecters {
isValid = false
}
}
if field.maximumNumberOfLines > 0 {
let allowWidth = textView.frame.inset(by: textView.textContainerInset).width - (2.0 * textView.textContainer.lineFragmentPadding)
let textSize = textView.textStorage.boundingRect(
with: CGSize(width: allowWidth, height: CGFloat.greatestFiniteMagnitude),
options: [ .usesLineFragmentOrigin ],
context: nil
)
if UInt(textSize.height / font.lineHeight) > field.maximumNumberOfLines {
isValid = false
}
}
}
return isValid
}
public func textViewDidChange(_ textView: UITextView) {
guard let field = self.field else { return }
field._updatePlaceholderVisibility()
let height = field._textHeight()
if abs(field.textHeight - height) > CGFloat.leastNonzeroMagnitude {
field.textHeight = height
UIView.animate(withDuration: 0.1, animations: {
if let onChangedHeight = field.onChangedHeight {
onChangedHeight(field)
}
field._observer.notify({ (observer) in
observer.changed(multiTextField: field, height: height)
})
textView.scrollRangeToVisible(textView.selectedRange)
}, completion: { _ in
textView.scrollRangeToVisible(textView.selectedRange)
})
}
if let closure = field.onEditing {
closure(field)
}
field._observer.notify({ (observer) in
observer.editing(multiTextField: field)
})
if let form = field.form {
form.validation()
}
}
}
}
// MARK: UITextInputTraits
extension QMultiTextField : UITextInputTraits {
public var autocapitalizationType: UITextAutocapitalizationType {
set(value) { self._field.autocapitalizationType = value }
get { return self._field.autocapitalizationType }
}
public var autocorrectionType: UITextAutocorrectionType {
set(value) { self._field.autocorrectionType = value }
get { return self._field.autocorrectionType }
}
public var spellCheckingType: UITextSpellCheckingType {
set(value) { self._field.spellCheckingType = value }
get { return self._field.spellCheckingType }
}
public var keyboardType: UIKeyboardType {
set(value) { self._field.keyboardType = value }
get { return self._field.keyboardType }
}
public var keyboardAppearance: UIKeyboardAppearance {
set(value) { self._field.keyboardAppearance = value }
get { return self._field.keyboardAppearance }
}
public var returnKeyType: UIReturnKeyType {
set(value) { self._field.returnKeyType = value }
get { return self._field.returnKeyType }
}
public var enablesReturnKeyAutomatically: Bool {
set(value) { self._field.enablesReturnKeyAutomatically = value }
get { return self._field.enablesReturnKeyAutomatically }
}
public var isSecureTextEntry: Bool {
set(value) { self._field.isSecureTextEntry = value }
get { return self._field.isSecureTextEntry }
}
@available(iOS 10.0, *)
public var textContentType: UITextContentType! {
set(value) { self._field.textContentType = value }
get { return self._field.textContentType }
}
}
| mit | a6896974e2fd11042828cd46fde04ab7 | 36.551118 | 149 | 0.62207 | 5.729223 | false | false | false | false |
Shivol/Swift-CS333 | playgrounds/uiKit/uiKitCatalog/UIKitCatalog/StackViewController.swift | 3 | 3835 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates different options for manipulating UIStackView content.
*/
import UIKit
class StackViewController: UIViewController {
// MARK: - Properties
@IBOutlet var furtherDetailStackView: UIStackView!
@IBOutlet var plusButton: UIButton!
@IBOutlet var addRemoveExampleStackView: UIStackView!
@IBOutlet var addArrangedViewButton: UIButton!
@IBOutlet var removeArrangedViewButton: UIButton!
let maximumArrangedSubviewCount = 3
// MARK: - View Life Cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
furtherDetailStackView.isHidden = true
plusButton.isHidden = false
updateAddRemoveButtons()
}
// MARK: - Actions
@IBAction func showFurtherDetail(_: AnyObject) {
// Animate the changes by performing them in a `UIView` animation block.
UIView.animate(withDuration: 0.25, animations: {
// Reveal the further details stack view and hide the plus button.
self.furtherDetailStackView.isHidden = false
self.plusButton.isHidden = true
})
}
@IBAction func hideFurtherDetail(_: AnyObject) {
// Animate the changes by performing them in a `UIView` animation block.
UIView.animate(withDuration: 0.25, animations: {
// Hide the further details stack view and reveal the plus button.
self.furtherDetailStackView.isHidden = true
self.plusButton.isHidden = false
})
}
@IBAction func addArrangedSubviewToStack(_: AnyObject) {
// Create a simple, fixed-size, square view to add to the stack view
let newViewSize = CGSize(width: 50, height: 50)
let newView = UIView(frame: CGRect(origin: CGPoint.zero, size: newViewSize))
newView.backgroundColor = randomColor()
newView.widthAnchor.constraint(equalToConstant: newViewSize.width).isActive = true
newView.heightAnchor.constraint(equalToConstant: newViewSize.height).isActive = true
/*
Adding an arranged subview automatically adds it as a child of the
stack view.
*/
addRemoveExampleStackView.addArrangedSubview(newView)
updateAddRemoveButtons()
}
@IBAction func removeArrangedSubviewFromStack(_: AnyObject) {
// Make sure there is an arranged view to remove.
guard let viewToRemove = addRemoveExampleStackView.arrangedSubviews.last else { return }
addRemoveExampleStackView.removeArrangedSubview(viewToRemove)
/*
Calling `removeArrangedSubview` does not remove the provided view from
the stack view's `subviews` array. Since we no longer want the view
we removed to appear, we have to explicitly remove it from its superview.
*/
viewToRemove.removeFromSuperview()
updateAddRemoveButtons()
}
// MARK: - Convenience
fileprivate func updateAddRemoveButtons() {
let arrangedSubviewCount = addRemoveExampleStackView.arrangedSubviews.count
addArrangedViewButton.isEnabled = arrangedSubviewCount < maximumArrangedSubviewCount
removeArrangedViewButton.isEnabled = arrangedSubviewCount > 0
}
fileprivate func randomColor() -> UIColor {
let red = CGFloat(arc4random_uniform(255)) / 255.0
let green = CGFloat(arc4random_uniform(255)) / 255.0
let blue = CGFloat(arc4random_uniform(255)) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
| mit | d55c2afcc9790f60bed591f964db949b | 34.82243 | 96 | 0.661362 | 5.360839 | false | false | false | false |
6ag/BaoKanIOS | BaoKanIOS/Classes/Module/Profile/Controller/JFBaseTableViewController.swift | 1 | 2656 | //
// JFBaseTableViewController.swift
// BaoKanIOS
//
// Created by zhoujianfeng on 16/5/5.
// Copyright © 2016年 六阿哥. All rights reserved.
//
import UIKit
class JFBaseTableViewController: UITableViewController {
/// 组模型数组
var groupModels: [JFProfileCellGroupModel]?
override func viewDidLoad() {
super.viewDidLoad()
tableView.sectionHeaderHeight = 0.01
tableView.separatorStyle = .none
tableView.register(JFProfileCell.self, forCellReuseIdentifier: "profileCell")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return groupModels?.count ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groupModels![section].cells?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "profileCell") as! JFProfileCell
let groupModel = groupModels![indexPath.section]
let cellModel = groupModel.cells![indexPath.row]
cell.cellModel = cellModel
cell.showLineView = !(indexPath.row == groupModel.cells!.count - 1)
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return groupModels![section].footerTitle
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return groupModels![section].headerTitle
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cellModel = groupModels![indexPath.section].cells![indexPath.row]
// 如果有可执行代码就执行
if cellModel.operation != nil {
cellModel.operation!()
return
}
// 如果是箭头类型就跳转控制器
if cellModel .isKind(of: JFProfileCellArrowModel.self) {
let cellArrow = cellModel as! JFProfileCellArrowModel
/// 目标控制器类
let destinationVcClass = cellArrow.destinationVc as! UIViewController.Type
let destinationVc = destinationVcClass.init()
destinationVc.title = cellArrow.title
navigationController?.pushViewController(destinationVc, animated: true)
}
}
}
| apache-2.0 | 6d78898fdce34fcd4c86fcd5125695ed | 32.907895 | 109 | 0.646876 | 5.335404 | false | false | false | false |
exercism/xswift | exercises/dominoes/Sources/Dominoes/DominoesExample.swift | 2 | 4900 | struct Dominoes {
let singles: [Bone]
let doubles: [Bone]
var chained: Bool {
if singles.isEmpty && doubles.count == 1 { return true }
let (success, result) = chainning(swapDuplicate(singles))
if doubles.isEmpty {
return success
} else if success == true {
return doubles.count == doubles.filter({ each in return result.contains(where: { e in return e.value.head == each.value.head }) }).count
} else {
return false
}
}
private func swapDuplicate(_ input: [Bone]) -> [Bone] {
var unique = [Bone]()
for each in input {
if unique.contains(each) {
unique.insert(Bone(each.value.tail, each.value.head), at: 0)
} else {
unique.append(each)
}
}
return unique
}
private func chainning(_ input: [Bone]) -> (Bool, [Bone]) {
var matched = input
guard !matched.isEmpty else { return (false, []) }
let total = matched.count - 1
for index in 0...total {
for innerIndex in 0...total {
matched[index].connect(matched[innerIndex])
}
}
return (matched.filter({ $0.connected >= 2 }).count == matched.count) ?
(true, matched) : (false, [])
}
init(_ input: [(Int, Int)]) {
var singles = [Bone]()
var doubles = [Bone]()
for each in input {
if each.0 == each.1 {
doubles.append(Bone(each.0, each.1))
} else {
singles.append(Bone(each.0, each.1))
}
}
self.singles = singles
self.doubles = doubles
}
}
func == (lhs: Bone, rhs: Bone) -> Bool {
return lhs.value.head == rhs.value.head && lhs.value.tail == rhs.value.tail
}
class Bone: CustomStringConvertible, Equatable {
let value:(head: Int, tail: Int)
var connected: Int = 0
var available: Int?
var connectedTo: Bone?
var description: String {
return "\(value)|\(connected)|\(String(describing: available)) "
}
@discardableResult
func connect(_ input: Bone) -> Bool {
guard self !== input else { return false }
guard self !== input.connectedTo else { return false }
var toReturn = false
func oneZero() {
if available == input.value.head {
self.available = nil
input.available = input.value.tail
toReturn = true
}
if available == input.value.tail {
self.available = nil
input.available = input.value.head
toReturn = true
}
}
func zeroOne() {
if available == value.head {
input.available = nil
self.available = value.tail
toReturn = true
}
if available == value.tail {
input.available = nil
self.available = value.head
toReturn = true
}
}
func oneOne() {
if available == input.available {
self.available = nil
input.available = nil
toReturn = true
}
}
func zeroZero() {
if value.head == input.value.head {
available = value.tail
input.available = input.value.tail
connectedTo = input
toReturn = true
}
if value.tail == input.value.tail {
available = value.head
input.available = input.value.head
connectedTo = input
toReturn = true
}
if value.head == input.value.tail {
available = value.tail
input.available = input.value.head
connectedTo = input
toReturn = true
}
if value.tail == input.value.head {
available = value.head
input.available = input.value.tail
connectedTo = input
toReturn = true
}
}
switch (connected, input.connected) {
case (1, 0):
guard available != nil else { return false }
oneZero()
case (0, 1):
guard input.available != nil else { return false }
zeroOne()
case (1, 1):
oneOne()
case (0, 0):
zeroZero()
default:
toReturn = false
}
if toReturn {
connected += 1
input.connected += 1
return true
} else {
return false
}
}
init(_ head: Int, _ tail: Int) {
self.value.head = head
self.value.tail = tail
}
}
| mit | ecc8543418954737b19dae6b8a8f30c1 | 26.840909 | 148 | 0.477959 | 4.725169 | false | false | false | false |
dduan/swift | test/Constraints/function.swift | 1 | 2214 | // RUN: %target-parse-verify-swift
func f0(x: Float) -> Float {}
func f1(x: Float) -> Float {}
func f2(@autoclosure x: () -> Float) {}
var f : Float
f0(f0(f))
f0(1)
f1(f1(f))
f2(f)
f2(1.0)
func call_lvalue(@autoclosure rhs: () -> Bool) -> Bool {
return rhs()
}
// Function returns
func weirdCast<T, U>(x: T) -> U {}
func ff() -> (Int) -> (Float) { return weirdCast }
// Block <-> function conversions
var funct: Int -> Int = { $0 }
var block: @convention(block) Int -> Int = funct
funct = block
block = funct
// Application of implicitly unwrapped optional functions
var optFunc: (String -> String)! = { $0 }
var s: String = optFunc("hi")
// <rdar://problem/17652759> Default arguments cause crash with tuple permutation
func testArgumentShuffle(first: Int = 7, third: Int = 9) {
}
testArgumentShuffle(third: 1, 2)
func rejectsAssertStringLiteral() {
assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
}
// <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads
func process(line: UInt = #line, _ fn: () -> Void) {}
func process(line: UInt = #line) -> Int { return 0 }
func dangerous() throws {}
func test() {
process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}}
try dangerous()
test()
}
}
// <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic
class A {
func a(text:String) {
}
func a(text:String, something:Int?=nil) {
}
}
A().a(text:"sometext") // expected-error{{extraneous argument label 'text:' in call}}{{7-12=}}
// <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type
func r22451001() -> AnyObject {}
print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}}
// SR-590 Passing two parameters to a function that takes one argument of type Any crashes the compiler
func sr590(x: Any) {}
sr590(3,4) // expected-error {{extra argument in call}}
| apache-2.0 | 5039311cf900e45197521a73283e6075 | 26.333333 | 152 | 0.671183 | 3.406154 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Space/MXSpaceService.swift | 1 | 40898 | //
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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
/// MXSpaceService error
public enum MXSpaceServiceError: Int, Error {
case spaceNotFound
case unknown
}
// MARK: - MXSpaceService errors
extension MXSpaceServiceError: CustomNSError {
public static let errorDomain = "org.matrix.sdk.spaceService"
public var errorCode: Int {
return Int(rawValue)
}
public var errorUserInfo: [String: Any] {
return [:]
}
}
// MARK: - MXSpaceService notification constants
extension MXSpaceService {
/// Posted once the first graph as been built or loaded
public static let didInitialise = Notification.Name("MXSpaceServiceDidInitialise")
/// Posted once the graph of rooms is up and running
public static let didBuildSpaceGraph = Notification.Name("MXSpaceServiceDidBuildSpaceGraph")
}
/// MXSpaceService enables to handle spaces.
@objcMembers
public class MXSpaceService: NSObject {
// MARK: - Properties
private let spacesPerIdReadWriteQueue: DispatchQueue
private unowned let session: MXSession
private lazy var stateEventBuilder: MXRoomInitialStateEventBuilder = {
return MXRoomInitialStateEventBuilder()
}()
private let roomTypeMapper: MXRoomTypeMapper
private let processingQueue: DispatchQueue
private let sdkProcessingQueue: DispatchQueue
private let completionQueue: DispatchQueue
private var spacesPerId: [String: MXSpace] = [:]
private var isGraphBuilding = false;
private var isClosed = false;
private var sessionStateDidChangeObserver: Any?
private var graph: MXSpaceGraphData = MXSpaceGraphData() {
didSet {
var spacesPerId: [String:MXSpace] = [:]
self.graph.spaceRoomIds.forEach { spaceId in
if let space = self.getSpace(withId: spaceId) {
spacesPerId[spaceId] = space
}
}
spacesPerIdReadWriteQueue.sync(flags: .barrier) {
self.spacesPerId = spacesPerId
}
}
}
// MARK: Public
/// The instance of `MXSpaceNotificationCounter` that computes the number of unread messages for each space
public let notificationCounter: MXSpaceNotificationCounter
/// List of `MXSpace` instances of the high level spaces.
public var rootSpaces: [MXSpace] {
return self.graph.rootSpaceIds.compactMap { spaceId in
self.getSpace(withId: spaceId)
}
}
/// List of `MXRoomSummary` of the high level spaces.
public var rootSpaceSummaries: [MXRoomSummary] {
return self.graph.rootSpaceIds.compactMap { spaceId in
self.session.roomSummary(withRoomId: spaceId)
}
}
/// List of `MXRoomSummary` of all spaces known by the user.
public var spaceSummaries: [MXRoomSummary] {
return self.graph.spaceRoomIds.compactMap { spaceId in
self.session.roomSummary(withRoomId: spaceId)
}
}
/// `true` if the `MXSpaceService` instance needs to be updated (e.g. the instance was busy while `handleSync` was called). `false` otherwise
public private(set) var needsUpdate: Bool = true
/// Set it to `false` if you want to temporarily disable graph update. This will be set automatically to `true` after next sync of the `MXSession`.
public var graphUpdateEnabled = true
/// List of ID of all the ancestors (direct parent spaces and parent spaces of the direct parent spaces) by room ID.
public var ancestorsPerRoomId: [String:Set<String>] {
return graph.ancestorsPerRoomId
}
/// The `MXSpaceService` instance is initialised if a previously saved graph has been restored or after the first sync.
public private(set) var isInitialised = false {
didSet {
if !oldValue && isInitialised {
self.completionQueue.async {
NotificationCenter.default.post(name: MXSpaceService.didInitialise, object: self)
}
}
}
}
// MARK: - Setup
public init(session: MXSession) {
self.session = session
self.notificationCounter = MXSpaceNotificationCounter(session: session)
self.roomTypeMapper = MXRoomTypeMapper(defaultRoomType: .room)
self.processingQueue = DispatchQueue(label: "org.matrix.sdk.MXSpaceService.processingQueue", attributes: .concurrent)
self.completionQueue = DispatchQueue.main
self.sdkProcessingQueue = DispatchQueue.main
self.spacesPerIdReadWriteQueue = DispatchQueue(
label: "org.matrix.sdk.MXSpaceService.spacesPerIdReadWriteQueue",
attributes: .concurrent
)
super.init()
self.registerNotificationObservers()
}
deinit {
unregisterNotificationObservers()
}
// MARK: - Public
/// close the service and free all data
public func close() {
self.isClosed = true
self.graph = MXSpaceGraphData()
self.notificationCounter.close()
self.isInitialised = false
self.completionQueue.async {
NotificationCenter.default.post(name: MXSpaceService.didBuildSpaceGraph, object: self)
}
}
/// Loads graph from the given store
public func loadData() {
self.processingQueue.async {
var _myUserId: String?
var _myDeviceId: String?
self.sdkProcessingQueue.sync {
_myUserId = self.session.myUserId
_myDeviceId = self.session.myDeviceId
}
guard let myUserId = _myUserId, let myDeviceId = _myDeviceId else {
MXLog.error("[MXSpaceService] loadData: Unexpectedly found nil for myUserId and/or myDeviceId")
return
}
let store = MXSpaceFileStore(userId: myUserId, deviceId: myDeviceId)
if let loadedGraph = store.loadSpaceGraphData() {
self.graph = loadedGraph
self.completionQueue.async {
self.isInitialised = true
self.notificationCounter.computeNotificationCount()
NotificationCenter.default.post(name: MXSpaceService.didBuildSpaceGraph, object: self)
}
}
}
}
/// Returns the set of direct parent IDs of the given room
/// - Parameters:
/// - roomId: ID of the room
/// - Returns: set of direct parent IDs of the given room. Empty set if the room has no parent.
public func directParentIds(ofRoomWithId roomId: String) -> Set<String> {
return graph.parentIdsPerRoomId[roomId] ?? Set()
}
/// Returns the set of direct parent IDs of the given room for which the room is suggested or not according to the request.
/// - Parameters:
/// - roomId: ID of the room
/// - suggested: If `true` the method will return the parent IDs where the room is suggested. If `false` the method will return the parent IDs where the room is NOT suggested
/// - Returns: set of direct parent IDs of the given room. Empty set if the room has no parent.
public func directParentIds(ofRoomWithId roomId: String, whereRoomIsSuggested suggested: Bool) -> Set<String> {
return directParentIds(ofRoomWithId: roomId).filter { spaceId in
guard let space = spacesPerId[spaceId] else {
return false
}
return (suggested && space.suggestedRoomIds.contains(roomId)) || (!suggested && !space.suggestedRoomIds.contains(roomId))
}
}
/// Allows to know if a given room is a descendant of a given space
/// - Parameters:
/// - roomId: ID of the room
/// - spaceId: ID of the space
/// - Returns: `true` if the room with the given ID is an ancestor of the space with the given ID .`false` otherwise
public func isRoom(withId roomId: String, descendantOf spaceId: String) -> Bool {
return self.graph.descendantsPerRoomId[spaceId]?.contains(roomId) ?? false
}
/// Allows to know if the room is oprhnaed (e.g. has no ancestor)
/// - Parameters:
/// - roomId: ID of the room
/// - Returns: `true` if the room with the given ID is orphaned .`false` otherwise
public func isOrphanedRoom(withId roomId: String) -> Bool {
return self.graph.orphanedRoomIds.contains(roomId) || self.graph.orphanedDirectRoomIds.contains(roomId)
}
/// Returns the first ancestor which is a root space
/// - Parameters:
/// - roomId: ID of the room
/// - Returns: Instance of the ancestor if found. `nil` otherwise
public func firstRootAncestorForRoom(withId roomId: String) -> MXSpace? {
if let ancestorIds = ancestorsPerRoomId[roomId] {
for ancestorId in ancestorIds where ancestorsPerRoomId[ancestorId] == nil {
return spacesPerId[ancestorId]
}
}
return nil
}
/// Handle a sync response
/// - Parameters:
/// - syncResponse: The sync response object
public func handleSyncResponse(_ syncResponse: MXSyncResponse) {
guard self.needsUpdate || !(syncResponse.rooms?.join?.isEmpty ?? true) || !(syncResponse.rooms?.invite?.isEmpty ?? true) || !(syncResponse.rooms?.leave?.isEmpty ?? true) || !(syncResponse.toDevice?.events.isEmpty ?? true) else {
return
}
self.buildGraph()
}
/// Create a space.
/// - Parameters:
/// - parameters: The parameters for space creation.
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
public func createSpace(with parameters: MXSpaceCreationParameters, completion: @escaping (MXResponse<MXSpace>) -> Void) -> MXHTTPOperation {
return self.session.createRoom(parameters: parameters) { (response) in
switch response {
case .success(let room):
let space: MXSpace = MXSpace(roomId: room.roomId, session:self.session)
self.completionQueue.async {
completion(.success(space))
}
case .failure(let error):
self.completionQueue.async {
completion(.failure(error))
}
}
}
}
/// Create a space shortcut.
/// - Parameters:
/// - name: The space name.
/// - topic: The space topic.
/// - isPublic: true to indicate to use public chat presets and join the space without invite or false to use private chat presets and join the space on invite.
/// - aliasLocalPart: local part of the alias
/// (e.g. for the alias "#my_alias:example.org", the local part is "my_alias")
/// - inviteArray: list of invited user IDs
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
public func createSpace(withName name: String?, topic: String?, isPublic: Bool, aliasLocalPart: String? = nil, inviteArray: [String]? = nil, completion: @escaping (MXResponse<MXSpace>) -> Void) -> MXHTTPOperation {
let parameters = MXSpaceCreationParameters()
parameters.name = name
parameters.topic = topic
parameters.preset = isPublic ? kMXRoomPresetPublicChat : kMXRoomPresetPrivateChat
parameters.visibility = isPublic ? kMXRoomDirectoryVisibilityPublic : kMXRoomDirectoryVisibilityPrivate
parameters.inviteArray = inviteArray
if isPublic {
parameters.roomAlias = aliasLocalPart
let guestAccessStateEvent = self.stateEventBuilder.buildGuestAccessEvent(withAccess: .canJoin)
parameters.addOrUpdateInitialStateEvent(guestAccessStateEvent)
let historyVisibilityStateEvent = self.stateEventBuilder.buildHistoryVisibilityEvent(withVisibility: .worldReadable)
parameters.addOrUpdateInitialStateEvent(historyVisibilityStateEvent)
parameters.powerLevelContentOverride?.invite = 0 // default
} else {
parameters.powerLevelContentOverride?.invite = 50 // moderator
}
return self.createSpace(with: parameters, completion: completion)
}
/// Get a space from a roomId.
/// - Parameter spaceId: The id of the space.
/// - Returns: A MXSpace with the associated roomId or null if room doesn't exists or the room type is not space.
public func getSpace(withId spaceId: String) -> MXSpace? {
var space: MXSpace?
spacesPerIdReadWriteQueue.sync {
space = self.spacesPerId[spaceId]
}
if space == nil, let newSpace = self.session.room(withRoomId: spaceId)?.toSpace() {
space = newSpace
spacesPerIdReadWriteQueue.sync(flags: .barrier) {
self.spacesPerId[spaceId] = newSpace
}
}
return space
}
/// Get the space children informations of a given space from the server.
/// - Parameters:
/// - spaceId: The room id of the queried space.
/// - suggestedOnly: If `true`, return only child events and rooms where the `m.space.child` event has `suggested: true`.
/// - limit: Optional. A limit to the maximum number of children to return per space. `-1` for no limit
/// - maxDepth: Optional. The maximum depth in the tree (from the root room) to return. `-1` for no limit
/// - paginationToken: Optional. Pagination token given to retrieve the next set of rooms.
/// - completion: A closure called when the operation completes.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
public func getSpaceChildrenForSpace(withId spaceId: String,
suggestedOnly: Bool,
limit: Int?,
maxDepth: Int?,
paginationToken: String?,
completion: @escaping (MXResponse<MXSpaceChildrenSummary>) -> Void) -> MXHTTPOperation {
return self.session.matrixRestClient.getSpaceChildrenForSpace(withId: spaceId, suggestedOnly: suggestedOnly, limit: limit, maxDepth: maxDepth, paginationToken: paginationToken) { (response) in
switch response {
case .success(let spaceChildrenResponse):
self.processingQueue.async { [weak self] in
guard let self = self else {
return
}
guard let rooms = spaceChildrenResponse.rooms else {
// We should have at least one room for the requested space
self.completionQueue.async {
completion(.failure(MXSpaceServiceError.spaceNotFound))
}
return
}
// Build room hierarchy and events
var childrenIdsPerChildRoomId: [String: [String]] = [:]
var parentIdsPerChildRoomId: [String:Set<String>] = [:]
var spaceChildEventsPerChildRoomId: [String:[String:Any]] = [:]
for room in spaceChildrenResponse.rooms ?? [] {
for event in room.childrenState ?? [] where event.wireContent.count > 0 {
spaceChildEventsPerChildRoomId[event.stateKey] = event.wireContent
var parentIds = parentIdsPerChildRoomId[event.stateKey] ?? Set()
parentIds.insert(room.roomId)
parentIdsPerChildRoomId[event.stateKey] = parentIds
var childrenIds = childrenIdsPerChildRoomId[room.roomId] ?? []
childrenIds.append(event.stateKey)
childrenIdsPerChildRoomId[room.roomId] = childrenIds
}
}
var spaceInfo: MXSpaceChildInfo?
if let rootSpaceChildSummaryResponse = rooms.first(where: { spaceResponse -> Bool in spaceResponse.roomId == spaceId}) {
spaceInfo = self.createSpaceChildInfo(with: rootSpaceChildSummaryResponse, childrenIds: childrenIdsPerChildRoomId[spaceId], childEvents: spaceChildEventsPerChildRoomId[spaceId])
}
// Build the child summaries of the queried space
let childInfos = self.spaceChildInfos(from: spaceChildrenResponse, excludedSpaceId: spaceId, childrenIdsPerChildRoomId: childrenIdsPerChildRoomId, parentIdsPerChildRoomId: parentIdsPerChildRoomId, spaceChildEventsPerChildRoomId: spaceChildEventsPerChildRoomId)
let spaceChildrenSummary = MXSpaceChildrenSummary(spaceInfo: spaceInfo, childInfos: childInfos, nextBatch: spaceChildrenResponse.nextBatch)
self.completionQueue.async {
completion(.success(spaceChildrenSummary))
}
}
case .failure(let error):
self.completionQueue.async {
completion(.failure(error))
}
}
}
}
// MARK: - Space graph computation
private class PrepareDataResult {
private var _spaces: [MXSpace] = []
private var _spacesPerId: [String : MXSpace] = [:]
private var _directRoomIdsPerMemberId: [String: [String]] = [:]
private var computingSpaces: Set<String> = Set()
private var computingDirectRooms: Set<String> = Set()
var spaces: [MXSpace] {
var result: [MXSpace] = []
self.serialQueue.sync {
result = self._spaces
}
return result
}
var spacesPerId: [String : MXSpace] {
var result: [String : MXSpace] = [:]
self.serialQueue.sync {
result = self._spacesPerId
}
return result
}
var directRoomIdsPerMemberId: [String: [String]] {
var result: [String: [String]] = [:]
self.serialQueue.sync {
result = self._directRoomIdsPerMemberId
}
return result
}
var isPreparingData = true
var isComputing: Bool {
var isComputing = false
self.serialQueue.sync {
isComputing = !self.computingSpaces.isEmpty || !self.computingDirectRooms.isEmpty
}
return isComputing
}
private let serialQueue = DispatchQueue(label: "org.matrix.sdk.MXSpaceService.PrepareDataResult.serialQueue")
func add(space: MXSpace) {
self.serialQueue.sync {
self._spaces.append(space)
self._spacesPerId[space.spaceId] = space
}
}
func add(directRoom: MXRoom, toUserWithId userId: String) {
self.serialQueue.sync {
var rooms = self._directRoomIdsPerMemberId[userId] ?? []
rooms.append(directRoom.roomId)
self._directRoomIdsPerMemberId[userId] = rooms
}
}
func setComputing(_ isComputing: Bool, forSpace space: MXSpace) {
self.serialQueue.sync {
if isComputing {
computingSpaces.insert(space.spaceId)
} else {
computingSpaces.remove(space.spaceId)
}
}
}
func setComputing(_ isComputing: Bool, forDirectRoom room: MXRoom) {
self.serialQueue.sync {
if isComputing {
computingDirectRooms.insert(room.roomId)
} else {
computingDirectRooms.remove(room.roomId)
}
}
}
}
/// Build the graph of rooms
private func buildGraph() {
guard !self.isClosed && !self.isGraphBuilding && self.graphUpdateEnabled else {
MXLog.debug("[MXSpaceService] buildGraph: aborted: graph is building or disabled")
self.needsUpdate = true
return
}
self.isGraphBuilding = true
self.needsUpdate = false
let startDate = Date()
MXLog.debug("[MXSpaceService] buildGraph: started")
var directRoomIds = Set<String>()
let roomIds: [String] = self.session.rooms.compactMap { room in
if room.isDirect {
directRoomIds.insert(room.roomId)
}
return room.roomId
}
let output = PrepareDataResult()
MXLog.debug("[MXSpaceService] buildGraph: preparing data for \(roomIds.count) rooms")
self.prepareData(with: roomIds, index: 0, output: output) { result in
guard !self.isClosed else {
return
}
MXLog.debug("[MXSpaceService] buildGraph: data prepared in \(Date().timeIntervalSince(startDate))")
self.computSpaceGraph(with: result, roomIds: roomIds, directRoomIds: directRoomIds) { graph in
guard !self.isClosed else {
return
}
self.graph = graph
MXLog.debug("[MXSpaceService] buildGraph: ended after \(Date().timeIntervalSince(startDate))s")
self.isGraphBuilding = false
self.isInitialised = true
NotificationCenter.default.post(name: MXSpaceService.didBuildSpaceGraph, object: self)
self.processingQueue.async {
var _myUserId: String?
var _myDeviceId: String?
self.sdkProcessingQueue.sync {
_myUserId = self.session.myUserId
_myDeviceId = self.session.myDeviceId
}
guard let myUserId = _myUserId, let myDeviceId = _myDeviceId else {
MXLog.error("[MXSpaceService] buildGraph: Unexpectedly found nil for myUserId and/or myDeviceId")
return
}
let store = MXSpaceFileStore(userId: myUserId, deviceId: myDeviceId)
if !store.store(spaceGraphData: self.graph) {
MXLog.error("[MXSpaceService] buildGraph: failed to store space graph")
}
// TODO improve updateNotificationsCount and call the method to all spaces once subspaces will be supported
self.notificationCounter.computeNotificationCount()
}
}
}
}
private func prepareData(with roomIds:[String], index: Int, output: PrepareDataResult, completion: @escaping (_ result: PrepareDataResult) -> Void) {
guard !self.isClosed else {
// abort prepareData if the service is closed. No completion needed
return
}
self.processingQueue.async {
guard index < roomIds.count else {
self.completionQueue.async {
output.isPreparingData = false
if !output.isComputing {
completion(output)
}
}
return
}
self.sdkProcessingQueue.async {
guard let room = self.session.room(withRoomId: roomIds[index]) else {
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
return
}
var space: MXSpace?
self.spacesPerIdReadWriteQueue.sync {
space = self.spacesPerId[room.roomId] ?? room.toSpace()
}
self.prepareData(with: roomIds, index: index, output: output, room: room, space: space, isRoomDirect: room.isDirect, directUserId: room.directUserId, completion: completion)
}
}
}
private func prepareData(with roomIds:[String], index: Int, output: PrepareDataResult, room: MXRoom, space _space: MXSpace?, isRoomDirect:Bool, directUserId _directUserId: String?, completion: @escaping (_ result: PrepareDataResult) -> Void) {
guard !self.isClosed else {
// abort prepareData if the service is closed. No completion needed
return
}
self.processingQueue.async {
if let space = _space {
output.setComputing(true, forSpace: space)
space.readChildRoomsAndMembers {
output.setComputing(false, forSpace: space)
if !output.isPreparingData && !output.isComputing {
guard !self.isClosed else {
// abort prepareData if the service is closed. No completion needed
return
}
completion(output)
}
}
output.add(space: space)
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
} else if isRoomDirect {
if let directUserId = _directUserId {
output.add(directRoom: room, toUserWithId: directUserId)
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
} else {
self.sdkProcessingQueue.async {
output.setComputing(true, forDirectRoom: room)
room.members { response in
guard !self.isClosed else {
// abort prepareData if the service is closed. No completion needed
return
}
guard let members = response.value as? MXRoomMembers else {
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
return
}
let membersId = members.members?.compactMap({ roomMember in
return roomMember.userId != self.session.myUserId ? roomMember.userId : nil
}) ?? []
self.processingQueue.async {
membersId.forEach { memberId in
output.add(directRoom: room, toUserWithId: memberId)
}
output.setComputing(false, forDirectRoom: room)
if !output.isPreparingData && !output.isComputing {
completion(output)
}
}
}
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
}
}
} else {
self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
}
}
}
private func computSpaceGraph(with result: PrepareDataResult, roomIds: [String], directRoomIds: Set<String>, completion: @escaping (_ graph: MXSpaceGraphData) -> Void) {
let startDate = Date()
MXLog.debug("[MXSpaceService] computSpaceGraph: started for \(roomIds.count) rooms, \(directRoomIds.count) direct rooms, \(result.spaces.count) spaces, \(result.spaces.reduce(0, { $0 + $1.childSpaces.count })) child spaces, \(result.spaces.reduce(0, { $0 + $1.childRoomIds.count })) child rooms, \(result.spaces.reduce(0, { $0 + $1.otherMembersId.count })) other members, \(result.directRoomIdsPerMemberId.count) members")
self.processingQueue.async {
var parentIdsPerRoomId: [String : Set<String>] = [:]
result.spaces.forEach { space in
space.updateChildSpaces(with: result.spacesPerId)
space.updateChildDirectRooms(with: result.directRoomIdsPerMemberId)
space.childRoomIds.forEach { roomId in
var parentIds = parentIdsPerRoomId[roomId] ?? Set<String>()
parentIds.insert(space.spaceId)
parentIdsPerRoomId[roomId] = parentIds
}
space.childSpaces.forEach { childSpace in
var parentIds = parentIdsPerRoomId[childSpace.spaceId] ?? Set<String>()
parentIds.insert(space.spaceId)
parentIdsPerRoomId[childSpace.spaceId] = parentIds
}
}
let rootSpaces = result.spaces.filter { space in
return parentIdsPerRoomId[space.spaceId] == nil
}.sorted { space1, space2 in
let _space1Order = space1.order
let _space2Order = space2.order
if let space1Order = _space1Order, let space2Order = _space2Order {
return space1Order <= space2Order
}
if _space1Order == nil && _space2Order == nil {
return space1.spaceId <= space2.spaceId
} else if _space1Order != nil && _space2Order == nil {
return true
} else {
return false
}
}
var ancestorsPerRoomId: [String: Set<String>] = [:]
var descendantsPerRoomId: [String: Set<String>] = [:]
rootSpaces.forEach { space in
self.buildRoomHierarchy(with: space, visitedSpaceIds: [], ancestorsPerRoomId: &ancestorsPerRoomId, descendantsPerRoomId: &descendantsPerRoomId)
}
var orphanedRoomIds: Set<String> = Set<String>()
var orphanedDirectRoomIds: Set<String> = Set<String>()
for roomId in roomIds {
let isRoomDirect = directRoomIds.contains(roomId)
if !isRoomDirect && parentIdsPerRoomId[roomId] == nil {
orphanedRoomIds.insert(roomId)
} else if isRoomDirect && parentIdsPerRoomId[roomId] == nil {
orphanedDirectRoomIds.insert(roomId)
}
}
let graph = MXSpaceGraphData(
spaceRoomIds: result.spaces.map({ space in
space.spaceId
}),
parentIdsPerRoomId: parentIdsPerRoomId,
ancestorsPerRoomId: ancestorsPerRoomId,
descendantsPerRoomId: descendantsPerRoomId,
rootSpaceIds: rootSpaces.map({ space in
space.spaceId
}),
orphanedRoomIds: orphanedRoomIds,
orphanedDirectRoomIds: orphanedDirectRoomIds)
MXLog.debug("[MXSpaceService] computSpaceGraph: space graph computed in \(Date().timeIntervalSince(startDate))s")
self.completionQueue.async {
completion(graph)
}
}
}
private func buildRoomHierarchy(with space: MXSpace, visitedSpaceIds: [String], ancestorsPerRoomId: inout [String: Set<String>], descendantsPerRoomId: inout [String: Set<String>]) {
var visitedSpaceIds = visitedSpaceIds
visitedSpaceIds.append(space.spaceId)
space.childRoomIds.forEach { roomId in
var parentIds = ancestorsPerRoomId[roomId] ?? Set<String>()
visitedSpaceIds.forEach { spaceId in
parentIds.insert(spaceId)
var descendantIds = descendantsPerRoomId[spaceId] ?? Set<String>()
descendantIds.insert(roomId)
descendantsPerRoomId[spaceId] = descendantIds
}
ancestorsPerRoomId[roomId] = parentIds
}
space.childSpaces.forEach { childSpace in
buildRoomHierarchy(with: childSpace, visitedSpaceIds: visitedSpaceIds, ancestorsPerRoomId: &ancestorsPerRoomId, descendantsPerRoomId: &descendantsPerRoomId)
}
}
// MARK: - Notification handling
private func registerNotificationObservers() {
self.sessionStateDidChangeObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.mxSessionStateDidChange, object: session, queue: nil) { [weak self] notification in
guard let session = self?.session, session.state == .storeDataReady else {
return
}
self?.loadData()
}
}
private func unregisterNotificationObservers() {
if let observer = self.sessionStateDidChangeObserver {
NotificationCenter.default.removeObserver(observer)
}
}
// MARK: - Private
private func createRoomSummary(with spaceChildSummaryResponse: MXSpaceChildSummaryResponse) -> MXRoomSummary {
let roomId = spaceChildSummaryResponse.roomId
let roomTypeString = spaceChildSummaryResponse.roomType
let roomSummary: MXRoomSummary = MXRoomSummary(roomId: roomId, andMatrixSession: nil)
roomSummary.roomTypeString = roomTypeString
roomSummary.roomType = self.roomTypeMapper.roomType(from: roomTypeString)
let joinedMembersCount = UInt(spaceChildSummaryResponse.numJoinedMembers)
let membersCount = MXRoomMembersCount()
membersCount.joined = joinedMembersCount
membersCount.members = joinedMembersCount
roomSummary.membersCount = membersCount
roomSummary.displayname = spaceChildSummaryResponse.name
roomSummary.topic = spaceChildSummaryResponse.topic
roomSummary.avatar = spaceChildSummaryResponse.avatarUrl
roomSummary.isEncrypted = false
return roomSummary
}
private func spaceChildInfos(from spaceChildrenResponse: MXSpaceChildrenResponse, excludedSpaceId: String, childrenIdsPerChildRoomId: [String: [String]], parentIdsPerChildRoomId: [String:Set<String>], spaceChildEventsPerChildRoomId: [String:[String:Any]]) -> [MXSpaceChildInfo] {
guard let spaceChildSummaries = spaceChildrenResponse.rooms else {
return []
}
let childInfos: [MXSpaceChildInfo] = spaceChildSummaries.compactMap { (spaceChildSummaryResponse) -> MXSpaceChildInfo? in
let spaceId = spaceChildSummaryResponse.roomId
guard spaceId != excludedSpaceId else {
return nil
}
return self.createSpaceChildInfo(with: spaceChildSummaryResponse, childrenIds: childrenIdsPerChildRoomId[spaceId], childEvents: spaceChildEventsPerChildRoomId[spaceId])
}
return childInfos
}
private func createSpaceChildInfo(with spaceChildSummaryResponse: MXSpaceChildSummaryResponse, childrenIds: [String]?, childEvents: [String:Any]?) -> MXSpaceChildInfo {
let roomTypeString = spaceChildSummaryResponse.roomType
let roomType = self.roomTypeMapper.roomType(from: roomTypeString)
return MXSpaceChildInfo(childRoomId: spaceChildSummaryResponse.roomId,
isKnown: true,
roomTypeString: roomTypeString,
roomType: roomType,
name: spaceChildSummaryResponse.name,
topic: spaceChildSummaryResponse.topic,
canonicalAlias: spaceChildSummaryResponse.canonicalAlias,
avatarUrl: spaceChildSummaryResponse.avatarUrl,
activeMemberCount: spaceChildSummaryResponse.numJoinedMembers,
autoJoin: childEvents?[kMXEventTypeStringAutoJoinKey] as? Bool ?? false,
suggested: childEvents?[kMXEventTypeStringSuggestedKey] as? Bool ?? false,
childrenIds: childrenIds ?? [])
}
}
// MARK: - Objective-C interface
extension MXSpaceService {
/// Create a space.
/// - Parameters:
/// - parameters: The parameters for space creation.
/// - success: A closure called when the operation is complete.
/// - failure: A closure called when the operation fails.
/// - Returns: a `MXHTTPOperation` instance.
@objc public func createSpace(with parameters: MXSpaceCreationParameters, success: @escaping (MXSpace) -> Void, failure: @escaping (Error) -> Void) -> MXHTTPOperation {
return self.createSpace(with: parameters) { (response) in
uncurryResponse(response, success: success, failure: failure)
}
}
/// Create a space shortcut.
/// - Parameters:
/// - name: The space name.
/// - topic: The space topic.
/// - isPublic: true to indicate to use public chat presets and join the space without invite or false to use private chat presets and join the space on invite.
/// - aliasLocalPart: local part of the alias
/// (e.g. for the alias "#my_alias:example.org", the local part is "my_alias")
/// - inviteArray: list of invited user IDs
/// - success: A closure called when the operation is complete.
/// - failure: A closure called when the operation fails.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
@objc public func createSpace(withName name: String, topic: String?, isPublic: Bool, aliasLocalPart: String?, inviteArray: [String]?, success: @escaping (MXSpace) -> Void, failure: @escaping (Error) -> Void) -> MXHTTPOperation {
return self.createSpace(withName: name, topic: topic, isPublic: isPublic, aliasLocalPart: aliasLocalPart, inviteArray: inviteArray) { (response) in
uncurryResponse(response, success: success, failure: failure)
}
}
/// Get the space children informations of a given space from the server.
/// - Parameters:
/// - spaceId: The room id of the queried space.
/// - suggestedOnly: If `true`, return only child events and rooms where the `m.space.child` event has `suggested: true`.
/// - limit: Optional. A limit to the maximum number of children to return per space. `-1` for no limit
/// - maxDepth: Optional. The maximum depth in the tree (from the root room) to return. `-1` for no limit
/// - paginationToken: Optional. Pagination token given to retrieve the next set of rooms.
/// - success: A closure called when the operation is complete.
/// - failure: A closure called when the operation fails.
/// - Returns: a `MXHTTPOperation` instance.
@discardableResult
@objc public func getSpaceChildrenForSpace(withId spaceId: String, suggestedOnly: Bool, limit: Int, maxDepth: Int, paginationToken: String?, success: @escaping (MXSpaceChildrenSummary) -> Void, failure: @escaping (Error) -> Void) -> MXHTTPOperation {
return self.getSpaceChildrenForSpace(withId: spaceId, suggestedOnly: suggestedOnly, limit: limit, maxDepth: maxDepth, paginationToken: paginationToken) { (response) in
uncurryResponse(response, success: success, failure: failure)
}
}
}
// MARK: - Internal room additions
extension MXRoom {
func toSpace() -> MXSpace? {
guard let summary = self.summary, summary.roomType == .space else {
return nil
}
return MXSpace(roomId: self.roomId, session: self.mxSession)
}
}
| apache-2.0 | 2a9a2b9b83f148ba61d9f0362f1961d8 | 44.49277 | 431 | 0.593868 | 5.537233 | false | false | false | false |
Turistforeningen/SjekkUT | ios/SjekkUt/views/project/ProjectDatesCell.swift | 1 | 1578 | //
// StartStopCell.swift
// SjekkUt
//
// Created by Henrik Hartz on 31.03.2017.
// Copyright © 2017 Den Norske Turistforening. All rights reserved.
//
import Foundation
class ProjectDatesCell: UICollectionViewCell {
@IBOutlet var durationLabel: DntLabel!
let dateFormat = DateFormatter()
var project:Project? {
didSet {
dateFormat.dateStyle = .medium
dateFormat.timeStyle = .none
var durationText = ""
switch (project?.start, project?.stop) {
case (nil, nil):
durationText = "The list is always active"
case (nil, let stop):
let stopString = dateFormat.string(from: stop!)
durationText = String.localizedStringWithFormat(NSLocalizedString("The list is active until %@", comment: "list duration only stop"), stopString)
case (let start, nil):
let startString = dateFormat.string(from: start!)
durationText = String.localizedStringWithFormat(NSLocalizedString("The list active from %@", comment: "list duration only start"), startString)
case (let start, let stop):
let startString = dateFormat.string(from: start!)
let stopString = dateFormat.string(from: stop!)
durationText = String.localizedStringWithFormat(NSLocalizedString("The list is active in the period %@-%@", comment: "list duration start and stop"), startString, stopString)
}
durationLabel.text = durationText
}
}
}
| mit | e2e1e875bf1b6d5eddd682fcfc877ff7 | 40.5 | 190 | 0.622067 | 5.1875 | false | false | false | false |
shitoudev/v2ex | v2exKit/STInsetLabel.swift | 1 | 939 | //
// STInsetLabel.swift
// v2ex
//
// Created by zhenwen on 7/31/15.
// Copyright (c) 2015 zhenwen. All rights reserved.
//
import UIKit
class STInsetLabel: UILabel {
var padding = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) //UIEdgeInsetsZero
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
internal convenience init(frame: CGRect, inset:UIEdgeInsets) {
self.init(frame: frame)
self.padding = inset
}
override func drawTextInRect(rect: CGRect) {
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, padding))
}
override func intrinsicContentSize() -> CGSize {
var size = super.intrinsicContentSize()
size.width += padding.left + padding.right
size.height += padding.top + padding.bottom
return size
}
} | mit | 74d61256776be6385ebbcbba9b6c1ea7 | 23.736842 | 89 | 0.630458 | 4.082609 | false | false | false | false |
benlangmuir/swift | test/SILGen/class_resilience.swift | 22 | 2399 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-emit-silgen -module-name class_resilience -I %t -enable-library-evolution %s | %FileCheck %s
import resilient_class
// Accessing final property of resilient class from different resilience domain
// through accessor
// CHECK-LABEL: sil [ossa] @$s16class_resilience20finalPropertyOfOtheryy010resilient_A022ResilientOutsideParentCF
// CHECK: function_ref @$s15resilient_class22ResilientOutsideParentC13finalPropertySSvg
public func finalPropertyOfOther(_ other: ResilientOutsideParent) {
_ = other.finalProperty
}
public class MyResilientClass {
public final var finalProperty: String = "MyResilientClass.finalProperty"
}
// Accessing final property of resilient class from my resilience domain
// directly
// CHECK-LABEL: sil [ossa] @$s16class_resilience19finalPropertyOfMineyyAA16MyResilientClassCF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $MyResilientClass):
// CHECK: ref_element_addr [[ARG]] : $MyResilientClass, #MyResilientClass.finalProperty
// CHECK: } // end sil function '$s16class_resilience19finalPropertyOfMineyyAA16MyResilientClassCF'
public func finalPropertyOfMine(_ other: MyResilientClass) {
_ = other.finalProperty
}
class SubclassOfOutsideChild : ResilientOutsideChild {
override func method() {}
func newMethod() {}
}
// Note: no entries for [inherited] methods
// CHECK-LABEL: sil_vtable SubclassOfOutsideChild {
// CHECK-NEXT: #ResilientOutsideParent.init!allocator: (ResilientOutsideParent.Type) -> () -> ResilientOutsideParent : @$s16class_resilience22SubclassOfOutsideChildCACycfC [override]
// CHECK-NEXT: #ResilientOutsideParent.method: (ResilientOutsideParent) -> () -> () : @$s16class_resilience22SubclassOfOutsideChildC6methodyyF [override]
// CHECK-NEXT: #SubclassOfOutsideChild.newMethod: (SubclassOfOutsideChild) -> () -> () : @$s16class_resilience22SubclassOfOutsideChildC9newMethodyyF
// CHECK-NEXT: #SubclassOfOutsideChild.deinit!deallocator: @$s16class_resilience22SubclassOfOutsideChildCfD
// CHECK-NEXT: }
| apache-2.0 | fc519256b77af0c480d805871fb82036 | 48.979167 | 188 | 0.78366 | 4.194056 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Browser/SearchEngines/OpenSearchEngine.swift | 2 | 7021 | // 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 UIKit
class OpenSearchEngine: NSObject, NSCoding {
struct UX {
static let preferredIconSize = 30
}
let shortName: String
let engineID: String?
let image: UIImage
let isCustomEngine: Bool
let searchTemplate: String
private let suggestTemplate: String?
private let searchTermComponent = "{searchTerms}"
private let localeTermComponent = "{moz:locale}"
private lazy var searchQueryComponentKey: String? = self.getQueryArgFromTemplate()
private let googleEngineID = "google-b-1-m"
var headerSearchTitle: String {
guard engineID != googleEngineID else {
return .Search.GoogleEngineSectionTitle
}
return String(format: .Search.EngineSectionTitle, shortName)
}
enum CodingKeys: String, CodingKey {
case isCustomEngine
case searchTemplate
case shortName
case image
case engineID
}
init(engineID: String?,
shortName: String,
image: UIImage,
searchTemplate: String,
suggestTemplate: String?,
isCustomEngine: Bool) {
self.shortName = shortName
self.image = image
self.searchTemplate = searchTemplate
self.suggestTemplate = suggestTemplate
self.isCustomEngine = isCustomEngine
self.engineID = engineID
}
// MARK: - NSCoding
required init?(coder aDecoder: NSCoder) {
let isCustomEngine = aDecoder.decodeAsBool(forKey: CodingKeys.isCustomEngine.rawValue)
guard let searchTemplate = aDecoder.decodeObject(forKey: CodingKeys.searchTemplate.rawValue) as? String,
let shortName = aDecoder.decodeObject(forKey: CodingKeys.shortName.rawValue) as? String,
let image = aDecoder.decodeObject(forKey: CodingKeys.image.rawValue) as? UIImage else {
assertionFailure()
return nil
}
self.searchTemplate = searchTemplate
self.shortName = shortName
self.isCustomEngine = isCustomEngine
self.image = image
self.engineID = aDecoder.decodeObject(forKey: CodingKeys.engineID.rawValue) as? String
self.suggestTemplate = nil
}
func encode(with aCoder: NSCoder) {
aCoder.encode(searchTemplate, forKey: CodingKeys.searchTemplate.rawValue)
aCoder.encode(shortName, forKey: CodingKeys.shortName.rawValue)
aCoder.encode(isCustomEngine, forKey: CodingKeys.isCustomEngine.rawValue)
aCoder.encode(image, forKey: CodingKeys.image.rawValue)
aCoder.encode(engineID, forKey: CodingKeys.engineID.rawValue)
}
// MARK: - Public
/// Returns the search URL for the given query.
func searchURLForQuery(_ query: String) -> URL? {
return getURLFromTemplate(searchTemplate, query: query)
}
/// Returns the search suggestion URL for the given query.
func suggestURLForQuery(_ query: String) -> URL? {
if let suggestTemplate = suggestTemplate {
return getURLFromTemplate(suggestTemplate, query: query)
}
return nil
}
/// Returns the query that was used to construct a given search URL
func queryForSearchURL(_ url: URL?) -> String? {
guard isSearchURLForEngine(url), let key = searchQueryComponentKey else { return nil }
if let value = url?.getQuery()[key] {
return value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
} else {
// If search term could not found in query, it may be exist inside fragment
var components = URLComponents()
components.query = url?.fragment?.removingPercentEncoding
guard let value = components.url?.getQuery()[key] else { return nil }
return value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
}
}
// MARK: - Private
/// Return the arg that we use for searching for this engine
/// Problem: the search terms may not be a query arg, they may be part of the URL - how to deal with this?
private func getQueryArgFromTemplate() -> String? {
// we have the replace the templates SearchTermComponent in order to make the template
// a valid URL, otherwise we cannot do the conversion to NSURLComponents
// and have to do flaky pattern matching instead.
let placeholder = "PLACEHOLDER"
let template = searchTemplate.replacingOccurrences(of: searchTermComponent, with: placeholder)
var components = URLComponents(string: template)
if let retVal = extractQueryArg(in: components?.queryItems, for: placeholder) {
return retVal
} else {
// Query arg may be exist inside fragment
components = URLComponents()
components?.query = URL(string: template)?.fragment
return extractQueryArg(in: components?.queryItems, for: placeholder)
}
}
private func extractQueryArg(in queryItems: [URLQueryItem]?, for placeholder: String) -> String? {
let searchTerm = queryItems?.filter { item in
return item.value == placeholder
}
return searchTerm?.first?.name
}
/// Check that the URL host contains the name of the search engine somewhere inside it
private func isSearchURLForEngine(_ url: URL?) -> Bool {
guard let urlHost = url?.shortDisplayString,
let queryEndIndex = searchTemplate.range(of: "?")?.lowerBound,
let templateURL = URL(string: String(searchTemplate[..<queryEndIndex])) else { return false }
return urlHost == templateURL.shortDisplayString
}
private func getURLFromTemplate(_ searchTemplate: String, query: String) -> URL? {
if let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: .SearchTermsAllowed) {
// Escape the search template as well in case it contains not-safe characters like symbols
let templateAllowedSet = NSMutableCharacterSet()
templateAllowedSet.formUnion(with: .URLAllowed)
// Allow brackets since we use them in our template as our insertion point
templateAllowedSet.formUnion(with: CharacterSet(charactersIn: "{}"))
if let encodedSearchTemplate = searchTemplate.addingPercentEncoding(withAllowedCharacters: templateAllowedSet as CharacterSet) {
let localeString = Locale.current.identifier
let urlString = encodedSearchTemplate
.replacingOccurrences(of: searchTermComponent, with: escapedQuery, options: .literal, range: nil)
.replacingOccurrences(of: localeTermComponent, with: localeString, options: .literal, range: nil)
return URL(string: urlString)
}
}
return nil
}
}
| mpl-2.0 | f2dafa9eee49f78860fa162ab92e46e8 | 40.3 | 140 | 0.665717 | 5.327011 | false | false | false | false |
sysatom/OSC | OSC/Logger.swift | 1 | 2359 | //
// Logger.swift
// OSC
//
// Created by yuan on 15/11/17.
// Copyright © 2015年 yuan. All rights reserved.
//
import UIKit
class Logger {
let destination: NSURL
lazy private var dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter
}()
lazy private var fileHandle: NSFileHandle? = {
if let path = self.destination.path {
NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil)
var error: NSError?
if let fileHandle = try? NSFileHandle(forWritingToURL: self.destination) {
print("Successfully logging to: \(path)")
return fileHandle
} else {
print("Serious error in logging: could not open path to log file. \(error).")
}
} else {
print("Serious error in logging: specified destination (\(self.destination)) does not appear to have a path component.")
}
return nil
}()
init(destination: NSURL) {
self.destination = destination
}
deinit {
fileHandle?.closeFile()
}
func log(message: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) {
let logMessage = stringRepresentation(message, function: function, file: file, line: line)
printToConsole(logMessage)
printToDestination(logMessage)
}
}
private extension Logger {
func stringRepresentation(message: String, function: String, file: String, line: Int) -> String {
let dateString = dateFormatter.stringFromDate(NSDate())
let file = NSURL(fileURLWithPath: file).lastPathComponent ?? "(Unknown File)"
return "\(dateString) [\(file):\(line)] \(function): \(message)\n"
}
func printToConsole(logMessage: String) {
print(logMessage)
}
func printToDestination(logMessage: String) {
if let data = logMessage.dataUsingEncoding(NSUTF8StringEncoding) {
fileHandle?.writeData(data)
} else {
print("Serious error in logging: could not encode logged string into data.")
}
}
} | mit | f8099c80fa2c6ad384c831089ff1ca01 | 31.287671 | 132 | 0.60399 | 4.91858 | false | false | false | false |
jrmsklar/SwiftPasscodeLock | PasscodeLock/PasscodeLockPresenter.swift | 1 | 4004 | //
// PasscodeLockPresenter.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/29/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
public class PasscodeLockPresenter {
private var mainWindow: UIWindow?
private lazy var passcodeLockWindow: UIWindow = {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.windowLevel = 0
window.makeKeyAndVisible()
return window
}()
private let passcodeConfiguration: PasscodeLockConfigurationType
public var isPasscodePresented = false
public let passcodeLockVC: PasscodeLockViewController
public init(mainWindow window: UIWindow?, configuration: PasscodeLockConfigurationType, viewController: PasscodeLockViewController) {
mainWindow = window
mainWindow?.windowLevel = 1
passcodeConfiguration = configuration
passcodeLockVC = viewController
}
public convenience init(mainWindow window: UIWindow?, configuration: PasscodeLockConfigurationType) {
let passcodeLockVC = PasscodeLockViewController(state: .EnterPasscode, configuration: configuration)
self.init(mainWindow: window, configuration: configuration, viewController: passcodeLockVC)
}
// HACK: below function that handles not presenting the keyboard in case Passcode is presented
// is a smell in the code that had to be introduced for iOS9 where Apple decided to move the keyboard
// in a UIRemoteKeyboardWindow.
// This doesn't allow our Passcode Lock window to move on top of keyboard.
// Setting a higher windowLevel to our window or even trying to change keyboards'
// windowLevel has been tried without luck.
//
// Revise in a later version and remove the hack if not needed
func toggleKeyboardVisibility(hide hide: Bool) {
if let keyboardWindow = UIApplication.sharedApplication().windows.last
where keyboardWindow.description.hasPrefix("<UIRemoteKeyboardWindow")
{
keyboardWindow.alpha = hide ? 0.0 : 1.0
}
}
public func presentPasscodeLock() {
guard passcodeConfiguration.repository.hasPasscode else { return }
guard !isPasscodePresented else { return }
isPasscodePresented = true
passcodeLockWindow.windowLevel = 2
toggleKeyboardVisibility(hide: true)
let userDismissCompletionCallback = passcodeLockVC.dismissCompletionCallback
passcodeLockVC.dismissCompletionCallback = { [weak self] in
userDismissCompletionCallback?()
self?.dismissPasscodeLock()
}
passcodeLockWindow.rootViewController = passcodeLockVC
}
public func dismissPasscodeLock(animated animated: Bool = true) {
isPasscodePresented = false
mainWindow?.windowLevel = 1
mainWindow?.makeKeyAndVisible()
if animated {
UIView.animateWithDuration(
0.5,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: [.CurveEaseInOut],
animations: { [weak self] in
self?.passcodeLockWindow.alpha = 0
},
completion: { [weak self] _ in
self?.passcodeLockWindow.windowLevel = 0
self?.passcodeLockWindow.rootViewController = nil
self?.passcodeLockWindow.alpha = 1
self?.toggleKeyboardVisibility(hide: false)
}
)
} else {
passcodeLockWindow.windowLevel = 0
passcodeLockWindow.rootViewController = nil
toggleKeyboardVisibility(hide: false)
}
}
}
| mit | 71d0196a9f00d830db55371820243871 | 34.114035 | 137 | 0.619785 | 6.206202 | false | true | false | false |
gregomni/swift | test/Generics/concrete_conformances_in_protocol.swift | 2 | 1938 | // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
// rdar://problem/88135912
// XFAIL: *
protocol P {
associatedtype T
}
struct S : P {
typealias T = S
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).R0@
// CHECK-LABEL: Requirement signature: <Self where Self.[R0]A == S>
protocol R0 {
associatedtype A where A : P, A == S
}
////
struct G<T> : P {}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).R1@
// CHECK-LABEL: Requirement signature: <Self where Self.[R1]B == G<Self.[R1]A>>
protocol R1 {
associatedtype A
associatedtype B where B : P, B == G<A>
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).R2@
// CHECK-LABEL: Requirement signature: <Self where Self.[R2]A == G<Self.[R2]B>>
protocol R2 {
associatedtype A where A : P, A == G<B>
associatedtype B
}
////
protocol PP {
associatedtype T : P
}
struct GG<T : P> : PP {}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR3@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR3]A : P, Self.[RR3]B == GG<Self.[RR3]A>>
protocol RR3 {
associatedtype A : P
associatedtype B where B : PP, B == GG<A>
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR4@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR4]A == GG<Self.[RR4]B>, Self.[RR4]B : P>
protocol RR4 {
associatedtype A where A : PP, A == GG<B>
associatedtype B : P
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR5@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR5]A : PP, Self.[RR5]B == GG<Self.[RR5]A.[PP]T>>
protocol RR5 {
associatedtype A : PP
associatedtype B where B : PP, B == GG<A.T>
}
// CHECK-LABEL: concrete_conformances_in_protocol.(file).RR6@
// CHECK-LABEL: Requirement signature: <Self where Self.[RR6]A == GG<Self.[RR6]B.[PP]T>, Self.[RR6]B : PP>
protocol RR6 {
associatedtype A where A : PP, A == GG<B.T>
associatedtype B : PP
}
| apache-2.0 | 1c109dad010de2947f7d08de90630e8d | 23.846154 | 106 | 0.664087 | 2.936364 | false | false | false | false |
gregomni/swift | test/Interop/Cxx/namespace/classes-module-interface.swift | 8 | 2340 | // RUN: %target-swift-ide-test -print-module -module-to-print=Classes -I %S/Inputs -source-filename=x -enable-experimental-cxx-interop | %FileCheck %s
// CHECK: enum ClassesNS1 {
// CHECK-NEXT: struct ForwardDeclaredStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: enum ClassesNS2 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: struct ForwardDeclaredStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: enum ClassesNS3 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: typealias GlobalAliasToNS1 = ClassesNS1
// CHECK-NEXT: enum ClassesNS4 {
// CHECK-NEXT: typealias AliasToGlobalNS1 = ClassesNS1
// CHECK-NEXT: typealias AliasToGlobalNS2 = ClassesNS1.ClassesNS2
// CHECK-NEXT: enum ClassesNS5 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToInnerNS5 = ClassesNS4.ClassesNS5
// CHECK-NEXT: typealias AliasToNS2 = ClassesNS1.ClassesNS2
// CHECK-NEXT: typealias AliasChainToNS1 = ClassesNS1
// CHECK-NEXT: typealias AliasChainToNS2 = ClassesNS1.ClassesNS2
// CHECK-NEXT: }
// CHECK-NEXT: enum ClassesNS5 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToAnotherNS5 = ClassesNS4.ClassesNS5
// CHECK-NEXT: enum ClassesNS5 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToNS5NS5 = ClassesNS5.ClassesNS5
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToGlobalNS5 = ClassesNS5
// CHECK-NEXT: typealias AliasToLocalNS5 = ClassesNS5.ClassesNS5
// CHECK-NEXT: typealias AliasToNS5 = ClassesNS5.ClassesNS5
// CHECK-NEXT: }
| apache-2.0 | 356ee82bac17c920cdcec117720cf85c | 40.052632 | 150 | 0.673932 | 3.518797 | false | false | false | false |
fcanas/Formulary | Formulary/Forms/FormViewController.swift | 1 | 10306 | //
// FormViewController.swift
// Formulary
//
// Created by Fabian Canas on 1/16/15.
// Copyright (c) 2015 Fabian Canas. All rights reserved.
//
import UIKit
/**
* `FormViewController` is a descendent of `UIViewController` used to display
* a `Form` in a UIKit application.
*
* In order to show a `Form` to a user, you will typically create a `Form`,
* instantiate a `FormViewController`, set the `FormViewController`'s `form`
* property, and present the `FormViewController`.
*
* Where a `Form` refers to both the schema and data an application wishes to
* obtain from a user, the `FormViewController` is an adapter that manages the
* visual presentation of a `Form`, manages the lifecycle of interaction with
* the `Form`, and is a key point of interaction with the rest of an iOS
* application.
*
* - seealso: `Form`
*/
open class FormViewController: UIViewController {
fileprivate var dataSource: FormDataSource?
/**
* The `Form` that the `FormViewController` presents to the user
*
* - seealso: `Form`
*/
open var form :Form {
didSet {
form.editingEnabled = editingEnabled
dataSource = FormDataSource(form: form, tableView: tableView)
tableView?.dataSource = dataSource
}
}
/**
* The UITableView instance the `FormViewController` will populate with
* `Form` data.
*
* If this property is `nil` when `viewDidLoad` is called, the
* `FormViewController` will create a `UITableView` and add it to its view
* hierarchy.
*/
open var tableView: UITableView!
/**
* The style of `tableView` to create in `viewDidLoad` if no `tableView`
* exists.
*
* Setting `tableViewStyle` only has an effect if set before `viewDidLoad`
* is called and the `FormViewController` does not yet have a `tableView`.
* Otherwise its value is never read.
*
* - seealso: tableView
*/
open var tableViewStyle: UITableViewStyle = .grouped
/**
* Enables or disables editing of the represented `Form`.
*/
open var editingEnabled :Bool = true {
didSet {
self.form.editingEnabled = editingEnabled
if isEditing == false {
self.tableView?.firstResponder()?.resignFirstResponder()
}
self.tableView?.reloadData()
}
}
lazy fileprivate var tableViewDelegate :FormViewControllerTableDelegate = {
return FormViewControllerTableDelegate(formViewController: self)
}()
/**
* Returns a newly initialized form view controller with the nib file in the
* specified bundle and ready to represent the specified Form.
*
* - parameters:
* - form: The Form to show in the FormViewController
* - nibName: The name of the nib file to associate with the view controller. The nib file name should not contain any leading path information. If you specify nil, the nibName property is set to nil.
* - nibBundle: The bundle in which to search for the nib file. This method looks for the nib file in the bundle's language-specific project directories first, followed by the Resources directory. If this parameter is nil, the method uses the heuristics described below to locate the nib file.
*/
public init(form: Form = Form(sections: []), nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self.form = form
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/**
* Returns a newly initialized FormViewController with a Form
*
* - parameter: form The Form to show in the FormViewController
*/
public convenience init(form: Form) {
self.init(form: form, nibName: nil, bundle: nil)
}
/**
* Returns a newly initialized FormViewController with an empty Form.
*
* Use this convenience initializer for compatibility with generic UIKit
* view controllers. It is perfectly acceptable to create a Form and assign
* it to the FormViewController after initialization.
*/
public override convenience init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self.init(form: Form(sections: []), nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/**
* Returns a newly initialized FormViewController with an empty Form.
*
* Use this convenience initializer for compatibility with generic UIKit
* view controllers. It is perfectly acceptable to create a Form and assign
* it to the FormViewController after initialization.
*/
public required init?(coder aDecoder: NSCoder) {
form = Form(sections: [])
super.init(coder: aDecoder)
}
fileprivate func link(_ form: Form, table: UITableView) {
dataSource = FormDataSource(form: form, tableView: tableView)
tableView.dataSource = dataSource
}
/**
* Called by UIKit after the controller's view is loaded into memory.
*
* FormViewController implements custom logic to ensure that a Form can be
* correctly displayed regarless of how it was constructed. This includes
* creating and configuring a Table View and constructing a private data
* source for the table view.
*
* You typically will not need to override -viewDidLoad in subclasses of
* FormViewController. But if you do, things will work better if you invoke
* the superclass's implementation first.
*/
override open func viewDidLoad() {
super.viewDidLoad()
if tableView == nil {
tableView = UITableView(frame: view.bounds, style: tableViewStyle)
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
if tableView.superview == nil {
view.addSubview(tableView)
}
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 60
tableView.delegate = tableViewDelegate
dataSource = FormDataSource(form: form, tableView: tableView)
tableView.dataSource = dataSource
}
/**
* If you override this method, you must call super at some point in your
* implementation.
*/
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(FormViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
/**
* If you override this method, you must call super at some point in your
* implementation.
*/
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
}
private extension FormViewController {
@objc func keyboardWillShow(_ notification: Notification) {
if let cell = tableView.firstResponder()?.containingCell(),
let selectedIndexPath = tableView.indexPath(for: cell) {
let keyboardInfo = KeyboardNotification(notification)
var keyboardEndFrame = keyboardInfo.screenFrameEnd
keyboardEndFrame = view.window!.convert(keyboardEndFrame, to: view)
var contentInset = tableView.contentInset
var scrollIndicatorInsets = tableView.scrollIndicatorInsets
contentInset.bottom = tableView.frame.origin.y + self.tableView.frame.size.height - keyboardEndFrame.origin.y
scrollIndicatorInsets.bottom = tableView.frame.origin.y + self.tableView.frame.size.height - keyboardEndFrame.origin.y
UIView.beginAnimations("keyboardAnimation", context: nil)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyboardInfo.animationCurve) ?? .easeInOut)
UIView.setAnimationDuration(keyboardInfo.animationDuration)
tableView.contentInset = contentInset
tableView.scrollIndicatorInsets = scrollIndicatorInsets
tableView.scrollToRow(at: selectedIndexPath, at: .none, animated: true)
UIView.commitAnimations()
}
}
@objc func keyboardWillHide(_ notification: Notification) {
let keyboardInfo = KeyboardNotification(notification)
var contentInset = tableView.contentInset
var scrollIndicatorInsets = tableView.scrollIndicatorInsets
contentInset.bottom = 0
scrollIndicatorInsets.bottom = 0
UIView.beginAnimations("keyboardAnimation", context: nil)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: keyboardInfo.animationCurve) ?? .easeInOut)
UIView.setAnimationDuration(keyboardInfo.animationDuration)
tableView.contentInset = contentInset
tableView.scrollIndicatorInsets = scrollIndicatorInsets
UIView.commitAnimations()
}
}
private class FormViewControllerTableDelegate :NSObject, UITableViewDelegate {
weak var formViewController :FormViewController?
init(formViewController :FormViewController) {
super.init()
self.formViewController = formViewController
}
@objc func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
formViewController?.tableView.firstResponder()?.resignFirstResponder()
}
@objc func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if let cell = cell as? FormTableViewCell {
cell.formRow?.action?(nil)
cell.action?(nil)
}
if let cell = cell as? ControllerSpringingCell, let controller = cell.nestedViewController {
formViewController?.navigationController?.pushViewController(controller(), animated: true)
}
}
}
| mit | 3954c5093e1eda1092f6dc1664843c0f | 39.25 | 299 | 0.666149 | 5.477937 | false | false | false | false |
zning1994/practice | Swift学习/code4xcode6/ch11/11.6.2可选链3.playground/section-1.swift | 1 | 725 | // 本书网站: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 Employee {
var no : Int = 0
var name : String = ""
var job : String = ""
var salary : Double = 0
var dept : Department? = Department()
struct Department {
var no : Int = 10
var name : String = "SALES"
}
}
var emp = Employee()
println(emp.dept?.name)
| gpl-2.0 | cb486bbfe3ac4b61ec40d8d75881e7c8 | 23.2 | 62 | 0.628099 | 2.827103 | false | false | false | false |
lyle-luan/firefox-ios | Client/Frontend/Login/LoginView.swift | 3 | 7875 | /* 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 UIKit
// TODO: Use a strings file.
private let TextLogin = "Login"
private let TextLoginLabel = "Sign in with your Firefox account"
private let TextLoginInstead = "Sign in instead"
private let TextSignUp = "Sign up"
private let TextSignUpLabel = "Create a new Firefox account"
private let TextSignUpInstead = "Sign up instead"
private let TextForgotPassword = "Forgot password?"
private let ImagePathLogo = "guidelines-logo"
private let ImagePathEmail = "email.png"
private let ImagePathPassword = "password.png"
class LoginView: UIView {
var didClickLogin: (() -> ())?
private var loginButton: UIButton!
private var loginLabel: UILabel!
private var forgotPasswordButton: UIButton!
private var switchLoginOrSignUpButton: UIButton!
private var userText: ImageTextField!
private var passText: PasswordTextField!
private var statusLabel: UILabel!
// True if showing login state; false if showing sign up state.
private var stateLogin = true
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
didInitView()
}
override init(frame: CGRect) {
super.init(frame: frame)
didInitView()
}
override init() {
// init() calls init(frame) with a 0 rect.
super.init()
}
var username: String {
get {
return userText.text
}
set(username) {
userText.text = username
}
}
var password: String {
get {
return passText.text
}
set(password) {
passText.text = password
}
}
private func didInitView() {
backgroundColor = UIColor.darkGrayColor()
// Firefox logo
let image = UIImage(named: ImagePathLogo)!
let logo = UIImageView(image: image)
addSubview(logo)
let ratio = image.size.width / image.size.height
logo.snp_makeConstraints { make in
make.top.equalTo(60)
make.centerX.equalTo(self)
make.width.equalTo(75)
make.width.equalTo(logo.snp_height).multipliedBy(ratio)
}
// 105 text
let label105 = UILabel()
label105.textColor = UIColor.whiteColor()
label105.font = UIFont(name: "HelveticaNeue-UltraLight", size: 25)
label105.text = "105"
addSubview(label105)
label105.snp_makeConstraints { make in
make.top.equalTo(logo.snp_bottom).offset(8)
make.centerX.equalTo(self)
}
// Email address
userText = ImageTextField()
userText.setLeftImage(UIImage(named: ImagePathEmail))
userText.backgroundColor = UIColor.lightGrayColor()
userText.font = UIFont(name: "HelveticaNeue-Thin", size: 14)
userText.textColor = UIColor.whiteColor()
userText.placeholder = "Email address"
userText.layer.borderColor = UIColor.whiteColor().CGColor
userText.layer.borderWidth = 1
userText.keyboardType = UIKeyboardType.EmailAddress
addSubview(userText)
userText.snp_makeConstraints { make in
make.top.equalTo(label105.snp_bottom).offset(40)
make.left.equalTo(self.snp_left)
make.right.equalTo(self.snp_right)
make.height.equalTo(30)
}
// Password
passText = PasswordTextField()
passText.setLeftImage(UIImage(named: ImagePathPassword))
passText.backgroundColor = UIColor.lightGrayColor()
passText.font = UIFont(name: "HelveticaNeue-Thin", size: 14)
passText.textColor = UIColor.whiteColor()
passText.placeholder = "Password"
passText.layer.borderColor = UIColor.whiteColor().CGColor
passText.layer.borderWidth = 1
passText.secureTextEntry = true
addSubview(passText)
passText.snp_makeConstraints { make in
make.top.equalTo(self.userText.snp_bottom).offset(-1)
make.left.equalTo(self.snp_left)
make.right.equalTo(self.snp_right)
make.height.equalTo(30)
}
// Login label
loginLabel = UILabel()
loginLabel.font = UIFont(name: "HelveticaNeue-Thin", size: 12)
loginLabel.textColor = UIColor.whiteColor()
loginLabel.text = "Sign in with your Firefox account"
addSubview(loginLabel)
loginLabel.snp_makeConstraints { make in
make.top.equalTo(self.passText.snp_bottom).offset(5)
make.centerX.equalTo(self)
}
// Login button
loginButton = UIButton()
loginButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 15)
loginButton.setTitle("Login", forState: UIControlState.Normal)
loginButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
loginButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.layer.borderWidth = 1
loginButton.layer.cornerRadius = 6
addSubview(loginButton)
loginButton.snp_makeConstraints { make in
make.top.equalTo(self.loginLabel.snp_bottom).offset(25)
make.centerX.equalTo(self)
}
// Forgot password button
forgotPasswordButton = UIButton()
forgotPasswordButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 12)
forgotPasswordButton.setTitle("Forgot password?", forState: UIControlState.Normal)
forgotPasswordButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
addSubview(forgotPasswordButton)
forgotPasswordButton.snp_makeConstraints { make in
make.top.equalTo(self.loginButton.snp_bottom).offset(25)
make.centerX.equalTo(self)
}
// Sign up or login instead button
switchLoginOrSignUpButton = UIButton()
switchLoginOrSignUpButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 12)
switchLoginOrSignUpButton.setTitle("Sign up instead", forState: UIControlState.Normal)
switchLoginOrSignUpButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
addSubview(switchLoginOrSignUpButton)
switchLoginOrSignUpButton.snp_makeConstraints { make in
make.top.equalTo(self.forgotPasswordButton.snp_bottom)
make.centerX.equalTo(self)
}
// Click listeners
switchLoginOrSignUpButton.addTarget(self, action: "SELdidClickSwitchLoginOrSignUp", forControlEvents: UIControlEvents.TouchUpInside)
forgotPasswordButton.addTarget(self, action: "SELdidClickForgotPassword", forControlEvents: UIControlEvents.TouchUpInside)
loginButton.addTarget(self, action: "SELdidClickLogin", forControlEvents: UIControlEvents.TouchUpInside)
}
func SELdidClickSwitchLoginOrSignUp() {
stateLogin = !stateLogin
if (stateLogin) {
loginButton.setTitle(TextLogin, forState: UIControlState.Normal)
loginLabel.text = TextLoginLabel
forgotPasswordButton.hidden = false
switchLoginOrSignUpButton.setTitle(TextSignUpInstead, forState: UIControlState.Normal)
} else {
loginButton.setTitle(TextSignUp, forState: UIControlState.Normal)
loginLabel.text = TextSignUpLabel
forgotPasswordButton.hidden = true
switchLoginOrSignUpButton.setTitle(TextLoginInstead, forState: UIControlState.Normal)
}
}
func SELdidClickForgotPassword() {
}
func SELdidClickLogin() {
didClickLogin?()
}
}
| mpl-2.0 | 28022ef2b267b7c74d0a324f31414d0f | 37.043478 | 140 | 0.663111 | 4.897388 | false | false | false | false |
kean/Nuke | Tests/NukeTests/ImagePrefetcherTests.swift | 1 | 8164 | // The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).
import XCTest
@testable import Nuke
final class ImagePrefetcherTests: XCTestCase {
private var pipeline: ImagePipeline!
private var dataLoader: MockDataLoader!
private var dataCache: MockDataCache!
private var imageCache: MockImageCache!
private var observer: ImagePipelineObserver!
private var prefetcher: ImagePrefetcher!
override func setUp() {
super.setUp()
dataLoader = MockDataLoader()
dataCache = MockDataCache()
imageCache = MockImageCache()
observer = ImagePipelineObserver()
pipeline = ImagePipeline(delegate: observer) {
$0.dataLoader = dataLoader
$0.imageCache = imageCache
$0.dataCache = dataCache
}
prefetcher = ImagePrefetcher(pipeline: pipeline)
}
override func tearDown() {
super.tearDown()
observer = nil
}
// MARK: Basics
/// Start prefetching for the request and then request an image separarely.
func testBasicScenario() {
dataLoader.isSuspended = true
expect(prefetcher.queue).toEnqueueOperationsWithCount(1)
prefetcher.startPrefetching(with: [Test.url])
wait()
expect(pipeline).toLoadImage(with: Test.url)
pipeline.queue.async {
self.dataLoader.isSuspended = false
}
wait()
// THEN
XCTAssertEqual(dataLoader.createdTaskCount, 1)
XCTAssertEqual(observer.startedTaskCount, 2)
}
// MARK: Start Prefetching
func testStartPrefetching() {
expectPrefetcherToComplete()
// WHEN
prefetcher.startPrefetching(with: [Test.url])
wait()
// THEN image saved in both caches
XCTAssertNotNil(pipeline.cache[Test.request])
XCTAssertNotNil(pipeline.cache.cachedData(for: Test.request))
}
func testStartPrefetchingWithTwoEquivalentURLs() {
dataLoader.isSuspended = true
expectPrefetcherToComplete()
// WHEN
prefetcher.startPrefetching(with: [Test.url])
prefetcher.startPrefetching(with: [Test.url])
pipeline.queue.async {
self.dataLoader.isSuspended = false
}
wait()
// THEN only one task is started
XCTAssertEqual(observer.startedTaskCount, 1)
}
func testWhenImageIsInMemoryCacheNoTaskStarted() {
dataLoader.isSuspended = true
// GIVEN
pipeline.cache[Test.request] = Test.container
// WHEN
prefetcher.startPrefetching(with: [Test.url])
pipeline.queue.sync {}
// THEN
XCTAssertEqual(observer.startedTaskCount, 0)
}
// MARK: Stop Prefetching
func testStopPrefetching() {
dataLoader.isSuspended = true
// WHEN
let url = Test.url
expectNotification(ImagePipelineObserver.didStartTask, object: observer)
prefetcher.startPrefetching(with: [url])
wait()
expectNotification(ImagePipelineObserver.didCancelTask, object: observer)
prefetcher.stopPrefetching(with: [url])
wait()
}
// MARK: Destination
func testStartPrefetchingDestinationDisk() {
// GIVEN
pipeline = pipeline.reconfigured {
$0.makeImageDecoder = { _ in
XCTFail("Expect image not to be decoded")
return nil
}
}
prefetcher = ImagePrefetcher(pipeline: pipeline, destination: .diskCache)
expectPrefetcherToComplete()
// WHEN
prefetcher.startPrefetching(with: [Test.url])
wait()
// THEN image saved in both caches
XCTAssertNil(pipeline.cache[Test.request])
XCTAssertNotNil(pipeline.cache.cachedData(for: Test.request))
}
// MARK: Pause
func testPausingPrefetcher() {
// WHEN
prefetcher.isPaused = true
prefetcher.startPrefetching(with: [Test.url])
let expectation = self.expectation(description: "TimePassed")
pipeline.queue.asyncAfter(deadline: .now() + .milliseconds(10)) {
expectation.fulfill()
}
wait()
// THEN
XCTAssertEqual(observer.startedTaskCount, 0)
}
// MARK: Priority
func testDefaultPrioritySetToLow() {
// WHEN start prefetching with URL
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
prefetcher.startPrefetching(with: [Test.url])
wait()
// THEN priority is set to .low
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
XCTAssertEqual(operation.queuePriority, .low)
// Cleanup
prefetcher.stopPrefetching()
}
func testDefaultPriorityAffectsRequests() {
// WHEN start prefetching with ImageRequest
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
let request = Test.request
XCTAssertEqual(request.priority, .normal) // Default is .normal
prefetcher.startPrefetching(with: [request])
wait()
// THEN priority is set to .low
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
XCTAssertEqual(operation.queuePriority, .low)
}
func testLowerPriorityThanDefaultNotAffected() {
// WHEN start prefetching with ImageRequest with .veryLow priority
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
var request = Test.request
request.priority = .veryLow
prefetcher.startPrefetching(with: [request])
wait()
// THEN priority is set to .low (prefetcher priority)
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
XCTAssertEqual(operation.queuePriority, .low)
}
func testChangePriority() {
// GIVEN
prefetcher.priority = .veryHigh
// WHEN
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
prefetcher.startPrefetching(with: [Test.url])
wait()
// THEN
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
XCTAssertEqual(operation.queuePriority, .veryHigh)
}
func testChangePriorityOfOutstandingTasks() {
// WHEN
pipeline.configuration.dataLoadingQueue.isSuspended = true
let observer = expect(pipeline.configuration.dataLoadingQueue).toEnqueueOperationsWithCount(1)
prefetcher.startPrefetching(with: [Test.url])
wait()
guard let operation = observer.operations.first else {
return XCTFail("Failed to find operation")
}
// WHEN/THEN
expect(operation).toUpdatePriority(from: .low, to: .veryLow)
prefetcher.priority = .veryLow
wait()
}
// MARK: Misc
func testThatAllPrefetchingRequestsAreStoppedWhenPrefetcherIsDeallocated() {
pipeline.configuration.dataLoadingQueue.isSuspended = true
let request = Test.request
expectNotification(ImagePipelineObserver.didStartTask, object: observer)
prefetcher.startPrefetching(with: [request])
wait()
expectNotification(ImagePipelineObserver.didCancelTask, object: observer)
autoreleasepool {
prefetcher = nil
}
wait()
}
func expectPrefetcherToComplete() {
let expectation = self.expectation(description: "PrefecherDidComplete")
prefetcher.didComplete = {
expectation.fulfill()
}
}
}
| mit | d2b1955666ae697ff64e1c9899e0bd07 | 29.462687 | 102 | 0.646742 | 5.346431 | false | true | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.